http://stackoverflow.com/q/49865952
has title: Implementing Gradient Descent In Python and receiving an overflow error
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/86750214
accepted answer: http://stackoverflow.com/a/49869703
favorite count: 0
has answer: http://stackoverflow.com/a/49869703
type: Question
has body: Gradient Descent and Overflow Error I am currently implementing vectorized gradient descent in python. However, I continue to get an overflow error. The numbers in my dataset are not extremely large though. I am using this formula: I choose this implementation to avoid using derivatives. Does anyone have any suggestion on how to remedy this problem or am I implementing it wrong? Thank you in advance! Dataset Link: https://www.kaggle.com/CooperUnion/anime-recommendations-database/data ## Cleaning Data ## import math import matplotlib.pyplot as plt import numpy as np import pandas as pd data = pd.read_csv('anime.csv') # print(data.corr()) # print(data['members'].isnull().values.any()) # Prints False # print(data['rating'].isnull().values.any()) # Prints True members = [] # Corresponding fan club size for row ratings = [] # Corresponding rating for row for row in data.iterrows(): if not math.isnan(row[1]['rating']): # Checks for Null ratings members.append(row[1]['members']) ratings.append(row[1]['rating']) plt.plot(members, ratings) plt.savefig('scatterplot.png') theta0 = 0.3 # Random guess theta1 = 0.3 # Random guess error = 0 Formula's def hypothesis(x, theta0, theta1): return theta0 + theta1 * x def costFunction(x, y, theta0, theta1, m): loss = 0 for i in range(m): # Represents summation loss += (hypothesis(x[i], theta0, theta1) - y[i])**2 loss *= 1 / (2 * m) # Represents 1/2m return loss def gradientDescent(x, y, theta0, theta1, alpha, m, iterations=1500): for i in range(iterations): gradient0 = 0 gradient1 = 0 for j in range(m): gradient0 += hypothesis(x[j], theta0, theta1) - y[j] gradient1 += (hypothesis(x[j], theta0, theta1) - y[j]) * x[j] gradient0 *= 1/m gradient1 *= 1/m temp0 = theta0 - alpha * gradient0 temp1 = theta1 - alpha * gradient1 theta0 = temp0 theta1 = temp1 error = costFunction(x, y, theta0, theta1, len(y)) print("Error is:", error) return theta0, theta1 print(gradientDescent(members, ratings, theta0, theta1, 0.01, len(ratings))) Error's After sev…
has comment: http://stackoverflow.com/comment/86749783
score: 3
tagged with: gradient-descent
has comment: http://stackoverflow.com/comment/86749794
has comment: http://stackoverflow.com/comment/86748616
tagged with: loss-function
tagged with: python
has comment: http://stackoverflow.com/comment/86753875
tagged with: artificial-intelligence
possible better answer: http://stackoverflow.com/a/51848489
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86747304
answer count: 2
has answer: http://stackoverflow.com/a/51848489
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/86733563
score: 0
type: Comment
has text: 'my \t test \n text' output: 'my test text'
type: QuestionComment
comment on: http://stackoverflow.com/q/49854755

http://stackoverflow.com/comment/86672766
type: QuestionComment
comment on: http://stackoverflow.com/q/49828534
type: Comment
has text: Which version of Python?
score: 0

http://stackoverflow.com/comment/86749579
comment on: http://stackoverflow.com/q/49866785
type: Comment
type: QuestionComment
has text: This works for me. could you double check the indentation here? Are you definitely on the rewrite branch?
score: 0

http://stackoverflow.com/comment/86936934
comment on: http://stackoverflow.com/a/49890075
score: 0
has text: Note that the fio line given in this answer doesn't have direct=1 thus there is a chance all the I/O could be satisfied by the kernel's buffer cache which may not be desired and could distort the results...
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86644227
comment on: http://stackoverflow.com/a/49805739
type: Comment
score: 0
type: AnswerComment
has text: Thank you for your answer. I just wanted to know the details of the function. Thank you so much.

http://stackoverflow.com/comment/86557296
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49767414
score: 0
has text: The buffer affects mainly the performance. It makes a difference in overhead if you can get the same data in 1 large, 10 medium or say 50 small blocks where each block is a network packet to be sent and received and then acknowledged by another network packet.

http://stackoverflow.com/q/49908986
has comment: http://stackoverflow.com/comment/86834480
has title: How to make all combinations of many functions in python?
score: 1
has comment: http://stackoverflow.com/comment/86834102
has answer: http://stackoverflow.com/a/49909338
tagged with: python
has body: So i have x = 3 def first(x): return x+2 def second(x): return x/2 def third(x): return x*4 I would like to make a pipe of functions like : first -> second -> third but all combinations of functions : like first -> second , first -> third and get each time the value of x for each combination. And i don't need not only to multiply them but to be able to make multiple combination of various length. Here it's just fixed number of combination : How to multiply functions in python? regards and thanks
linked to: http://stackoverflow.com/q/30195045
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49909338

http://stackoverflow.com/comment/86703717
comment on: http://stackoverflow.com/a/49841295
has text: I get this error: line 20, in collect_websocket @wraps(func) NameError: name 'wraps' is not defined, Is there something im missing?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49869955
accepted answer of: http://stackoverflow.com/q/49869895
has body: There are two mistakes in your code. First, this: def get_list(self): self.student_list should be: def get_list(self): return self.student_list Second, you're using the class StudentRepo where you should be using an instance of StudentRepo: s1 = Student("A", 10) s2 = Student("B", 11) my_roster = StudentRepo() my_roster.add(s1) my_roster.add(s2) studentList = my_roster.get_list() for student in studentList: print(student.name)
type: Answer
answers question: http://stackoverflow.com/q/49869895
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3

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

http://stackoverflow.com/comment/86855284
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49911831
has text: The files are just data. The visualization of glyph is done by font, and do no matter such files. Unicode, programs (so also your vim), etc. can handle undefined characters without problems.
score: 1

http://stackoverflow.com/comment/86572236
type: QuestionComment
score: 0
has text: I need the text not to be highlighted.
comment on: http://stackoverflow.com/q/49777682
type: Comment

http://stackoverflow.com/q/49791364
has comment: http://stackoverflow.com/comment/86598353
type: Question
has comment: http://stackoverflow.com/comment/86617993
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49791869
has comment: http://stackoverflow.com/comment/86597648
type: UnansweredQuestion
answer count: 1
tagged with: python
favorite count: 0
downvote count: 0
tagged with: http://stackoverflow.com/tag/csv
has body: I am trying to use python's csv standard library module to generate comma-separated value (csv) files. It will not allow the first line to be blank. More annoyingly, it treats the first line differently from other lines, so an empty list gives an empty string ("") in one case and a blank line thereafter: import csv import io def make_csv(rows): with io.StringIO(newline='') as sout: writer = csv.writer(sout, quoting=csv.QUOTE_MINIMAL) writer.writerows(rows) return sout.getvalue() Given the above definition, an interpreter session might look like: &gt;&gt;&gt; make_csv([[''], ['']]) # (only the) first line has quoted empty string '""\r\n\r\n' &gt;&gt;&gt; make_csv([['A'], ['A']]) # expected: same input row, same output row 'A\r\nA\r\n' Why does this quoted empty string happen only on the first line? Is there any way I can stop it, or at least get more consistent behavior? Update: this is a bug reported in Dec 2017 as https://bugs.python.org/issue32255, and resolved by commit https://github.com/python/cpython/commit/2001900b0c02a397d8cf1d776a7cc7fcb2a463e3, which was included in the 3.6.5 release
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86597725
has title: Python csv writer adds quotes on empty first line, but not subsequent lines
has comment: http://stackoverflow.com/comment/86597566

http://stackoverflow.com/comment/86624986
type: Comment
comment on: http://stackoverflow.com/q/49805007
type: QuestionComment
has text: Have a look at [time.sleep()](https://docs.python.org/3/library/time.html#time.sleep) to wait a little in your loop.
score: 2

http://stackoverflow.com/a/49821975
has body: First filter guest_list by the column of Boolean values attending. Second check if the attending names from guest_list exist in CONTACTS CONTACTS[CONTACTS.name.isin(guest_list.loc[guest_list.attending,'guest_name'])] name phone 0 Alice 007 1 Alice 1764 3 Charlie 314159
accepted answer of: http://stackoverflow.com/q/49821843
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49821843
upvote count: 1

http://stackoverflow.com/comment/87845738
score: 0
type: AnswerComment
has text: thanks, I did notice that one, but it's string, no need to convert to datetime format.
type: Comment
comment on: http://stackoverflow.com/a/50414656

http://stackoverflow.com/comment/86827572
has text: How would you like to refer to each motor? By name? robot.motor[name]? If you really want to make it as readable as possible, perhaps you should have this done by the robot class as methods where robot class calls methonds on the motor class which includes your tool methods. Which would look like Robot.go_forward(time?), it has way more sense than calling each motor, as is a user friendly interface.
type: Comment
comment on: http://stackoverflow.com/a/49904426
score: 0
type: AnswerComment

http://stackoverflow.com/a/49805176
score: -6
downvote count: 7
has body: You don't have a cursor in Flask SQLAlchemy because it's an ORM. Methods exist to perform actions on the database directly, unlike packages like SQLite. Check the documentation for more info on these. To execute SQL queries directly, you'd have to run them through the terminal directly through whichever RDBMS you're using (MySQL, PostgreSQL, etc.)
has comment: http://stackoverflow.com/comment/101189305
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49797786

http://stackoverflow.com/comment/86879541
score: 0
has text: Hello again, I ran into an unexpected problem, can you see my updated question (the "EDIT" part)?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49887670

http://stackoverflow.com/q/49833487
has comment: http://stackoverflow.com/comment/86683383
tagged with: http://stackoverflow.com/tag/csv
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49833547
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86682324
type: UnansweredQuestion
tagged with: data-visualization
tagged with: python
score: -1
has title: how can i arrange numbers inside csv file in ascending order and split it in seperate cells
has body: I have data in csv file where the format of the data looks as follow 30:2,29:3,28:2,13:3,12:3,5:5,10:4,4:4,11:2,3:3,1:4,2:4,31:,32:4,6:5,9:5,7:2,8:3,22:3,21:3,18:4,16:2,20:4,19:4,23:2,27:4,14:2,26:2,24:3,25:3 These are questions with answers. The digit before : represent question number and the digit after it represent answer to it. I want to write a python program for it so that this array is arranged in ascending order according to question number. I also want to split questions into separate column. Please help me.

http://stackoverflow.com/q/49835277
upvote count: 1
has title: exception without explicit reason when deploying U-SQL jobs to Azure by Python SDK
has answer: http://stackoverflow.com/a/50308714
has comment: http://stackoverflow.com/comment/86686888
favorite count: 0
has comment: http://stackoverflow.com/comment/86686594
type: Question
has comment: http://stackoverflow.com/comment/86686539
tagged with: u-sql
has comment: http://stackoverflow.com/comment/86686511
type: UnansweredQuestion
tagged with: azure
has comment: http://stackoverflow.com/comment/86685765
tagged with: python
has comment: http://stackoverflow.com/comment/87633568
score: 1
answer count: 1
downvote count: 0
has body: I am using python SDK to submit jobs to Azure using adlaJobClient , I have around 30 dynamic USQLs constructed using JINJA2, which I am populating in a list and then pushing them off to Azure using adlaJobClient one by one, The problem which I am facing is after a random number of successful deployments python throws an exception in the program console without any further explanation.there is no instance of U-SQL job failure in Azure either , below mentioned is error stack trace in python , when I run the same U-SQL query,which I am generating dynamically.. for which the execution is stopping it runs without fail in Azure (manually) ***** starting query number **** 24 Job is not yet done, waiting for 3 seconds. Current state: Compiling Job is not yet done, waiting for 3 seconds. Current state: Compiling Job is not yet done, waiting for 3 seconds. Current state: Compiling Job is not yet done, waiting for 3 seconds. Current state: starting Job is not yet done, waiting for 3 seconds. Current state: starting An exception has occurred, use %tb to see the full traceback. SystemExit: 1 for script in sql_query_list: jobId = str(uuid.uuid4()) jobResult = adlaJobClient.job.create(adla,jobId,JobInformation(name='Submit ADLA Job '+jobId,type='USql',properties=USqlJobProperties(script=script))) try: while(jobResult.state != JobState.ended): print('Job is not yet done, waiting for 3 seconds. Current state: ' + jobResult.state.value) time.sleep(3) jobResult = adlaJobClient.job.get(adla, jobId) print(' ******* JOB ID ********',jobId) print("****QUERY no FINISHED *****",sql_query_list.index(script)) print ('**** JOB ID RESULT: ****** ' + jobResult.result.value) except Exception as e: raise ValueError print ("xxxxxx JOB SUBMISSION TO ADLA FAILED xxxxxxx") print(e)

http://stackoverflow.com/comment/86832191
has text: Please show something you think should work, but doesn't. Remember that Stack Overflow is not a homework-answering site.
type: Comment
comment on: http://stackoverflow.com/q/49908163
type: QuestionComment
score: 2

http://stackoverflow.com/a/49832435
answers question: http://stackoverflow.com/q/49832185
type: Answer
score: 4
has body: Finding Nth largest indices An efficient one could use np.argparition that skips sorting and simply parititions, which when sliced would give us the required indices. We would also generalize it to find Nth largest one along a specified axis or a global one (similar to ndarray.argmax()), like so - def argNmax(a, N, axis=None): if axis is None: return np.argpartition(a.ravel(), -N)[-N] else: return np.take(np.argpartition(a, -N, axis=axis), -N, axis=axis) Sample runs - In [66]: a Out[66]: array([[908, 770, 258, 534], [399, 376, 808, 750], [655, 654, 825, 355]]) In [67]: argNmax(a, N=2, axis=0) Out[67]: array([2, 2, 1, 0]) In [68]: argNmax(a, N=2, axis=1) Out[68]: array([1, 3, 0]) In [69]: argNmax(a, N=2) # global second largest index Out[69]: 10 Finding Nth smallest indices Extending this to find the Nth smallest one along an axis or globally, we would have - def argNmin(a, N, axis=None): if axis is None: return np.argpartition(a.ravel(), N-1)[N-1] else: return np.take(np.argpartition(a, N-1, axis=axis), N-1, axis=axis) Sample runs - In [105]: a Out[105]: array([[908, 770, 258, 534], [399, 376, 808, 750], [655, 654, 825, 355]]) In [106]: argNmin(a, N=2, axis=0) Out[106]: array([2, 2, 1, 0]) In [107]: argNmin(a, N=2, axis=1) Out[107]: array([3, 0, 1]) In [108]: argNmin(a, N=2) Out[108]: 11 Timings To give a perspective on the benefit on using argpartition over actual sorting with argsort as shown in @pythonic833's post, here's a quick runtime test on the global argmax version - In [70]: a = np.random.randint(0,99999,(1000,1000)) In [72]: %timeit np.argsort(a)[-2] # @pythonic833's soln 10 loops, best of 3: 40.6 ms per loop In [73]: %timeit argNmax(a, N=2) 100 loops, best of 3: 2.12 ms per loop
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86680677
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49832185
upvote count: 4

http://stackoverflow.com/comment/86836952
comment on: http://stackoverflow.com/a/49888913
type: AnswerComment
score: 0
has text: I built a little mass calculator of my own cause I randomly felt like it: https://www.pastebucket.com/566011
type: Comment

http://stackoverflow.com/comment/86595590
has text: Thank you I will try my best to implement this and get back to you.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49790392

http://stackoverflow.com/comment/86666293
has text: should it be `v.replace('”','"')` ?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49825205

http://stackoverflow.com/q/49863141
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49863217
type: Question
has comment: http://stackoverflow.com/comment/86741461
tagged with: datetime
has title: python pandas: remove part of date time object (datetime64[ns])
tagged with: python
has body: I have a pandas dataframe , and I am trying to remove the day and time part of a date time column (i.e. only keep the year and month part). I did the following: df['my_date_new'] = pd.to_datetime(df['my_date'].dt.year, df['my_date'].dt.month, 0) but got the following error: TypeError: invalid type comparison What did I do wrong here and how could I fix this?
tagged with: python-2.7
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/86827184
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49863260

http://stackoverflow.com/comment/86692395
has text: Doesn't command need to be a list?
comment on: http://stackoverflow.com/a/49838693
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49907981
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86832688
type: Answer
accepted answer of: http://stackoverflow.com/q/49907021
has comment: http://stackoverflow.com/comment/87962921
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49907021
has body: Or maybe df.groupby('col1').col2.apply(lambda x : (x.diff().eq(1))).map({True:2,False:1}) Out[1148]: 0 1 1 2 2 2 3 1 4 2 5 1 6 1 7 1 Name: col2, dtype: int64

http://stackoverflow.com/q/49787860
has body: I have gone through already available answers in SO but nothing seems working for me. I am following python commands to upload my package(Note: I am a new user and have registered the account with username and password): Create setup.py: from setuptools import setup setup( name='', # This is the name of your PyPI-package. version='0.1', # Update the version number for new releases scripts=[''] # The name of your script, and also the command you'll be using for calling it ) Package the script: python setup.py sdist Register the account: python setup.py register This prompted me below message(I choose 2nd as I am new user): 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: Upload the package: python setup.py sdist upload After trying steps I got the error while uploading: Upload failed (403): Invalid or non-existent authentication information. error: Upload failed (403): Invalid or non-existent authentication information.
possible better answer: http://stackoverflow.com/a/49939966
has title: Not able to upload package in https://upload.pypi.org/legacy/
has comment: http://stackoverflow.com/comment/86924888
score: 6
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49940613
has comment: http://stackoverflow.com/comment/86840054
has answer: http://stackoverflow.com/a/49939966
has comment: http://stackoverflow.com/comment/86842751
has comment: http://stackoverflow.com/comment/86840140
has answer: http://stackoverflow.com/a/49954315
tagged with: python
accepted answer: http://stackoverflow.com/a/49954315
has answer: http://stackoverflow.com/a/66913948
answer count: 4
upvote count: 8
type: Question
tagged with: python-3.x
downvote count: 2

http://stackoverflow.com/comment/86819094
score: 1
type: AnswerComment
has text: Yes the scan doesn't start until the source is complete like in your original code. That's the reason why you need a buffer. Backpressure is a tool to handle this kind of situation where you have a fast source and a slow observer. But you have a risk of overflowing the memory if messages keep stacking up. Adapting to python seem to be a lot of work. You may want to check out https://github.com/MichaelSchneeberger/rxbackpressure
type: Comment
comment on: http://stackoverflow.com/a/49900723

http://stackoverflow.com/comment/86567871
type: Comment
comment on: http://stackoverflow.com/a/49776053
type: AnswerComment
has text: Maybe is there another method to achieve the same result?
score: 0

python
tags question: http://stackoverflow.com/q/49793006
tags question: http://stackoverflow.com/q/49815709
tags question: http://stackoverflow.com/q/49867553
tags question: http://stackoverflow.com/q/49764481
tags question: http://stackoverflow.com/q/49771711
tags question: http://stackoverflow.com/q/49872005
tags question: http://stackoverflow.com/q/49903830
tags question: http://stackoverflow.com/q/49812284
tags question: http://stackoverflow.com/q/49819504
tags question: http://stackoverflow.com/q/49769137
tags question: http://stackoverflow.com/q/49760712
tags question: http://stackoverflow.com/q/49767573
tags question: http://stackoverflow.com/q/49759259
tags question: http://stackoverflow.com/q/49863759
tags question: http://stackoverflow.com/q/49808508
tags question: http://stackoverflow.com/q/49817574
tags question: http://stackoverflow.com/q/49816754
tags question: http://stackoverflow.com/q/49791606
tags question: http://stackoverflow.com/q/49850821
tags question: http://stackoverflow.com/q/49889939
tags question: http://stackoverflow.com/q/49827112
tags question: http://stackoverflow.com/q/49788464
tags question: http://stackoverflow.com/q/49880150
tags question: http://stackoverflow.com/q/49807881
tags question: http://stackoverflow.com/q/49832606
tags question: http://stackoverflow.com/q/49758961
tags question: http://stackoverflow.com/q/49905497
tags question: http://stackoverflow.com/q/49785133
tags question: http://stackoverflow.com/q/49852972
tags question: http://stackoverflow.com/q/49798491
tags question: http://stackoverflow.com/q/49783137
tags question: http://stackoverflow.com/q/49833270
tags question: http://stackoverflow.com/q/49791658
tags question: http://stackoverflow.com/q/49863060
tags question: http://stackoverflow.com/q/49776490
tags question: http://stackoverflow.com/q/49889702
tags question: http://stackoverflow.com/q/49848978
tags question: http://stackoverflow.com/q/49900685
tags question: http://stackoverflow.com/q/49875621
tags question: http://stackoverflow.com/q/49861721
tags question: http://stackoverflow.com/q/49826581
tags question: http://stackoverflow.com/q/49787118
tags question: http://stackoverflow.com/q/49758413
tags question: http://stackoverflow.com/q/49871187
tags question: http://stackoverflow.com/q/49794713
tags question: http://stackoverflow.com/q/49846343
tags question: http://stackoverflow.com/q/49908089
tags question: http://stackoverflow.com/q/49784513
tags question: http://stackoverflow.com/q/49819451
tags question: http://stackoverflow.com/q/49806651
tags question: http://stackoverflow.com/q/49788801
tags question: http://stackoverflow.com/q/49835791
tags question: http://stackoverflow.com/q/49867908
tags question: http://stackoverflow.com/q/49892145
tags question: http://stackoverflow.com/q/49789861
tags question: http://stackoverflow.com/q/49906109
tags question: http://stackoverflow.com/q/49845774
tags question: http://stackoverflow.com/q/49883476
tags question: http://stackoverflow.com/q/49863598
tags question: http://stackoverflow.com/q/49817786
tags question: http://stackoverflow.com/q/49880306
tags question: http://stackoverflow.com/q/49842164
tags question: http://stackoverflow.com/q/49814301
tags question: http://stackoverflow.com/q/49802301
tags question: http://stackoverflow.com/q/49858094
tags question: http://stackoverflow.com/q/49759710
tags question: http://stackoverflow.com/q/49810960
tags question: http://stackoverflow.com/q/49761879
tags question: http://stackoverflow.com/q/49896802
tags question: http://stackoverflow.com/q/49882563
tags question: http://stackoverflow.com/q/49866677
tags question: http://stackoverflow.com/q/49763476
tags question: http://stackoverflow.com/q/49901435
tags question: http://stackoverflow.com/q/49778057
tags question: http://stackoverflow.com/q/49886985
tags question: http://stackoverflow.com/q/49889819
tags question: http://stackoverflow.com/q/49825205
tags question: http://stackoverflow.com/q/49890639
tags question: http://stackoverflow.com/q/49899973
tags question: http://stackoverflow.com/q/49775998

http://stackoverflow.com/a/49799637
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86616702
accepted answer of: http://stackoverflow.com/q/49796314
answers question: http://stackoverflow.com/q/49796314
type: Answer
has comment: http://stackoverflow.com/comment/86615266
has body: The already mentioned FuncAnimation has a parameter frame that the animation function can use an index: import matplotlib.pyplot as plt import matplotlib.animation as anim fig = plt.figure() x=[20,23,25,27,29,31] y=[10,12,14,16,17,19] t=[2,9,1,4,3,9] #create index list for frames, i.e. how many cycles each frame will be displayed frame_t = [] for i, item in enumerate(t): frame_t.extend([i] * item) def init(): fig.clear() #animation function def animate(i): #prevent autoscaling of figure plt.xlim(15, 35) plt.ylim( 5, 25) #set new point plt.scatter(x[i], y[i], c = "b") #animate scatter plot ani = anim.FuncAnimation(fig, animate, init_func = init, frames = frame_t, interval = 100, repeat = True) plt.show() Equivalently, you could store the same frame several time in the ArtistAnimation list. Basically the flipbook approach. Sample output:
has comment: http://stackoverflow.com/comment/86616322
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/86707904
score: 0
type: Comment
has text: When you say "predict" - are you actually trying to use some kind of predictive model? Or is this literally just matching the x-values?
type: QuestionComment
comment on: http://stackoverflow.com/q/49846434

http://stackoverflow.com/q/49874289
type: Question
has comment: http://stackoverflow.com/comment/86764502
has comment: http://stackoverflow.com/comment/86764670
tagged with: python
possible better answer: http://stackoverflow.com/a/49874779
has answer: http://stackoverflow.com/a/49874779
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/49874915
has body: I have a JSON object which I want to flatten before exporting it to CSV. I'd like to use the flatten_json module for this. My JSON input looks like this: { "responseStatus": "SUCCESS", "responseDetails": { "total": 5754 }, "data": [ { "id": 1324651 }, { "id": 5686131 }, { "id": 2165735 }, { "id": 2133256 } ] } Easy so far even for a beginner like me, but what I'm interesting in exporting is only the data array. So, I would think of this: data_json = json["data"] flat_json = flatten_json.flatten(data_json) Which doesn't work, since data is an array, stored as a list in Python, not as a dictionary: [ { "id": 1324651 }, { "id": 5686131 }, { "id": 2165735 }, { "id": 2133256 } ] How should I proceed to feed the content of the data array into the flatten_json function? Thanks! R.
has title: Flattening an array in a JSON object
has answer: http://stackoverflow.com/a/49874915

http://stackoverflow.com/q/49889088
has body: The following is my code. I have been trying to fix the code to perform dictionary attack on a hash (SHA-1) and I am getting the following result. P.S. I am a beginner to coding. import hashlib import random #plug in the hash that needs to be cracked hash_to_crack = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8" #direct the location of the dictionary file dict_file = "C:/Users/kiran/AppData/Local/Programs/Python/Python37/dictionary.txt" def main(): with open(dict_file) as fileobj: for line in fileobj: line = line.strip() if hashlib.sha1(line.encode()).hexdigest() == hash_to_crack: print ("The password is %s") % (line); return "" print ("Failed to crack the hash!") return "" if __name__ == "__main__": main() The result: RESTART: C:/Users/kiran/AppData/Local/Programs/Python/Python37/Codes/datest1.py The password is %s Traceback (most recent call last): File "C:/Users/kiran/AppData/Local/Programs/Python/Python37/Codes/datest1.py", line 20, in &lt;module&gt; main() File "C:/Users/kiran/AppData/Local/Programs/Python/Python37/Codes/datest1.py", line 13, in main print ("The password is %s") % (line); TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'
has comment: http://stackoverflow.com/comment/86794292
possible better answer: http://stackoverflow.com/a/49889131
type: Question
tagged with: dictionary-attack
answer count: 2
tagged with: hash
has title: Dictionary attack on SHA1 hash
has comment: http://stackoverflow.com/comment/86794299
tagged with: python
has answer: http://stackoverflow.com/a/49889131
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49889128
score: 0
tagged with: sha1
has answer: http://stackoverflow.com/a/49889128

http://stackoverflow.com/comment/86816667
score: 0
comment on: http://stackoverflow.com/q/49900621
type: QuestionComment
has text: You can use current timestamp.
type: Comment

http://stackoverflow.com/comment/87381492
has text: maybe you can come up with a [mcve] of what you have tried?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49866506

http://stackoverflow.com/q/49905006
has answer: http://stackoverflow.com/a/49906935
tagged with: forms
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/49907414
linked to: http://stackoverflow.com/q/19506105
linked to: http://stackoverflow.com/q/10251724
has comment: http://stackoverflow.com/comment/86840907
has comment: http://stackoverflow.com/comment/86840943
tagged with: python
tagged with: flask
possible better answer: http://stackoverflow.com/a/49907414
has body: I'm using Flask and SQLAlchemy and I would like to write an HTML form to perform a database update. However, I would like the user to build the query for convenience: from a select the user selects the column to be modified, in an input he inserts the new value, from a second select he selects the column for the where clause and in the last input text he inserts the value of the condition. From a logical point of view I thought of something like this: exhb = Exhibition.query.filter_by (request.form.get ('wh') = request.form ['cond']). first () exhb.request.form.get ('columns') = Request.Form ['val'] db.session.commit () But it returns: SyntaxError: keyword can not be an expression I tried to use two variables to assign wh and columns but, although the value are read correctly, it returns me: Entity '&lt;class' connect.Exhibition '&gt;' has no property 'wh' How can I then simply get the name of the two columns to be used in the query? Are there any built-in methods to do this?
type: AnsweredQuestion
score: 0
answer count: 2
has title: python - Handle column names in form for update query with Flask-SQLAlchemy
accepted answer: http://stackoverflow.com/a/49906935

http://stackoverflow.com/comment/91773596
type: Comment
type: QuestionComment
score: 0
has text: This question appears to have been abandoned, with requests for clarification left hanging. I wonder if it can be closed as Unclear?
comment on: http://stackoverflow.com/q/49873433

http://stackoverflow.com/q/49891686
upvote count: 9
has title: Can't pickle _thread.lock objects Pyspark send request to elasticseach
has comment: http://stackoverflow.com/comment/86800586
has comment: http://stackoverflow.com/comment/86799702
tagged with: pyspark
has comment: http://stackoverflow.com/comment/86799834
tagged with: python
has comment: http://stackoverflow.com/comment/86800069
has comment: http://stackoverflow.com/comment/86800239
type: AnsweredQuestion
has body: I am using pyspark streaming to collect data from tweepy. After all the set up, I send the dict(json) to elasticsearch via elasticsearch.index(). But I get "can't pickle_thread.lock objects" error and other 63 errors. The track back log is too long to show in my console! The design is that I get a json/dict type file, convert it into an DStream, add another feature names "sentiment" to it by calling TextBlob in a map() function. It all works fine, but when I add another map function to call elasticsearch.index(), I get the error. Below is the part of the super long error log in my console. Blockquote During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/ayane/anaconda/lib/python3.6/site-packages/pyspark/streaming/util.py", line 105, in dumps func.func, func.rdd_wrap_func, func.deserializers))) File "/Users/ayane/anaconda/lib/python3.6/site-packages/pyspark/serializers.py", line 460, in dumps return cloudpickle.dumps(obj, 2) File "/Users/ayane/anaconda/lib/python3.6/site-packages/pyspark/cloudpickle.py", line 704, in dumps cp.dump(obj) File "/Users/ayane/anaconda/lib/python3.6/site-packages/pyspark/cloudpickle.py", line 162, in dump raise pickle.PicklingError(msg) _pickle.PicklingError: Could not serialize object: TypeError: can't pickle _thread.lock objects at org.apache.spark.streaming.api.python.PythonTransformFunctionSerializer$.serialize(PythonDStream.scala:144) at org.apache.spark.streaming.api.python.TransformFunction$$anonfun$writeObject$1.apply$mcV$sp(PythonDStream.scala:101) at org.apache.spark.streaming.api.python.TransformFunction$$anonfun$writeObject$1.apply(PythonDStream.scala:100) at org.apache.spark.streaming.api.python.TransformFunction$$anonfun$writeObject$1.apply(PythonDStream.scala:100) at org.apache.spark.util.Utils$.tryOrIOException(Utils.scala:1303) ... 63 more Part of my code looks like this: def sendPut(doc): res = es.index(index = "tweetrepository", doc_type= 'tweet', body = doc) …
downvote count: 0
tagged with: apache-spark
tagged with: elasticsearch
answer count: 1
has comment: http://stackoverflow.com/comment/86800789
has comment: http://stackoverflow.com/comment/86800116
has answer: http://stackoverflow.com/a/49901792
accepted answer: http://stackoverflow.com/a/49901792
favorite count: 0
has comment: http://stackoverflow.com/comment/86799536
score: 9
type: Question

http://stackoverflow.com/comment/86831847
type: Comment
comment on: http://stackoverflow.com/a/49901441
type: AnswerComment
has text: What do you mean "removes the first value"? Just remove the `if key!=name` check
score: 0

utf
tag name: utf
tags question: http://stackoverflow.com/q/49769903
type: Tag

http://stackoverflow.com/q/49763560
possible better answer: http://stackoverflow.com/a/49763644
tagged with: iterator
answer count: 3
upvote count: 0
tagged with: dictionary-comprehension
score: -2
downvote count: 2
has title: Making a dictionary with keys being lists of increasing values
has answer: http://stackoverflow.com/a/49764356
accepted answer: http://stackoverflow.com/a/49764356
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49763698
has comment: http://stackoverflow.com/comment/86623817
has body: I'm trying to figure out how to make a dictionary that looks like this: 1: [0, 1, ..., 26] 2: [27, 29, ..., 53] 3: [55, 56, ..., 80] I can't think of a quick way to do this. Can anybody think of an elegant way to code a dictionary that looks like this? Thanks!
tagged with: python
tagged with: dictionary
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/49763644
has comment: http://stackoverflow.com/comment/86543880

http://stackoverflow.com/q/49878701
has answer: http://stackoverflow.com/a/49888544
possible better answer: http://stackoverflow.com/a/49888544
answer count: 3
has title: scipy curve_fit cannot fit a tophat function
has answer: http://stackoverflow.com/a/64435686
tagged with: scipy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49888515
accepted answer: http://stackoverflow.com/a/49888515
has comment: http://stackoverflow.com/comment/86773713
downvote count: 0
tagged with: curve-fitting
tagged with: python
has body: I am trying to fit a top hat function to some data, ie. f(x) is constant for the entire real line, except for one segment of finite length which is equal to another constant. My parameters are the two constants of the tophat function, the midpoint, and the width and I'm trying to use scipy.optimize.curve_fit to get all of these. Unfortunately, curve_fit is having trouble obtaining the width of the hat. No matter what I do, it refuses to test any value of the width other than the one I start with, and fits the rest of the data very badly. The following code snippet illustrates the problem: import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def tophat(x, base_level, hat_level, hat_mid, hat_width): ret=[] for xx in x: if hat_mid-hat_width/2. &lt; xx &lt; hat_mid+hat_width/2.: ret.append(hat_level) else: ret.append(base_level) return np.array(ret) x = np.arange(-10., 10., 0.01) y = tophat(x, 1.0, 5.0, 0.0, 1.0)+np.random.rand(len(x))*0.2-0.1 guesses = [ [1.0, 5.0, 0.0, 1.0], [1.0, 5.0, 0.0, 0.1], [1.0, 5.0, 0.0, 2.0] ] plt.plot(x,y) for guess in guesses: popt, pcov = curve_fit( tophat, x, y, p0=guess ) print popt plt.plot( x, tophat(x, popt[0], popt[1], popt[2], popt[3]) ) plt.show() Why is curve_fit so extremely terrible at getting this right, and how can I fix it?
type: AnsweredQuestion
upvote count: 3
score: 3

http://stackoverflow.com/comment/86579596
type: Comment
comment on: http://stackoverflow.com/q/49782137
score: 0
has text: For most cases I can think of, the usual solution would be to go through your open windows and see which one the script is in.
type: QuestionComment

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/49869376
tags question: http://stackoverflow.com/q/49779506
tags question: http://stackoverflow.com/q/49772087
tags question: http://stackoverflow.com/q/49853223
tags question: http://stackoverflow.com/q/49813584
tags question: http://stackoverflow.com/q/49817574
tags question: http://stackoverflow.com/q/49816979
tags question: http://stackoverflow.com/q/49859441
tags question: http://stackoverflow.com/q/49913996
tags question: http://stackoverflow.com/q/49842383
tags question: http://stackoverflow.com/q/49860092
tags question: http://stackoverflow.com/q/49816499
tags question: http://stackoverflow.com/q/49906129
tags question: http://stackoverflow.com/q/49834712
tags question: http://stackoverflow.com/q/49776144
tags question: http://stackoverflow.com/q/49882526
tags question: http://stackoverflow.com/q/49899373
tags question: http://stackoverflow.com/q/49795988
tags question: http://stackoverflow.com/q/49782461
tags question: http://stackoverflow.com/q/49857751
tags question: http://stackoverflow.com/q/49789410
tags question: http://stackoverflow.com/q/49817489
tags question: http://stackoverflow.com/q/49778993
tags question: http://stackoverflow.com/q/49879038
tags question: http://stackoverflow.com/q/49811304
tags question: http://stackoverflow.com/q/49842200
tags question: http://stackoverflow.com/q/49880828
tags question: http://stackoverflow.com/q/49838338
tags question: http://stackoverflow.com/q/49772684
tags question: http://stackoverflow.com/q/49853649
tags question: http://stackoverflow.com/q/49901193
tags question: http://stackoverflow.com/q/49839439
tags question: http://stackoverflow.com/q/49771587
type: Tag
tags question: http://stackoverflow.com/q/49870917

http://stackoverflow.com/comment/86698741
has text: What about cuda? What did it say about cuda?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49841147
score: 0

http://stackoverflow.com/q/49819691
type: Question
accepted answer: http://stackoverflow.com/a/49819992
has answer: http://stackoverflow.com/a/49819992
tagged with: timezone
has answer: http://stackoverflow.com/a/49819959
tagged with: epoch
tagged with: datetime
tagged with: python
type: AnsweredQuestion
has title: Why the difference between datetime.datetime.now().timestamp() and datetime.datetime.utcnow().timestamp()?
answer count: 3
possible better answer: http://stackoverflow.com/a/49820128
tagged with: python-3.5
has answer: http://stackoverflow.com/a/49820128
downvote count: 0
has body: As I understand the seconds since Unix epoch (1970-01-01 00:00:00 UTC) should be the same everywhere around the globe, since it is fixed to UTC. Now, if you are in a timezone with some hours +/- UTC, why do you get different timestamps if you do this (+2 hours in my case) &gt;&gt;&gt; datetime.datetime.utcnow().timestamp() 1523622844.637763 &gt;&gt;&gt; datetime.datetime.now().timestamp() 1523630048.558158 If you account for the time it took me to run the 2nd line of code, you get to the conclusion that there is a 7200 seconds (2 hrs) difference between the two timestamps. Shouldn't these timestamps be time zone unaware?
score: 7
upvote count: 7
favorite count: 0

http://stackoverflow.com/comment/86558210
has text: I used Firefox's builtin debug tool but that shouldn't be any different. I just inspected the requests going on. When I saw one with "Quotes" in its url I tried to open it and that was it.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49759429
type: Comment

http://stackoverflow.com/comment/86533479
type: QuestionComment
has text: https://stackoverflow.com/questions/40781295/how-to-find-the-first-empty-row-of-a-google-spread-sheet-using-python-gspread
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49758593

http://stackoverflow.com/q/49800747
has answer: http://stackoverflow.com/a/49864924
downvote count: 0
has title: Constructing hierarchy from dictionary/JSON
has body: I'm looking for a way to create hierarchy in form of child parent relationship between two or more instances of same class. How would one go about creating such objects from nested dictionary like in example ? Is this even possible ? Is there some other way which would be recommended to do such task? # -*- coding: utf-8 -*- from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, exists from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import Integer, String Base = declarative_base() class Person(Base): __tablename__ = 'person'; id = Column(Integer, primary_key=True) name = Column(String, nullable=False) parent_id = Column(Integer, ForeignKey('person.id')) def __init__(self, **kwargs): self.parent_id = kwargs.get('parent_id', None) self.name = kwargs.get('name') self.team = kwargs.get('team', []) # Is it possible to create more object of this type # and establish that their parent_id is ID of this object? def __repr__(self): return """ ID: {} Name: {} ParentID: {} """.format(self.id, self.name, self.parent_id) engine = create_engine('sqlite:///db.sqlite3') Base.metadata.create_all(engine) connection = engine.connect() Session = sessionmaker(bind=engine) session = Session() alice = {'name' : 'Alice'} bob = {'name' : 'Bob', 'team' : [alice, ]} p1 = Person(bob) session.add(p1) session.commit() I understand the iterative approach where I would first create parent object, then iterate over possible children and create them. I'm curious if there is a way to do this inside constructor rather than from 'outside' with loops.
answer count: 1
tagged with: python
upvote count: 7
tagged with: class-hierarchy
tagged with: parent-child
tagged with: recursion
type: AnsweredQuestion
score: 7
tagged with: sqlalchemy
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49864924

http://stackoverflow.com/comment/86696496
comment on: http://stackoverflow.com/q/49840710
has text: @Aran-Fey "words" or rather "text pieces" that end in `'u1'` go into `u1`, parts ending in `'u2'` go into `u2` - its a kindof weird thing to do, though.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49862977
has comment: http://stackoverflow.com/comment/86741433
has body: This is an overly simplified version of the problem that I'm working on. It's crude and basic but I just started out with python and wanna make sure that I have my basics straightened out. I can't seem to get the desired output with this. For ex: When the list generated by a() contains '2', when I call out b() it does not give me the required value of y, which in this case should be 2. from random import choice, sample def a(): a = sample(range(0,5),2) a.append(1) return a def b(): if 3 in a(): y = 1 elif 2 in a(): y = 2 else: pass return y print a() print b()
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49863324
has comment: http://stackoverflow.com/comment/86741149
has comment: http://stackoverflow.com/comment/86741289
downvote count: 1
has comment: http://stackoverflow.com/comment/86741466
has comment: http://stackoverflow.com/comment/86741050
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49863324
has title: is this the proper use of 'in' in a conditional statement?
tagged with: python
score: -1
type: AnsweredQuestion

http://stackoverflow.com/q/49863212
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86741574
has comment: http://stackoverflow.com/comment/86741648
has answer: http://stackoverflow.com/a/49863263
answer count: 3
has answer: http://stackoverflow.com/a/49863278
has comment: http://stackoverflow.com/comment/86743986
downvote count: 3
has body: Tried to search for the issue but couldn't find it. Here is the code: number1 = input("Hello, tell me one number! :") number2 = input("Now the second number! :") sum = (float(number1) + float(number2))/2 result1 = number1 &lt;= number2 print("Number 1 is:" + number1 ) print("Number 2 is:" + number2 ) print("The average of {0} and {1} is {2}".format(number1, number2, sum)) print(number1 + "is smaller or equal than" + number2 + ":" + result1) Error code is: print(number1 + "is smaller or equal than" + number2 + ":" + result1) TypeError: must be str, not bool Now I had a similar issue with the sum number, but I could fix it with the float(), but I cannot figure out how to print a simple true/false at the end.
has comment: http://stackoverflow.com/comment/86741650
has answer: http://stackoverflow.com/a/49863286
tagged with: macos
has comment: http://stackoverflow.com/comment/86741784
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86741675
has title: Can´t print boolean (true, false), TypeError: must be str, not bool

http://stackoverflow.com/comment/86731136
has text: It does not seem to be working; specifically, it does not count months and years @jpp
type: Comment
comment on: http://stackoverflow.com/a/49856946
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86655572
type: Comment
has text: I did it the same way, but I wanted something like the below.
type: AnswerComment
comment on: http://stackoverflow.com/a/49817174
score: 0

http://stackoverflow.com/q/49834066
tagged with: python-requests
downvote count: 1
favorite count: 0
type: Question
has body: I'm trying to download a zip file from an FTP link. I've tried to use request package but could not download import requests url = 'ftp://ftp.ibge.gov.br/Precos_Indices_de_Precos_ao_Consumidor/IPCA/Serie_Historica/ipca_SerieHist.zip' r = requests.get(url) Is there an easy way to download it? I can download it from the Chrome and don't need any type of login and password Thanks
tagged with: ftp
tagged with: http://stackoverflow.com/tag/zip
linked to: http://stackoverflow.com/q/31710459
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49834093
tagged with: python
has comment: http://stackoverflow.com/comment/86683764
duplicate of: http://stackoverflow.com/q/11768214
has comment: http://stackoverflow.com/comment/86683951
has title: download zipfile from a ftp link
linked to: http://stackoverflow.com/q/11768214
upvote count: 2
score: 1
answer count: 1

http://stackoverflow.com/q/49868023
has comment: http://stackoverflow.com/comment/87077348
has comment: http://stackoverflow.com/comment/87119053
answer count: 1
accepted answer: http://stackoverflow.com/a/66370793
tagged with: google-earth-engine
has title: Is there a way to calculate flow accumulation in google earth engine with python?
has answer: http://stackoverflow.com/a/66370793
type: AnsweredQuestion
score: 0
tagged with: python
has body: I see that Earth Engine has 'ee.Terrain.slope()', but is there a way I can use another python library to calculate flow accumulation - like in pyDEM or pygeoprocessing?
type: Question

http://stackoverflow.com/comment/86810623
has text: Does you network work okay otherwise? Do you get some normal accuracy values? Zero might be a legitimate AUC value in case you have a model collapse, for example. You should also print `y_pred` and `y_true` and see if you feed good data to the auc calculation. Otherwise I'd need much more info to debug this, like your whole code I could run on my comp, including data.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49888160
type: AnswerComment

http://stackoverflow.com/comment/86721066
score: 0
type: Comment
type: QuestionComment
has text: Are you using macOS?
comment on: http://stackoverflow.com/q/49853252

http://stackoverflow.com/q/49783669
tagged with: postgresql
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86582729
tagged with: dataframe
tagged with: merge
has title: Fastest way to update table nulls in postgresql from dataframe
has body: I have a pandas dataframe and matching postgresql table, where every cell in both is either null or a timestamp. For each cell in the table where the cell value equals null, and the corresponding dataframe cell value is a timestamp, I want to update the table cell value. What's the fastest way to do this? Currently I'm pulling in the whole table into a dataframe, comparing the two dataframes in python (cell by cell), entering those values into a 3rd dataframe (call it DFC), and then destroying the old table and building a new table from DFC. This seems inefficient. Example: **Data Frame** **Postgres Table** A B A B 1 NaN 5 1 NaN NaN 2 8 NaN 2 7 NaN **Goal State Postgres Table** A B 1 NaN 5 2 7 NaN Current Code: import pandas as pd from pandas import DataFrame d = {'A': ['None', 8], 'B': [5, 'None']} df = pd.DataFrame(data=d) out = {'A': ['None', 'None'], 'B': ['None', 'None']} outdf = pd.DataFrame(data=out) tbl = pd.read_sql_query('select * from "exampletable"',con=engine) for i, row in df.iterrows(): for j in ['A', 'B']: if df.at[i, j] != 'None' and tbl.at[i, j] == 'None': outdf.at[i, j] = df.at[i, j] else: outdf.at[i, j] = tbl.at[i, j] df.to_sql('exampletable', engine, if_exists='replace') print(outdf.to_string())
type: Question
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86582788
tagged with: python
has answer: http://stackoverflow.com/a/49783915

http://stackoverflow.com/q/49850095
tagged with: matplotlib
downvote count: 1
has comment: http://stackoverflow.com/comment/86714684
tagged with: jupyter
has comment: http://stackoverflow.com/comment/86729981
favorite count: 0
type: Question
has body: Can a histogram/bar chart be displayed with string x axis titles ? Below I'm attempting to display the chart with pre-configured x and y axis values where each x axis value is a string range. Below code : import matplotlib.pyplot as plt x = ['1 - 100','200 - 400','400 - 600','600 - 800','800 - 100'] y = [10,2,3,4,5] plt.bar(x,y,align='center') # A bar chart plt.xlabel('Number iterations') plt.ylabel('Time taken') plt.show() causes error : TypeError: unsupported operand type(s) for -: 'str' and 'float
has answer: http://stackoverflow.com/a/49858603
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86731922
has title: Histogram with string x axis
type: AnsweredQuestion
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86731928
has answer: http://stackoverflow.com/a/49850256
accepted answer: http://stackoverflow.com/a/49858603
possible better answer: http://stackoverflow.com/a/49850256

http://stackoverflow.com/comment/86754523
type: QuestionComment
comment on: http://stackoverflow.com/q/49869649
type: Comment
score: 0
has text: I think you got an error because of that the path is not valid, did you check it with the full path?

http://stackoverflow.com/comment/86663319
comment on: http://stackoverflow.com/a/49823512
has text: You need to ensure your python is 64 bit too. open command prompt and type python. First line. Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] Has to say 64 bit
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49888664
has body: The issue is that you're checking for the literal string "typeVar", not the user input. Instead of cursor.execute("SELECT * from place WHERE typeOfPlace=typeVar") try: cursor.execute("SELECT * from place WHERE typeOfPlace={}".format(typeVar)).
score: 0
has comment: http://stackoverflow.com/comment/86793492
has comment: http://stackoverflow.com/comment/86793592
answers question: http://stackoverflow.com/q/49888643
type: Answer
has comment: http://stackoverflow.com/comment/86793524
has comment: http://stackoverflow.com/comment/86793562

http://stackoverflow.com/q/49793399
accepted answer: http://stackoverflow.com/a/49795849
has comment: http://stackoverflow.com/comment/86601265
type: Question
has body: I have a Python script written, that is an extension to a massive C++ program written on Visual Studio 2013. The scripts works fine on the program and I can call it easily inside the project using system() command. However my new task is to get any Warnings from that script display as warnings inside the VS project. I have no shared directories, the python script requires no C++ variables from the project and the script has no return variables. My current simplistic way of running my script : system("py C:\\Task4\\testing_functions.py"); I tried using &lt;python.h&gt; library but couldn't get it to work on the pre-existing project without tampering with the configuration options and directories which is a no-go for the rest of the company. Is there a way I can perhaps export the python log into a report that Visual Studio can then read and display?
has answer: http://stackoverflow.com/a/49795849
has title: Display Python script warnings in a VS C++ code
linked to: http://stackoverflow.com/q/478898
tagged with: warnings
tagged with: python
has comment: http://stackoverflow.com/comment/86602366
tagged with: c++
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86603083
has comment: http://stackoverflow.com/comment/86605730
answer count: 1
linked to: http://stackoverflow.com/q/16235370
has comment: http://stackoverflow.com/comment/86604360

http://stackoverflow.com/comment/86953670
type: Comment
type: AnswerComment
has text: I apologize if I am annoying or anything, Python is not my strong suit even as a rigger
comment on: http://stackoverflow.com/a/49872814
score: 0

http://stackoverflow.com/a/49800501
has comment: http://stackoverflow.com/comment/92535589
answers question: http://stackoverflow.com/q/49800045
type: Answer
accepted answer of: http://stackoverflow.com/q/49800045
upvote count: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86616078
downvote count: 1
score: 3
has comment: http://stackoverflow.com/comment/92535297
has body: The answer by MadPhysicist can be optimized to avoid unneeded allocation of temporary data: x -= x.min() x /= x.ptp() Inplace operators (+=, -=, etc...) don't eat your memory (so swapping on disk is less likely to occur). Of course, this destroys your initial x so it's only OK if you don't need x afterwards... Also, the idea he proposed to concatenate multi data in higher dimension matrices, is a good idea if you have many many channels, but again it should be tested whether this BIG matrix generates disk swapping or not, compared to small matrices processed in sequence.

http://stackoverflow.com/comment/86679413
score: 0
comment on: http://stackoverflow.com/q/49831995
type: QuestionComment
type: Comment
has text: @sacul It gives: `Index(['Day1 Day2 Day3 Day4 Day5 Day6 Day7'], dtype='object')`

http://stackoverflow.com/q/49889137
has comment: http://stackoverflow.com/comment/86831974
has title: Cannot open file in Spyder editor; only getting linux error: setNativeLocks failed: "No locks available"
score: 0
answer count: 0
tagged with: spyder
has comment: http://stackoverflow.com/comment/86794502
type: Question
has comment: http://stackoverflow.com/comment/86794399
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86821377
tagged with: python
has body: I'm trying to access my files on the Spyder 3.2.8 editor, but any time I double-click on the file the editor freezes and I can't navigate it. Meanwhile, the error: setNativeLocks failed: "No locks available" continuously pops up in the Linux terminal I open Spyder with. For some context, I did recently update from version 3.1.4 to 3.2.8. I also mainly use my own environment I created in anaconda, but the result is the same inside or outside the environment. I've reinstalled/reset spyder, and restarted my computer. Any help is appreciated.

http://stackoverflow.com/q/49854487
has title: Cannot route non-ascii URLs Flask
answer count: 2
has answer: http://stackoverflow.com/a/49854832
type: UnansweredQuestion
tagged with: url
tagged with: flask
score: 0
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has answer: http://stackoverflow.com/a/49854814
has body: I have a problem with the routing my URL adress to Flask, precisely with running it in web-browser. All I want is to transfer the sharp symbol "#" and some Russian words (as like "#привет" or "#ПомогитеМнеПожалуйста") together. The screenshot of error: enter image description here My programming code at the moment looks like this: # -*- coding: utf-8 -*- from flask import Flask, jsonify app = Flask(__name__) @app.route('/hashtags/&lt;names&gt;', methods=['GET']) def get_hashtags(names): return jsonify({'Segmentation Hashtags': names}) if __name__ == '__main__': app.run(port=9876) So, basically, &lt;names&gt; is a parameter from function get_hashtag that is used for transfering my future hashtag to the web-browser using jsonify. I need to find the way of transfering any hashtag I want with sharp symbol "#" plus Russian letters. As far as I know, there is an ASCII-coding methods (something like .**decode(utf-8)**), but I have no idea how to use it properly. Thanks in advance!
type: Question

http://stackoverflow.com/comment/86608055
type: Comment
has text: Thanks a lot for your answer, now I added to the post the item which is causing the error
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49795208

http://stackoverflow.com/a/49813848
upvote count: 1
answers question: http://stackoverflow.com/q/49813386
has body: You can set a penalty for misclassification of each sample. If weights is a tensor of shape [batch_size], the loss for each sample will be multiplied by the corresponding weight. So if you assign the same weight to all samples (which is the same as using a scalar weight), your loss will only be scaled by this scalar, and the accuracy should not change. If you instead assign different weights for the minority class and the majority class, the contributions of the samples to the loss function will be different, and you should be able to influence the accuracy by choosing your weights differently. A few scenarios (your choice will depend on what you need): 1.) If you want a good overall accuracy, it you could choose the weights of the majority class to be very large and the weights of the minority class much smaller. This will probably lead to a classification of all events into the majority class (i.e. 95 % of total classification accuracy, but the minority class will usually be classified into the wrong class. 2.) If your signal is the minority class and the background is the majority class, you probably want very little background contamination in your predicted signal, i.e. you want almost no background samples to be predicted as signal. This will also happen if you choose the majority weight much larger than the minority weight, but you might find that the network tends to predict all samples to be background. So you will not have any signal samples left. In this case you should consider a large weight for the minority class + an extra loss for background samples being classified as signal samples (false positives), like this: loss = weighted_cross_entropy + extra_penalty_for_false_positives
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/86715493
type: QuestionComment
has text: Do you want to keep feeding the count of $ to the wave outputting module every time you see a #?
comment on: http://stackoverflow.com/q/49850431
type: Comment
score: 1

http://stackoverflow.com/comment/86565775
comment on: http://stackoverflow.com/q/49775405
score: 0
type: Comment
has text: You actually have 3 questions here and they are too open ended. Consider editing and focusing on one.
type: QuestionComment

http://stackoverflow.com/comment/86632470
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49808649
has text: It gives me `AttributeError: 'lxml.etree._Element' object has no attribute 'text_content'`

pyqt
type: Tag
tags question: http://stackoverflow.com/q/49761821
tags question: http://stackoverflow.com/q/49761055
tags question: http://stackoverflow.com/q/49840304
tags question: http://stackoverflow.com/q/49832036
tags question: http://stackoverflow.com/q/49867654
tags question: http://stackoverflow.com/q/49813237
tags question: http://stackoverflow.com/q/49911466
tags question: http://stackoverflow.com/q/49837565
tags question: http://stackoverflow.com/q/49909633
tags question: http://stackoverflow.com/q/49803745
tags question: http://stackoverflow.com/q/49854556
tags question: http://stackoverflow.com/q/49910164
tags question: http://stackoverflow.com/q/49813012
tags question: http://stackoverflow.com/q/49870920
tags question: http://stackoverflow.com/q/49789827
tags question: http://stackoverflow.com/q/49815149
tags question: http://stackoverflow.com/q/49869767
tags question: http://stackoverflow.com/q/49786260
tags question: http://stackoverflow.com/q/49911320
tags question: http://stackoverflow.com/q/49859670
tags question: http://stackoverflow.com/q/49898820
tags question: http://stackoverflow.com/q/49901868
tags question: http://stackoverflow.com/q/49768523
tags question: http://stackoverflow.com/q/49846832
tag name: pyqt
tags question: http://stackoverflow.com/q/49760249
tags question: http://stackoverflow.com/q/49766816
tags question: http://stackoverflow.com/q/49820853
tags question: http://stackoverflow.com/q/49849044
tags question: http://stackoverflow.com/q/49906003
tags question: http://stackoverflow.com/q/49838817
tags question: http://stackoverflow.com/q/49836480
tags question: http://stackoverflow.com/q/49850047
tags question: http://stackoverflow.com/q/49782785
tags question: http://stackoverflow.com/q/49758612
tags question: http://stackoverflow.com/q/49785026
tags question: http://stackoverflow.com/q/49777214
tags question: http://stackoverflow.com/q/49827976
tags question: http://stackoverflow.com/q/49888155

http://stackoverflow.com/q/49820972
score: 2
downvote count: 0
type: UnansweredQuestion
answer count: 1
has title: Flask-SQLAlchemy's create_all does not create tables
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
tagged with: unit-testing
has answer: http://stackoverflow.com/a/49821432
tagged with: python
tagged with: sqlalchemy
has body: I'm working on a flask application where I'm trying to isolate my unit tests. I'm using flask-sqlalchemy, and I'm trying to use the create_all and drop_all methods to clean my database after running a test. However, it appears my create_all and drop_all methods do not actually create/drop the tables as the documentation states. I have my models imported in the application before calling create_all, like most other answers say. This is the error I'm getting with the code below: psycopg2.ProgrammingError: relation "tasks" does not exist Here's my relevant code /app.py import os import configparser from flask import Flask from src.router import router from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) if not os.path.exists(os.path.join(app.root_path, 'config.ini')): raise Exception(f'config.ini not found in the {app.root_path}') config = configparser.ConfigParser() config.read('config.ini') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = config[os.environ['APP_ENV']]['DATABASE_URI'] app.register_blueprint(router) db = SQLAlchemy(app) migrate = Migrate(app, db) if __name__ == "__main__": app.run() /tests/test_router.py from unittest import TestCase from flask import Flask from app import app, db from src.models import Task class TestRouter(TestCase): def setUp(self): db.create_all() def tearDown(self): db.drop_all() def test_adds_task(self): task = Task(task_id='task_1', name='my task') db.session.add(task) db.session.commit()
type: Question
upvote count: 2

http://stackoverflow.com/a/49871095
type: Answer
has body: Revit typically outputs several CAD-based file formats (you did not explicitely mention the exact file format of your Revit files: DXF?, DWF? etc). So you need a Python package able to deal with CAD data. I would recommend pythonOCC http://www.pythonocc.org
score: 0
answers question: http://stackoverflow.com/q/49870920

http://stackoverflow.com/a/50492636
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/49836676
has body: Recover with python3 -m pip install --user pip==9.0.1 (or the version that worked)
score: 6
upvote count: 7

http://stackoverflow.com/comment/86841117
score: 0
type: Comment
has text: @yukchingleung the one thing I could imagine would be memory, if there are non-uniques with large multiplicity in both datasets.
type: AnswerComment
comment on: http://stackoverflow.com/a/49912284

http://stackoverflow.com/comment/86669508
comment on: http://stackoverflow.com/a/49819639
has text: @jejjejd are you sure about that? Because the only way I can reproduce this error is if either the numpy data type is wrong (you can convert it to a `np.float32` if that's the case), or the input is incorrectly specified. The input should be `np.array([(pt1_x, pt1_y), ..., (ptN_x, ptN_y)])` as stated in this answer.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86770808
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49874127
has text: @Megalng Thanks

http://stackoverflow.com/a/49836180
type: AcceptedAnswer
upvote count: 1
has comment: http://stackoverflow.com/comment/86687972
has comment: http://stackoverflow.com/comment/86688341
has body: Explanation The tensorflow computation graph needs to compute the values for y_true_cls and y_pred_cls in order to compute your confusionMatrix. To compute y_true_cls and y_pred_cls, the graph defined in the code needs the values for x and y_true placeholders. These values are provided in form of a dictionary when running a session. After providing these placeholders with values, the tensorflow graph has the requisite input to compute the value of the final confusionMatrix. Code I hope that the following code helps. &gt;&gt;&gt; confusionMatrix = tf.confusion_matrix(labels=y_true_cls,predictions=y_pred_cls) &gt;&gt;&gt; &gt;&gt;&gt; # fetch a chunk of data &gt;&gt;&gt; batch_size = 100 &gt;&gt;&gt; x_batch, y_batch, _, cls_batch = data.valid.next_batch(batch_size) &gt;&gt;&gt; &gt;&gt;&gt; # make a dictionary to be fed for placeholders `x` and `y_true` &gt;&gt;&gt; feed_dict_testing = {x: x_batch, y_true: y_batch} &gt;&gt;&gt; &gt;&gt;&gt; # now evaluate by running the session by feeding placeholders &gt;&gt;&gt; result=session.run(confusionMatrix, feed_dict=feed_dict_testing) &gt;&gt;&gt; &gt;&gt;&gt; print result Expected output If the classifier is working excellently then the output should be a diagonal matrix. predicted red blue originally red [[ 15, 0], originally blue [ 0, 15]] PS: Right now, I am not in front of a machine with Tensorflow on it. That's why I can't verify it myself. There might be some mistakes with variable names etc.
accepted answer of: http://stackoverflow.com/q/49835838
has comment: http://stackoverflow.com/comment/86688115
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86688469
has comment: http://stackoverflow.com/comment/86688248
has comment: http://stackoverflow.com/comment/86688372
has comment: http://stackoverflow.com/comment/86688048
answers question: http://stackoverflow.com/q/49835838
has comment: http://stackoverflow.com/comment/86688089
has comment: http://stackoverflow.com/comment/86688295
has comment: http://stackoverflow.com/comment/86688270
score: 1

http://stackoverflow.com/q/49769611
accepted answer: http://stackoverflow.com/a/49770012
tagged with: python
tagged with: jupyter
tagged with: jupyter-notebook
type: Question
has body: The jupyter widgets exension is not rendering the ui items. Have tried updating the client and enabling widgetsnbextension but code below : !pip install --upgrade jupyter_core jupyter_client !jupyter nbextension enable --py widgetsnbextension from IPython.display import display button = widgets.Button(description="Click Me!") display(button) def on_button_clicked(b): print("Button clicked.") button.on_click(on_button_clicked) renders : Requirement already up-to-date: jupyter_core in /usr/local/lib/python2.7/dist-packages Requirement already up-to-date: jupyter_client in /usr/local/lib/python2.7/dist-packages Requirement already up-to-date: traitlets in /usr/local/lib/python2.7/dist-packages (from jupyter_core) Requirement already up-to-date: python-dateutil&gt;=2.1 in /usr/local/lib/python2.7/dist-packages (from jupyter_client) Requirement already up-to-date: pyzmq&gt;=13 in /usr/local/lib/python2.7/dist-packages (from jupyter_client) Requirement already up-to-date: tornado&gt;=4.1 in /usr/local/lib/python2.7/dist-packages (from jupyter_client) Requirement already up-to-date: enum34; python_version == "2.7" in /usr/local/lib/python2.7/dist-packages (from traitlets-&gt;jupyter_core) Requirement already up-to-date: six in /usr/local/lib/python2.7/dist-packages (from traitlets-&gt;jupyter_core) Requirement already up-to-date: decorator in /usr/local/lib/python2.7/dist-packages (from traitlets-&gt;jupyter_core) Requirement already up-to-date: ipython-genutils in /usr/local/lib/python2.7/dist-packages (from traitlets-&gt;jupyter_core) Requirement already up-to-date: singledispatch in /usr/local/lib/python2.7/dist-packages (from tornado&gt;=4.1-&gt;jupyter_client) Requirement already up-to-date: futures in /usr/local/lib/python2.7/dist-packages (from tornado&gt;=4.1-&gt;jupyter_client) Requirement already up-to-date: backports-abc&gt;=0.4 in /usr/local/lib/python2.7/dist-packages (from tornado&gt;=4.1-&gt;jupyter_client) Enabling notebook extension jupyter-js-widgets/exte…
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49770012
upvote count: 1
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53117780
possible better answer: http://stackoverflow.com/a/53117780
score: 1
has title: Enable jupyter widgets

http://stackoverflow.com/comment/86694047
type: AnswerComment
comment on: http://stackoverflow.com/a/49827061
has text: 1) You need to understand what fields you have inside the "Comment Model" and how many of them are "Foreign_key". 2) The only part where you are getting the error is because inside views.py if you see closely then you are linking one of your foreign_key (Author to the logged in user), but because you also have another foreign_key inside the model you need to link that foreign_key/field to the existing post too. 3) you are using class based view, i will be updating my answer do check that out, it will cover how to link your comment with the corresponding post
score: 0
type: Comment

http://stackoverflow.com/comment/86766447
comment on: http://stackoverflow.com/a/49875522
type: Comment
has text: That is imported at the top of the program
type: AnswerComment
score: 0

http://stackoverflow.com/q/49907356
accepted answer: http://stackoverflow.com/a/49909685
tagged with: sublimetext3
has title: Finding files by relative path in sublime text 3
favorite count: 0
type: Question
upvote count: 2
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/49909685
type: AnsweredQuestion
has body: I am trying out Sublime Text as my new editor and I ran into an rather unexpected problem. I am working with a project (Django web app) that has many files with the same name sitting in different directories. So, I would have app1/models.py, app2/models.py ... app15/models.py etc. So if I just hit Cmd-P and type models.py I get a fairly sizable list that I have to scroll through to get to the file I want. In Vim, I just type :e a, hit TAB to complete the path, then once I have the right app, I type mo hit tab again and I am there. How do I do something similar in Sublime?
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49840710
answer count: 2
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49840898
has comment: http://stackoverflow.com/comment/86696496
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49841058
has title: Split string with two words
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49840898
has comment: http://stackoverflow.com/comment/86696476
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49841058
has body: Is there a way to split a string on either of two delimiters. Code example: # word --&gt; u1 or word --&gt; u2 a = "Hi thereu1hello ?u1Whatu2Goodu1Work worku2Stacku2" # here we must split this string with two words "u1" &amp;&amp; "u2" and insert them in 2 list like this u1 = ["Hi there", "hello ?", "Good"] u2 = ["What", "Work work", "Stack"]

http://stackoverflow.com/q/49873194
tagged with: css
has body: In Django, it is possible to use different Css files in one HTML document ? I would like to use one css for base.html and another one for page1.html while expanding base.html to page1.html... For example, base.html : {% load static %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="{% static "css/base.css" %}"&gt; &lt;/head&gt; {% block content %}{% endblock%} &lt;/body&gt; &lt;/html&gt; and page1.html : {% extends "base.html" %} {% load static %} &lt;link rel="stylesheet" href="{% static "css/page1.css" %}"&gt; {% block content %} code... {% endblock %} I don't want to merge the Css files, do I have an another solution ?
has title: Django : Use multiple CSS file in one html
type: AnsweredQuestion
tagged with: django-templates
accepted answer: http://stackoverflow.com/a/49873237
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has answer: http://stackoverflow.com/a/49873237
downvote count: 0
favorite count: 0
type: Question
score: 5
upvote count: 5
tagged with: django
tagged with: python

http://stackoverflow.com/comment/86540761
type: AnswerComment
has text: @HarshaVardhan It seems you have invalid datetimes, so those are coerced to NaT. Calling dt.year gives NaN. If you drop those rows, you can convert to int.
score: 0
comment on: http://stackoverflow.com/a/49762466
type: Comment

http://stackoverflow.com/comment/86734578
has text: Thanks! I'm trying to use the --onefile command, but then it doesn't take the binaries into account. I only get the error " FileNotFoundError: [Errno 2] No such file or directory: 'chromedriver': 'chromedriver'". Any workaround for this?
type: Comment
comment on: http://stackoverflow.com/a/49853701
type: AnswerComment
score: 1

http://stackoverflow.com/comment/86813561
has text: the problem was not where i was searching, thanks ! The first time i ran the program it created the pkl file as intended but it didn't contain what i wanted then when i re-run the program it loaded it and overwrote the list !
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49898774
score: 0

http://stackoverflow.com/comment/86706140
score: 0
type: Comment
type: QuestionComment
has text: I would say python is not php, you cannot just simply include your variables in a string. You need to use placeholders.
comment on: http://stackoverflow.com/q/49843280

http://stackoverflow.com/q/49907262
tagged with: multithreading
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49907374
type: Question
tagged with: python
type: AnsweredQuestion
has body: I am writing a threaded Python script for the first time and running into some trouble. The general idea is that a Raspberry Pi receives data from a Bluetooth connection, this data is then used to create a thread that calls the start_laps method. Once this thread is started, I need to continue listening for new data to determine if the thread should be killed. However, my code is not continuing execution after the thread is started. What would cause this? import json import bluetooth import threading import timed_LEDs import subprocess import ast def start_laps(delay, lap_times): timed_LEDs.start_LEDs(delay, lap_times) # put pi in discoverable subprocess.call(['sudo', 'hciconfig', 'hci0', 'piscan']) server_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) port = 1 server_socket.bind(("", port)) server_socket.listen(1) client_socket, address = server_socket.accept() print("Accepted connection from ", address) threads = [] while True: print("RECEIVING") data = client_socket.recv(1024) data = json.loads(data.decode()) print(data) if(data["lap_times"]): print("STARTING THREAD") t = threading.Thread(target=start_laps(int(data["delay"]), ast.literal_eval(data["lap_times"]))) threads.append(t) t.start() elif data == "stop": print("Stop dat lap") else: print(data) client_socket.close()
has answer: http://stackoverflow.com/a/49907374
has title: Python code not continuing execution after thread started
score: 1

http://stackoverflow.com/q/49845144
has title: Trying to trigger a `click` event on js, does not work
accepted answer: http://stackoverflow.com/a/49845363
tagged with: javascript
tagged with: python
type: AnsweredQuestion
score: 0
has body: I want to trigger a click event on a file input when another button object is clicked. I know the js code runs up to the point where I call the modelObject.click() sentence, but the target object does not react. This is the code: {% extends "StylingApp/base_site.html" %} {% block title %} Álbumes {% endblock title %} {% block stylesheets %} {{ block.super }} {% endblock stylesheets %} {% block content %} Álbum: {{ album.name }} Agregar Ir {% for photo in photos %} {{ photo.description }} {% endfor %} {% endblock content %} {% block javascripts %} {{ block.super }} {% endblock javascripts %}
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has answer: http://stackoverflow.com/a/49845363
type: Question

http://stackoverflow.com/q/49765382
tagged with: numpy
has comment: http://stackoverflow.com/comment/86559740
downvote count: 0
has answer: http://stackoverflow.com/a/49765965
upvote count: 1
has answer: http://stackoverflow.com/a/49780848
has comment: http://stackoverflow.com/comment/86576124
tagged with: vectorization
favorite count: 0
has comment: http://stackoverflow.com/comment/86546503
linked to: http://stackoverflow.com/q/48996893
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86546400
has comment: http://stackoverflow.com/comment/86546553
linked to: http://stackoverflow.com/q/49706909
score: 1
has answer: http://stackoverflow.com/a/49767553
has body: I have the following for loop and want to use numpy vectorizing, boolean, mask arrays etc to improve the execution speed. arr is a numpy array def translate(arr, x=0): arr1 = arr.copy() for i in range(arr1.shape[0]): for j in range(arr1.shape[1]): if i + x &lt; arr1.shape[0] and i + x &gt; 0: arr1[i,j] = arr[i+x,j] if i + x &lt; 0 or i + x &gt; arr1.shape[0]: arr1[i,j] = 255 return arr1 Any help or suggestions will be much appreciated. Edit: instead of 255, when (i+x) &lt;0, it should be arr[i,j] def translate(arr, x=0): arr1 = arr.copy() for i in range(arr1.shape[0]): for j in range(arr1.shape[1]): if i + x &lt; arr1.shape[0] and i + x &gt; 0: arr1[i,j] = arr[i+x,j] if i + x &lt; 0 or i + x &gt; arr1.shape[0]: arr1[i,j] = arr[i,j] return arr1
has answer: http://stackoverflow.com/a/49780595
accepted answer: http://stackoverflow.com/a/49767553
has comment: http://stackoverflow.com/comment/86576105
tagged with: python
has title: Improve the execution speed using Numpy
has comment: http://stackoverflow.com/comment/86546918
answer count: 4
type: Question
possible better answer: http://stackoverflow.com/a/49765965
has comment: http://stackoverflow.com/comment/86546357

http://stackoverflow.com/comment/87569339
comment on: http://stackoverflow.com/a/49990889
type: Comment
score: 9
has text: If there's an issue with Pip wouldn't it be good to not constantly try to push the user to upgrade PIP to a broken version?: You are using pip version 9.0.3, however version 10.0.1 is available.
type: AnswerComment

http://stackoverflow.com/comment/114956560
has text: Or `model.optimizer.lr.numpy()` in recent tensorflow versions. `lr` is just a variable, so assigning it works as usual: `model.optimizer.lr.assign(0.1)`
type: AnswerComment
comment on: http://stackoverflow.com/a/49785582
score: 2
type: Comment

http://stackoverflow.com/a/49788895
score: 0
has body: You can try with itertools , But i would like to try recursion : input_dta=[1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 14, 16, 18, 26, 27, 29, 30, 34, 35, 39, 48, 64, 65] final_=[] def consecutives(data): sub_final=[] if not data: return 0 else: for i,j in enumerate(data): try: if abs(data[i]-data[i+1])==1: sub_final.extend([data[i],data[i+1]]) else: if sub_final: final_.append(set(sub_final)) return consecutives(data[i+1:]) except IndexError: pass final_.append(set(sub_final)) consecutives(input_dta) print(final_) output: [{1, 2, 3, 4, 5, 6}, {8, 9, 10, 11}, {26, 27}, {29, 30}, {34, 35}, {64, 65}]
type: Answer
answers question: http://stackoverflow.com/q/49787852

http://stackoverflow.com/q/49761821
tagged with: pyqt
has title: How to get value form QLineEdit() pyqt5 with pushing button
score: 0
answer count: 1
tagged with: pyqt5
has answer: http://stackoverflow.com/a/49762009
tagged with: qlineedit
type: Question
tagged with: python
type: UnansweredQuestion
has body: I have created the QLineEdit object and trying to get valuse from this widget, but at the end I've got an error: qlineedit1 = QLineEdit() qlineedit1.setFixedSize(btn_x_size, btn_y_size) gridLayout.addWidget(qlineedit1, i, j) value = range_btn.clicked.connect(self.get_value(qlineedit1)) @pyqtSlot() def get_text(self, obj): textboxValue = obj.text() return textboxValue text1 = range_btn.clicked.connect(self.get_text(qlineedit1)) TypeError: argument 1 has unexpected type 'str'

http://stackoverflow.com/comment/109076874
score: 6
comment on: http://stackoverflow.com/a/57840282
type: Comment
has text: Might be worth stating that using `level=-1` specifies the rightmost, or outermost index.
type: AnswerComment

http://stackoverflow.com/comment/122886216
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49823033
has text: I am also facing similar issue. Is there any known solution. The two solutions below doesnt work for me.
score: 0

http://stackoverflow.com/comment/86755899
type: AnswerComment
has text: Thank you; this works fine! But is there a way to make similar assumptions as in Mathematica? Should I make this a feature proposal? What do you think?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49860260

http://stackoverflow.com/comment/86767818
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49860455
type: Comment
has text: @Topto. Ok, I've checked. As I suggested the problem is in your `break` statements. They exit your program from `for` block, and another `if` never triggers.

http://stackoverflow.com/q/49770521
tagged with: nltk
tagged with: python
tagged with: nlp
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49770905
answer count: 1
has title: TypeError: slice indices must be integers or None or have an __index__ method NLP
type: Question
has body: I am running an example for NLP, using a stemmer function as a class method. import nltk class IndexedText(object): def __init__(self, stemmer, text): self._text = text self._stemmer = stemmer self._index = nltk.Index((self._stem(word), i) for (i, word) in enumerate(text)) def concordance(self, word, width=40): key = self._stem(word) wc = width/4 # words of context print (self._index[key]) for i in self._index[key]: lcontext = ' '.join(self._text[i-wc:i]) rcontext = ' '.join(self._text[i:i+wc]) ldisplay = '%*s' % (width, lcontext[-width:]) rdisplay = '%-*s' % (width, rcontext[:width]) print (ldisplay, rdisplay) def _stem(self, word): return self._stemmer.stem(word).lower() porter = nltk.PorterStemmer() grail = nltk.corpus.webtext.words('grail.txt') text = IndexedText(porter, grail) Now i'm using concordance function on word 'lie' as follows : text.concordance('lie') And it gives me the error as below : TypeError: slice indices must be integers or None or have an __index__ method Where as the index['lie'] yields the output as all integers : [1824, 6451, 7038, 7080, 8450, 13860, 13965, 16684]
accepted answer: http://stackoverflow.com/a/49770905

http://stackoverflow.com/q/49796944
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49797365
has body: I want to create heaviside step function in TensorFlow. Since Heaviside function is not differentiable I also need to choose derivative approximation and define custom gradient so full implementation looks like this: import tensorflow as tf @tf.RegisterGradient("HeavisideGrad") def _heaviside_grad(unused_op: tf.Operation, grad: tf.Tensor): x = unused_op.inputs[0] # During backpropagation heaviside behaves like sigmoid return tf.sigmoid(x) * (1 - tf.sigmoid(x)) * grad def heaviside(x: tf.Tensor, g: tf.Graph = tf.get_default_graph()): custom_grads = { "Sign": "HeavisideGrad" } with g.gradient_override_map(custom_grads): # TODO: heaviside(0) currently returns 0. We need heaviside(0) = 1 sign = tf.sign(x) # tf.stop_gradient is needed to exclude tf.maximum from derivative step_func = sign + tf.stop_gradient(tf.maximum(0.0, sign) - sign) return step_func There is one caveat in my implementation: tf.sign(0) returns zero value so heaviside(0) also returns zero and I want heaviside(0) to return 1. How can I achieve such behavior?
has answer: http://stackoverflow.com/a/49812102
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86612420
tagged with: python
has comment: http://stackoverflow.com/comment/86617730
answer count: 4
has title: Implementing heaviside step function in TensorFlow
score: 3
has answer: http://stackoverflow.com/a/49801626
has answer: http://stackoverflow.com/a/59495901
upvote count: 3
has comment: http://stackoverflow.com/comment/86608719
downvote count: 0
tagged with: machine-learning
tagged with: tensorflow

http://stackoverflow.com/q/49779725
has comment: http://stackoverflow.com/comment/86575040
upvote count: 1
has comment: http://stackoverflow.com/comment/86574875
favorite count: 0
has comment: http://stackoverflow.com/comment/86575050
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/49779828
has answer: http://stackoverflow.com/a/49779828
tagged with: http://stackoverflow.com/tag/csv
has body: I have read many questions about this subject but I can't seem to find the reason why my code does not work. After doing some scraping from a website, I'm basically trying to sort a Pandas Dataframe by column ('Date'). I have tried converting the date to a datetime object, but that didn't work either, I would appreciate if any of you could advise me what I may be doing wrong here. def find_data(soup): l = [] for b in soup.find_all('div', class_= 'jobInfo'): d = {} company = b.find('h2').find('a') d["Role"] = company['title'].split(':')[0] d["URL"] = 'https://www.computerjobs.ie' + company['href'] company_name = b.find('ul', class_= 'jobDetails').find('li', class_= 'jobCompanyName').get_text() d["Company"] = company_name.split(':')[1].strip() date = b.find('ul', class_= 'jobDetails').find('li', class_= 'jobLiveDate').get_text() d["Date"] = date.split(':')[1].strip() l.append(d) df = pd.DataFrame(l) #Rearranging the order of the columns df = df'Date', 'Company', 'Role', 'URL' #Dropping null rows df=df.dropna() #df['Date'] = pd.to_datetime(df.Date) #df.sort_values('by=["'Date"], ascending = True) df.sort_values(by = ['Date']) df.to_csv("csv_files/pandas_data.csv") Output: ,Date,Employer,Title,URL 0,11/04/2018,nineDots - Technology Recruitment,Senior Python Developer,https://www.computerjobs.ie/jobs/7175653/senior-python-developer.asp 1,10/04/2018,Allen Recruitment,Lead Python Developer,https://www.computerjobs.ie/jobs/7158984/lead-python-developer.asp 2,10/04/2018,Allen Recruitment,Python Developer,https://www.computerjobs.ie/jobs/7158996/python-developer.asp 3,11/04/2018,Solas Consulting Group,Python Developer,https://www.computerjobs.ie/jobs/7231476/python-developer.asp 4,11/04/2018,nineDots - Technology Recruitment,Senior Python Developer,https://www.computerjobs.ie/jobs/7181828/senior-python-developer.asp 5,09/04/2018,realTime Recruitment Ltd.,Senior DevOps Engineer,https://www.computerjobs.ie/jobs/7240215/senior-devops-engineer.asp 6,11/04/2018,FRS Recruitment…
has title: Pandas Dataframe - Issue when sorting Dates
tagged with: python
tagged with: sorting
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/104227834
has text: It is important because Google transcription is more accurate. Let me check for for information as well. Thank you @philnash
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49848869

http://stackoverflow.com/comment/124774501
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49800822
has text: @AlexDeft Think about it. There is only two possibilities. Option a) you are passing a bad URL and SQLAlchemy rightfully errors and b) you are passing a correct URL and SQLAlchemy has a bug that makes it report a false error. Which one do you think it is? If you think it is b), then file a bug with SQLAlchemy. If you think it is a) then I have no way to help, because you are not showing your work.
type: Comment

http://stackoverflow.com/q/49765661
has answer: http://stackoverflow.com/a/49765662
favorite count: 0
possible better answer: http://stackoverflow.com/a/56732315
type: Question
has body: Suppose that this is the layout of the source directory of my PyBuilder project (empty __init__.py in myProject omitted): src ├── main │ └── python │ └── myProject │ └── usefulThing.py └── unittest └── python └── UsefulThingTest.py and the content of UsefulThingTest.py is as follows: import unittest from myProject.usefulThing import usefulFunction class UsefulThingTest(unittest.TestCase): def test_should_do_useful_things(self): self.assertEqual(usefulFunction(42), 1764) When I run pyb, I get the following warnings, and no tests are executed: [WARN] No unit tests executed. [INFO] All unit tests passed. Why doesn't PyBuilder run those tests?
answer count: 2
has answer: http://stackoverflow.com/a/56732315
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49765662
has title: PyBuilder: No unit tests executed
downvote count: 0
tagged with: python
tagged with: pybuilder
type: AnsweredQuestion
tagged with: python-unittest

http://stackoverflow.com/a/49832284
has body: Add plt.show() after your lines. pyplot tutorial can be useful.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49832176

http://stackoverflow.com/a/49866660
type: Answer
upvote count: 2
has body: Given reference dataframe df1 and query dataframe df2, you can perform a left merge to extract your result: res = df2.merge(df1, how='left') print(res) # time latitude longtitude pm2.5 # 0 0 1 3 NaN # 1 1 0 5 1.0 Loops are highly discouraged unless your operation cannot be vectorised.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49866551
answers question: http://stackoverflow.com/q/49866551
score: 2

http://stackoverflow.com/a/49822110
answers question: http://stackoverflow.com/q/49821837
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
has body: You can use browser.page_source, convert it to a string and use regular expression findall. Python Selenium accessing HTML source Python regex findall
accepted answer of: http://stackoverflow.com/q/49821837
type: Answer

http://stackoverflow.com/comment/86645746
comment on: http://stackoverflow.com/q/49814731
score: 0
type: QuestionComment
has text: Do you do other output to `f`? Do you really use "wb"? I get your error when I use "w" instead.
type: Comment

http://stackoverflow.com/comment/86781298
has text: The `csv` format is `m` rows of `n` columns separated by comma (or some other known delimiter). How do you expect to save a 3d array in that format? Have you tried to reshape the array to `(20075, 22*25)`?
score: 0
comment on: http://stackoverflow.com/q/49876524
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49881167
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49881112
has body: Use GroupBy.transform by max or map aggregated Series: compare_table['highest_random#1'] = compare_table.groupby('id')['random#'].transform('max') #a bit slowier alternative s = compare_table.groupby('id')['random#'].max() compare_table['highest_random#2'] = compare_table['id'].map(s) print (compare_table) id day# random# highest_random# highest_random#1 highest_random#2 0 1 1 2 5.0 5 5 1 1 2 5 5.0 5 5 2 1 3 1 5.0 5 5 3 2 1 6 6.0 6 6 4 2 2 4 6.0 6 6 5 3 1 5 9.0 9 9 6 3 2 9 9.0 9 9 7 3 3 3 9.0 9 9
score: 2
answers question: http://stackoverflow.com/q/49881112
has comment: http://stackoverflow.com/comment/86778356
has comment: http://stackoverflow.com/comment/86778387
type: Answer
has comment: http://stackoverflow.com/comment/86779128
has comment: http://stackoverflow.com/comment/86779153
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/49775067
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49775162
upvote count: 1
has answer: http://stackoverflow.com/a/49775162
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86564998
tagged with: python
has title: Bottle Python ping check 5 pings
tagged with: bottle
has body: I am trying to write a script to print a ping check to the browser with 5 pings. This script: from bottle import route, run, template import subprocess @route('/pings/&lt;ip&gt;') def ping(ip): param = '-c 1' command = ['ping', param, ip] num = 0 while (num &lt; 6): return subprocess.check_output(command) num += 1 run(host='0.0.0.0', port=8080) Currently outputs to the browser as follows: PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=54 time=17.7 ms --- 8.8.8.8 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 17.756/17.756/17.756/0.000 ms But it doesn't print out 5 pings like I expect it to. It only prints out the one ping, is it for some reason only printing out the last one? How can I print out 5 pings like it would look if you ran it from a shell command. Thanks.

http://stackoverflow.com/comment/122842152
has text: This kills all the input code of all cells. What if you only want to kill the input code of some cells but not all? I suspect there must be a Cell Metadata that will do the trick but I just can't figure it out.
type: AnswerComment
comment on: http://stackoverflow.com/a/58524517
score: 3
type: Comment

http://stackoverflow.com/comment/86690235
comment on: http://stackoverflow.com/q/49837475
has text: `str.join` is a method of strings. You have to call it from the string you want to use to join the other strings. To join them with a comma, you would do `','.join(commandSplit)`
type: Comment
type: QuestionComment
score: 0

pandas
tags question: http://stackoverflow.com/q/49798372
tags question: http://stackoverflow.com/q/49843461
tags question: http://stackoverflow.com/q/49780347
tags question: http://stackoverflow.com/q/49762381
tags question: http://stackoverflow.com/q/49844644
tags question: http://stackoverflow.com/q/49836620
tags question: http://stackoverflow.com/q/49888898
tags question: http://stackoverflow.com/q/49806757
tags question: http://stackoverflow.com/q/49886902
tags question: http://stackoverflow.com/q/49830772
tags question: http://stackoverflow.com/q/49800835
tags question: http://stackoverflow.com/q/49882929
tags question: http://stackoverflow.com/q/49903773
tags question: http://stackoverflow.com/q/49761425
tags question: http://stackoverflow.com/q/49833874
tags question: http://stackoverflow.com/q/49760092
tags question: http://stackoverflow.com/q/49801834
tags question: http://stackoverflow.com/q/49881112
tags question: http://stackoverflow.com/q/49864401
tags question: http://stackoverflow.com/q/49833144
tags question: http://stackoverflow.com/q/49758828
tags question: http://stackoverflow.com/q/49763005
tags question: http://stackoverflow.com/q/49861656
tags question: http://stackoverflow.com/q/49784457
tags question: http://stackoverflow.com/q/49844685
tags question: http://stackoverflow.com/q/49765834
tags question: http://stackoverflow.com/q/49879976
tags question: http://stackoverflow.com/q/49863243
tags question: http://stackoverflow.com/q/49792651
tags question: http://stackoverflow.com/q/49778417
tags question: http://stackoverflow.com/q/49827096
tags question: http://stackoverflow.com/q/49914567
tags question: http://stackoverflow.com/q/49913241
tags question: http://stackoverflow.com/q/49781127
tags question: http://stackoverflow.com/q/49815709
tags question: http://stackoverflow.com/q/49761303
tags question: http://stackoverflow.com/q/49805586
tags question: http://stackoverflow.com/q/49809438
tags question: http://stackoverflow.com/q/49831995
tags question: http://stackoverflow.com/q/49903037
tags question: http://stackoverflow.com/q/49846343
tags question: http://stackoverflow.com/q/49775840
tags question: http://stackoverflow.com/q/49802301
tags question: http://stackoverflow.com/q/49837404
tags question: http://stackoverflow.com/q/49802955
tags question: http://stackoverflow.com/q/49833636
tags question: http://stackoverflow.com/q/49860435
tags question: http://stackoverflow.com/q/49882714
tags question: http://stackoverflow.com/q/49787829
tags question: http://stackoverflow.com/q/49769302
tags question: http://stackoverflow.com/q/49857336
tags question: http://stackoverflow.com/q/49877387
tags question: http://stackoverflow.com/q/49886660
tags question: http://stackoverflow.com/q/49810707
tags question: http://stackoverflow.com/q/49815778
tags question: http://stackoverflow.com/q/49845989
tags question: http://stackoverflow.com/q/49800487
tags question: http://stackoverflow.com/q/49811865
tags question: http://stackoverflow.com/q/49877129
tags question: http://stackoverflow.com/q/49769706
tags question: http://stackoverflow.com/q/49909514
tags question: http://stackoverflow.com/q/49823178
tags question: http://stackoverflow.com/q/49910264
tags question: http://stackoverflow.com/q/49770113
tags question: http://stackoverflow.com/q/49787325
tags question: http://stackoverflow.com/q/49865132
tags question: http://stackoverflow.com/q/49864912
tags question: http://stackoverflow.com/q/49826116
tags question: http://stackoverflow.com/q/49884863
tags question: http://stackoverflow.com/q/49813964
tags question: http://stackoverflow.com/q/49888258
tags question: http://stackoverflow.com/q/49854524
tags question: http://stackoverflow.com/q/49841954
tags question: http://stackoverflow.com/q/49861147
tags question: http://stackoverflow.com/q/49875484
tags question: http://stackoverflow.com/q/49784969
tags question: http://stackoverflow.com/q/49842343
tags question: http://stackoverflow.com/q/49896450
tags question: http://stackoverflow.com/q/49822424
tags question: http://stackoverflow.com/q/49916607

http://stackoverflow.com/comment/86813576
type: AnswerComment
score: 1
has text: thanks a lot, that's what I did, I used selenium and it works just fine !
comment on: http://stackoverflow.com/a/49888370
type: Comment

http://stackoverflow.com/comment/86824323
type: Comment
has text: Does `html.replace('text-align: right;', 'text-align: center')` solve the issue?
type: AnswerComment
comment on: http://stackoverflow.com/a/49903930
score: 0

http://stackoverflow.com/q/49806573
upvote count: 3
linked to: http://stackoverflow.com/q/37696206
has comment: http://stackoverflow.com/comment/86629493
has comment: http://stackoverflow.com/comment/86628117
tagged with: anaconda
downvote count: 0
has comment: http://stackoverflow.com/comment/86631043
tagged with: kivy
linked to: http://stackoverflow.com/q/7674790
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49834505
has title: Can't pyinstall a Kivy python program
tagged with: pycharm
tagged with: pyinstaller
answer count: 1
has body: I can't get pyinstaller to create an .exe out of my python code. I think it must have something to do with A: I'm using Kivy for the prodject, and B: I'm trying to use anaconda as my python interpreter. For awhile it would make the .exe but when I launched it it would give a bunch of errors about no window being available. I tried installing/uninstalling packages, re-setting up my python interpreter on my editor (PyCharm), and finally I re-installed anaconda. Now when I try to run it, it wont even create the .exe, it just gives me an error. This is the command I'm running in the terminal, (venv) C:\Users\Luc\PycharmProjects\GoogleCommandCenter&gt;pyinstaller --onefile main.spec This is the error message I'm getting, 895 INFO: PyInstaller: 3.3.1 896 INFO: Python: 3.6.4 896 INFO: Platform: Windows-10-10.0.16299-SP0 898 INFO: UPX is not available. 900 INFO: Extending PYTHONPATH with paths ['C:\\Users\\Luc\\PycharmProjects\\GoogleCommandCenter', 'C:\\Users\\Luc\\PycharmProjects\\GoogleCommandCenter', 'C:\\Users\\Luc\\PycharmProjects\\GoogleCommandCenter\\venv', 'C:\\Users\\Luc\\PycharmProjects\\GoogleCommandCenter\\venv\\Scripts\\python.exe'] 901 INFO: checking Analysis 901 INFO: Building Analysis because out00-Analysis.toc is non existent 901 INFO: Initializing module dependency graph... 907 INFO: Initializing module graph hooks... 910 INFO: Analyzing base_library.zip ... 4627 INFO: running Analysis out00-Analysis.toc 4629 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable required by c:\users\luc\pycharmprojects\googlecommandcenter\venv\scripts\python.exe 5229 INFO: Caching module hooks... 5233 INFO: Analyzing main.py 8793 INFO: Processing pre-find module path hook distutils 8795 INFO: distutils: retargeting to non-venv dir 'C:\\Users\\Luc\\Anaconda3\\Lib\\distutils' 10009 INFO: Processing pre-find module path hook site 10010 INFO: site: retargeting to fake-dir 'c:\\users\\luc\\pycharmprojects\\googlecommandcenter\\venv\\lib\\si…
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49834505
score: 3

http://stackoverflow.com/q/49841597
score: 1
has comment: http://stackoverflow.com/comment/86698020
tagged with: python
has comment: http://stackoverflow.com/comment/86697913
has body: You would think it's quite simple, but the following code doesn't work as I would expect: from hashlib import md5 from PIL import Image im = Image.open("/tmp/original.jpg") im.save("/tmp/new.jpg", quality="keep") original = Image.open("/tmp/original.jpg") new = Image.open("/tmp/new.jpg") assert md5(original.tobytes()).hexdigest() == md5(new.tobytes()).hexdigest() Why is it that when I'm simply saving an image as a new file, and keeping the quality settings the same, that the image data isn't identical? What am I missing? Update (Explanation): My problem is that I have a Pillow JpegImage object being handed to my code as part of a pipeline and I don't have control over the step at which the file is saved to disk: &lt;magic&gt; → &lt;my code&gt; → &lt;magic that saves to disk&gt; All I want my code to do is add/update/replace (any of these) the EXIF data for the to-be-saved jpeg image. As this info doesn't appear to be editable on an image object, the only way that I can figure to do this is to save the image to a temporary place (like BytesIO), save it and the re-open it with Image.open() before passing it to the next function in the chain. Please tell me that there's a smarter, more efficient way to do this?
has comment: http://stackoverflow.com/comment/86698036
answer count: 0
has title: How to get Pillow to make identical copies (edit EXIF in-line)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86697896
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86720195
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/86730648

http://stackoverflow.com/q/49852271
has comment: http://stackoverflow.com/comment/86719126
has comment: http://stackoverflow.com/comment/86718999
linked to: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/86719225
has comment: http://stackoverflow.com/comment/86719091
tagged with: python
has answer: http://stackoverflow.com/a/49852345
duplicate of: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/86719094
has comment: http://stackoverflow.com/comment/86719056
type: AnsweredQuestion
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86719361
has comment: http://stackoverflow.com/comment/86719255
answer count: 1
downvote count: 1
has title: what is the difference between [[False] * 3] * 3 and [[False for i in range(3)] for j in range(3)]?
has comment: http://stackoverflow.com/comment/86719177
accepted answer: http://stackoverflow.com/a/49852345
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86719042
has body: I am trying to initialize the 2D array with false values. Both instructions mentioned below are producing same results. Please help to know the difference between the two ? Input [[False] * 3] * 3 [[False for i in range(3)] for j in range(3)] Output [[False, False, False], [False, False, False], [False, False, False]] [[False, False, False], [False, False, False], [False, False, False]]

http://stackoverflow.com/q/49880150
score: 3
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86779997
tagged with: post
tagged with: curl
has body: I want to use the requests library in Python to make a POST request. But the API I'm trying to use uses curl to make the request and I don't know how to convert that. This is the curl command: curl -X POST "https://api/recognize?secret_key=abc" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "image=@/path/to/image.jpg;type=image/jpeg" For the moment I'm just using a URL instead of the image itself as a workaround. Code: params = ( ('image_url', '2015-BMW-320djpg'), ('secret_key', 'abc'), ) response = requests.post('https://api/recognize_url', params=params)
upvote count: 3
has answer: http://stackoverflow.com/a/49880670
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/73632830
has title: Converting CURL command to Python with requests
tagged with: python-requests
favorite count: 0
type: Question

http://stackoverflow.com/comment/86739122
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49861900
has text: @Elvir Muslic Not a stupid question! I checked, and apparently there are no issues with the machine.

http://stackoverflow.com/a/49886259
accepted answer of: http://stackoverflow.com/q/49886199
has comment: http://stackoverflow.com/comment/86789296
has body: You may try inner merge. First, you may inner merge df1 with df2 and then you will get plates only for common rows and you can rename new df1's column as per your need df1 = df1.merge(df2, on="tag", how = 'inner') df1['new column'] = df1['plate'] del df1['plate'] I hope this works.
has comment: http://stackoverflow.com/comment/86788816
answers question: http://stackoverflow.com/q/49886199
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86789530
has comment: http://stackoverflow.com/comment/86789382
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86789232

http://stackoverflow.com/a/49791801
downvote count: 0
has body: Boolean array indexing: &gt;&gt;&gt; x = np.array([[1, 2, 3], ... [4, 5, 6]]) &gt;&gt;&gt; d = np.array([1, 0, 1]) &gt;&gt;&gt; x[:, d==1] array([[1, 3], [4, 6]])
type: Answer
accepted answer of: http://stackoverflow.com/q/49791681
score: 2
answers question: http://stackoverflow.com/q/49791681
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/49825770
has comment: http://stackoverflow.com/comment/119970345
score: 1
favorite count: 0
has body: Here is something curious which I cannot explain. Consider this code segment: import subprocess command = ['tasklist.exe', '/m', 'imm32.dll'] p = subprocess.Popen(command, stdout=subprocess.PIPE) out, err = p.communicate() The call to communicate() hung and I had to break out with Ctrl+C. After that, the tasklist process was still running, which I had to kill it with taskkill.exe. Take a look at the behaviors of tasklist.exe in the table below: | Command | Behavior | |-------------------------------------|----------| | ['tasklist.exe', '/m', 'imm32.dll'] | Hung | | ['tasklist.exe', '/m'] | Hung | | ['tasklist.exe'] | OK | It seems when the /m flag is present, the process does not return. It just runs forever. I have also tried the following and it also hung: os.system('tasklist.exe /m imm32.dll') How can I launch this command and not hang? Update It turns out that the communicate call did not hang, but took up to 10 minutes to finished, something that would take a couple of seconds if I ran the command from the cmd.exe prompt. I believe this has to do with buffering, but have not found a way to make it to finish faster.
has comment: http://stackoverflow.com/comment/86671001
has comment: http://stackoverflow.com/comment/86671043
type: Question
has comment: http://stackoverflow.com/comment/86671019
answer count: 0
has comment: http://stackoverflow.com/comment/86671073
upvote count: 1
tagged with: python
tagged with: tasklist
type: UnansweredQuestion
has title: Invoke tasklist /m with subprocess hangs
has comment: http://stackoverflow.com/comment/86667435
tagged with: python-2.7
downvote count: 0
has comment: http://stackoverflow.com/comment/86667274

http://stackoverflow.com/comment/86689418
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49837058
has text: Don't say 'run a classifier', that could mean either 'train' or 'predict'. You meant 'train'. Also, you haven't shown the code that instantiates `lrRocAucTest`, it presumably wraps your LR classifier that takes a random seed `random_state`. For determinism and reproducibility, you probably want to set that seed to one of a set of known values on each run.

http://stackoverflow.com/a/49795680
has comment: http://stackoverflow.com/comment/86606595
has body: this is overcomplex and syntaxically incorrect. Since you just need to prefix, just create a dictionary keyword => prefix: d = {"DR":"Detection Rate","FAR":"False Alarm Rate","FNR":"False N Rate"} then prepend the value (and if the token isn't in the dictionary, repeat the key, it covers half of your values apparently): for line in f: ligne = line.split() key = ligne[0] ligne.insert(0,d.get(key,key)) EDIT: comments hint at a trailing colon after the first word. Just change to: key = ligne[0].rstrip(":") ligne.insert(0,d.get(key,key)+":") Notes: insert works in place: saves some temp list creation (doesn't save element shifting, though) for line in f avoids reading the file at once. It just reads line by line.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49795389
upvote count: 1
has comment: http://stackoverflow.com/comment/86606543
accepted answer of: http://stackoverflow.com/q/49795389
score: 1
has comment: http://stackoverflow.com/comment/86606060
type: AcceptedAnswer

http://stackoverflow.com/comment/86831974
has text: @Carlos Cordoba Will do. Thank you.
type: QuestionComment
comment on: http://stackoverflow.com/q/49889137
type: Comment
score: 0

http://stackoverflow.com/q/49875740
linked to: http://stackoverflow.com/q/44700715
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/42373104
has title: ModuleNotFoundError: No module named 'matplotlib.finance'
has body: I am trying to run a flask project, I get the following error. File "main.py", line 4, in &lt;module&gt; from anomalies import anomalies_result_visualization File "D:\coursework\anomalies\anomalies_result_visualization.py", line 4, in &lt;module&gt; import matplotlib.finance as finance ModuleNotFoundError: No module named 'matplotlib.finance' My requirements.txt is as follows. Flask==0.12.1 matplotlib==1.4.3 six pandas statsmodels arch sklearn mpld3 Any help would be welcomed and thanks in advance. :)
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/44700715
has comment: http://stackoverflow.com/comment/86766963
tagged with: python
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/108728700
answer count: 0
has comment: http://stackoverflow.com/comment/86766956
tagged with: finance
tagged with: matplotlib
upvote count: 1
has comment: http://stackoverflow.com/comment/86769577
downvote count: 1
has comment: http://stackoverflow.com/comment/105731159

http://stackoverflow.com/q/49760907
score: 0
possible better answer: http://stackoverflow.com/a/49761029
answer count: 3
has body: Say I have this data my_list_of_tuples = [ ('bill', [(4, ['626']), (4, ['253', '30', '626']), (4, ['253', '30', '626']), (4, ['626']), (4, ['626']), (4, ['626'])]), ('sarah', [(2, ['6']), (2, ['2', '6']), (2, ['2', '6']), (2, ['6']), (2, ['6']), (2, ['6'])]), ('fred', [(1, ['6']), (1, ['2']), (1, ['2'])]) ] And I want to keep out all the items that are longest in a sub-tuple list element, and duplicates are removed, so that I am left with my_output_list_of_tuples = [ ('bill', [(4, ['253', '30', '626'])]), ('sarah', [(2, ['2', '6'])]), ('fred', [(1, ['6']), (1, ['2'])])] So far I tried my_output_list_of_tuples = [(x[0], max(x[1], key=lambda tup: len(tup[1]))) for x in my_list_of_tuples] but that does not work for fred, because the max function only returns one item. I also tried a few map attempts and lamba but got less far. I'm OK to break it up like for my_list_of_tuples_by_person_name in my_list_of_tuples: #Do something with my_list_of_tuples_by_person_name[1] Any ideas? Thanks in advance :)
type: Question
has comment: http://stackoverflow.com/comment/86537304
has title: Filter a list of tuples on the longest item in the tuple
has answer: http://stackoverflow.com/a/49761307
has answer: http://stackoverflow.com/a/49761129
has answer: http://stackoverflow.com/a/49761029
tagged with: python
accepted answer: http://stackoverflow.com/a/49761129
type: AnsweredQuestion

http://stackoverflow.com/q/49818325
score: 0
has comment: http://stackoverflow.com/comment/86652901
has body: I am trying to install BigARTM on Ubuntu following the instruction. Everything goes fine until I run sudo make. It generates the following error: [ 99%] Building python package bigartm running build running build_py [ 99%] Built target python_bigartm_build [100%] Building wheel bigartm usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: invalid command 'bdist_wheel' python/CMakeFiles/python_bigartm_wheel.dir/build.make:57: recipe for target 'python/CMakeFiles/python_bigartm_wheel' failed make[2]: *** [python/CMakeFiles/python_bigartm_wheel] Error 1 CMakeFiles/Makefile2:781: recipe for target 'python/CMakeFiles/python_bigartm_wheel.dir/all' failed make[1]: *** [python/CMakeFiles/python_bigartm_wheel.dir/all] Error 2 Makefile:140: recipe for target 'all' failed I suspected that the problem is connected with wheel. So I updated wheel: user@user:~/bigartm/build$ pip install wheel Collecting wheel Using cached wheel-0.31.0-py2.py3-none-any.whl Installing collected packages: wheel Successfully installed wheel-0.31.0 Also I updated wheel in conda, and it shows now: $ conda list | grep wheel wheel 0.31.0 py36_0 wheel 0.31.0 &lt;pip&gt; That did not help.
answer count: 1
has comment: http://stackoverflow.com/comment/86652406
has comment: http://stackoverflow.com/comment/86652931
type: Question
type: UnansweredQuestion
tagged with: python-wheel
tagged with: pip
has comment: http://stackoverflow.com/comment/86652195
tagged with: python
has title: Wheel issue with BigARTM
has comment: http://stackoverflow.com/comment/86652399
has comment: http://stackoverflow.com/comment/86652895
has comment: http://stackoverflow.com/comment/86652798
has answer: http://stackoverflow.com/a/75798586

http://stackoverflow.com/comment/86777685
type: AnswerComment
has text: But the returned list have a new value each time. By print I find that its value is: 0,1,2,3,4
comment on: http://stackoverflow.com/a/49880646
score: 0
type: Comment

http://stackoverflow.com/comment/86808674
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49896064
has text: By that you mean to type the import numpy in the the console in spyder? If so it happen there too

http://stackoverflow.com/q/49798244
has body: I have a data frame with that contains several columns. I would like to iterate some columns of the data frame and convert each row to a list based on a function called tokenizer. columns = ['stemmed', 'lemmatized', 'lem_stop','stem_stop', 'lem_stop_nltk', 'stem_stop_nltk'] tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') sentences = [] for i in columns: for tweet in df[i]: sentences += tweet_to_sentences(tweet, tokenizer) However, I would like to create 6 different lists rather than one. How can I change the name of the variable based on variable i in each step of the first loop (i.e. for i in columns:) I was thinking something like this for i in columns: for tweet in df[i]: sentences += tweet_to_sentences(tweet, tokenizer) i_list = sentences where i_list will translate in stemmed_list, lemmatized_list, lem_stop_list and so on. Any idea?
score: 0
answer count: 1
tagged with: rename
tagged with: loops
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49798424
tagged with: python
has title: Passing a list to a new list with a dynamic name after each step of a loop

http://stackoverflow.com/comment/94185294
has text: @MrYouMath You shouldn't edit the question, you should post an answer
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49825679

http://stackoverflow.com/comment/86557319
type: QuestionComment
has text: I may not fully understand the question. But it seems that you want to just have numbers on your axes? In that case calculate the numbers you want from the datetimes and use those as input to `plot`.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49760712

http://stackoverflow.com/a/49812333
has body: Alternatively, by taking reference Tim Seed's code. this can be used. from scipy.spatial import distance some_pt1 = [(10.76,2.9),(3.24,4.28),(7.98,1.98),(3.21,9.87)] some_pt2 = [(11.87,6.87), (67.87,8.88), (44.44, 6.78), (9.81, 1.09), (6.91, 0.56), (8.76, 8.97), (8.21, 71.66)] empthy_dict = {} for i in range(len(some_pt1)): for j in range(len(some_pt2)): dist = distance.euclidean(some_pt1[i],some_pt2[j]) empthy_dict[dist] = [some_pt1[i],some_pt2[j]] shortest = sorted(empthy_dict.keys())[0] points = empthy_dict[shortest] print('Shortest distance is ' ,shortest,' and points are ' ,points)
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49811583
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49785298
tagged with: nvidia
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49785512
has title: AttributeError: 'module' object has no attribute 'from_tensorflow_frozen_model'
type: UnansweredQuestion
has body: I am trying to convert my PB model to tenrorrt uff model to make it work on tx2. I used the example code from the Nvidia forum and tried to execute it. I know it is some python package related issue but I am not able to solve it I get following error with the below code import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import tensorrt as trt from tensorrt.parsers import uffparser import pycuda.driver as cuda import pycuda.autoinit import numpy as np from random import randint # generate a random test case from PIL import Image from matplotlib.pyplot import imshow #to show test case import time #import system tools import os import uff uff_model = uff.from_tensorflow_frozen_model('./rcnn_3chan.pb', ['image_tensor','detection_scores','detection_boxes' ,'detection_classes' ,'num_detections']) parser.register_output("image_tensor") parser.register_output("detection_scores") parser.register_output("detection_boxes") parser.register_output("detection_classes") parser.register_output("num_detections") WARNING:tensorflow:From /usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/datasets/base.py:198: retry (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version. Instructions for updating: Use the retry module or similar alternatives. Traceback (most recent call last): File "uff.py", line 5, in &lt;module&gt; import tensorrt as trt File "/usr/local/lib/python2.7/dist-packages/tensorrt/__init__.py", line 77, in &lt;module&gt; from tensorrt import infer, parsers, utils, lite, plugins File "/usr/local/lib/python2.7/dist-packages/tensorrt/utils/__init__.py", line 53, in &lt;module&gt; from ._utils import * File "/usr/local/lib/python2.7/dist-packages/tensorrt/utils/_utils.py", line 59, in &lt;module&gt; import uff File "/home/fts/Downloads/Amruta/uff.py", line 20, in &lt;module&gt; uff_model = uff.from_tensorflow_frozen_model('./rcnn_3chan.pb', ['image_tensor','detect…
tagged with: python
tagged with: tensorrt
downvote count: 0
answer count: 1
score: 1
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/86700077
comment on: http://stackoverflow.com/a/49842389
has text: I see: You need to do Item.click() and not href.click()
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49909061
downvote count: 0
has answer: http://stackoverflow.com/a/49909185
has comment: http://stackoverflow.com/comment/86834174
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86834484
has answer: http://stackoverflow.com/a/49909471
tagged with: python
has comment: http://stackoverflow.com/comment/86834187
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86835143
has title: Product of lists of lists with variable members
has body: Say I have this input data my_input_list = [[A],[A,B,C],[D],[D,E,F],[A,B,C,D,E,F],[A,C,E]] items_that_appear_twice = [A,B,C] items_that_appear_four = [D,E,F] And I want to create an expansion such that some elements are only allowed to appear twice. my_output_list = [ [A],[A], [A,B,C],[A,B,C], [D],[D],[D],[D], [D,E,F],[D,E,F],[D,E,F],[D,E,F], [A,B,C,D,E,F],[A,B,C,D,E,F],[D,E,F],[D,E,F], [A,C,E],[A,C,E],[E],[E]] I tired a few ideas and didn't find a really neat solution, like building lists of four and list.remove() from them which generated two empty lists. For example list removal techniques on my_input_list[0]*4 gives [A],[A],[],[] (two empty lists) when I want [A],[A] .
tagged with: list
possible better answer: http://stackoverflow.com/a/49909346
answer count: 3
tagged with: membership
has answer: http://stackoverflow.com/a/49909346
score: 1
accepted answer: http://stackoverflow.com/a/49909185

http://stackoverflow.com/comment/86788161
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49885953
has text: The question is not clear, particularly the last part. What is 'my algorithm'? Where did `adj_list` come from? Why is it the same shape as `graph` but contains different data? What are the inner dictionary values, are they edge weights?

http://stackoverflow.com/comment/86745930
type: QuestionComment
comment on: http://stackoverflow.com/q/49863071
score: 0
has text: Is anything about the data unexpected? Can you provide a minimum recreate-able example? At the moment I'm not sure the question provides enough information for an answer.
type: Comment

http://stackoverflow.com/comment/86791207
type: Comment
comment on: http://stackoverflow.com/q/49887159
has text: One question, why httpd? I am using gunicorn, not apache. I have a vm on the machine i send the resquest, and this machine didnt have httpd. (and to send the same request to the vm where i have the copy of the code works fine every single time).
score: 0
type: QuestionComment

http://stackoverflow.com/q/49801451
linked to: http://stackoverflow.com/q/44888858
has comment: http://stackoverflow.com/comment/86617779
score: 2
type: AnsweredQuestion
tagged with: pandas
has body: I have pandas.DataFrame like this : time num 1 a ,A 3 2 a ,B 3 3 a ,C 1 4 b ,A 4 5 b ,A 4 6 a ,B 3 7 d ,B 2 I want to remove the rows where time is unique in the dataset. The result would be: time num 2 a ,B 3 4 b ,A 4 5 b ,A 4 6 a ,B 3 Is there any way to do this without a loop???
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/44888858
has answer: http://stackoverflow.com/a/49801556
upvote count: 2
accepted answer: http://stackoverflow.com/a/49801556
has title: Removing unique rows in Python
downvote count: 0
answer count: 1
tagged with: python

http://stackoverflow.com/q/49806787
score: -1
accepted answer: http://stackoverflow.com/a/49807254
answer count: 4
has answer: http://stackoverflow.com/a/49806883
has comment: http://stackoverflow.com/comment/86637526
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 0
has body: I have a list that contains six lists which each contain 6 floats. I want to find the max value from the overall set, record its x and y values (for lack of a better term...as if I am considering the list of list a graph) and then remove that list from consideration so that each element in the outer list can only be chosen once. I came up with the following method to do it, which works. But I am afraid it is terribly inelegant and there is probably a much better way to go about this. Original list [[5.468295520651542, 37.0564281559046, 43.455497382198956, 3.781268179173938, 0.11634671320535195, 10.122164048865619], [7.3991031390134525, 48.87892376681614, 26.00896860986547, 4.708520179372197, 5.829596412556054, 7.174887892376682], [30.382775119617225, 2.6315789473684212, 0.7177033492822966, 64.5933014354067, 1.4354066985645932, 0.23923444976076555], [5.112474437627812, 2.8629856850715747, 6.952965235173824, 3.476482617586912, 76.27811860940696, 5.316973415132924], [85.98979013045944, 6.693136698808849, 3.5734543391945546, 1.5314804310833805, 1.1344299489506522, 1.0777084515031197], [5.565529622980251, 65.1705565529623, 2.5733093955715143, 5.326152004787552, 11.789347695990426, 9.57510472770796]] My Code maxmaxlist=[] maxxlist=[] maxylist=[] for i in range(0,6): maxlist=[] xlist=[] for j in range(0,len(templist)): temp = (max(templist[j])) maxlist.append(temp) xlist.append(templist[j].index(temp)) temp = max(maxlist) maxmaxlist.append(temp) temp2 = maxlist.index(temp) maxylist.append((templist[temp2]).index(temp)) maxxlist.append(temp2) templist[temp2] = [0] print maxmaxlist, maxxlist, maxylist
has answer: http://stackoverflow.com/a/49807020
downvote count: 1
has comment: http://stackoverflow.com/comment/86658194
has comment: http://stackoverflow.com/comment/86629120
possible better answer: http://stackoverflow.com/a/49806883
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86655991
has answer: http://stackoverflow.com/a/49813521
has comment: http://stackoverflow.com/comment/86628470
has title: Getting maximum values and x,y coordinates from a list of list without replacement
tagged with: algorithm
has answer: http://stackoverflow.com/a/49807254
tagged with: python

http://stackoverflow.com/a/49916387
type: Answer
has body: execute_async_script's name confuses many people. It doesn't executes the script asynchronously from your test code, it only allows you to execute a script which runs asynchronously from the browser's main thread, like AJAX calls and JavaScript setTimeout. These JavaScript functions and alike themselves return almost immediately, but they take a (JavaScript) function argument that is executed when the asynchronous operation completes. What execute_async_script does is exactly like execute_script, but instead of returning when the function itself returns (which is almost immediately) it provides its own callback JavaScript function (which it passes as the last argument, that's why the arguments[arguments.length - 1] is needed), that you can use in the JavaScript code you're passing into execute_async_script, to pass it on to the asynchronous function as the callback. execute_async_script returns only when this callback is called, instead of returning immediately. For example, in the following code, the call to execute_async_script acts like a delay of 2 seconds: browser.execute_async_script("setTimeout(arguments[0], 2000)") Note that because I didn't pass any additional arguments to the script, then arguments[0] is actually the last argument. In your case, you don't have to pass self.audio_play_end, but you have to call audio.play() inside your JavaScript snippet to start the audio. execute_async_script should return only when the audio is finished playing.
answers question: http://stackoverflow.com/q/49889898
downvote count: 0
upvote count: 1
score: 1

mysql-python
tags question: http://stackoverflow.com/q/49897357
tags question: http://stackoverflow.com/q/49780054
tags question: http://stackoverflow.com/q/49778957
tags question: http://stackoverflow.com/q/49846084
tags question: http://stackoverflow.com/q/49804582
tags question: http://stackoverflow.com/q/49885870
type: Tag
tags question: http://stackoverflow.com/q/49859657
tags question: http://stackoverflow.com/q/49793767
tag name: mysql-python

http://stackoverflow.com/a/49805773
answers question: http://stackoverflow.com/q/49805389
has comment: http://stackoverflow.com/comment/86626836
type: Answer
has comment: http://stackoverflow.com/comment/86626675
has body: You are probably will need use pack() or grid() to get the results you are looking for. I would not use place() all that much except for some specific needs that you likely wont run into early on in your programming. If you take the time to review grid() and pack() you will find they can do almost anything you need them to do. I had the same idea about place() when I first started learning Python/Tkinter and I have not really used it for the past year in my programs. It just doesn't come up as something I need. Take a look at the below code. I chose to use grid() to place my widget and we can use columnconfigure() and rowconfigure() to add a weight to the row and column the widget is placed in. This allows for expansion of the widget placed there. Per your question in the comments the weight is used to decide how much if any the column and/or row will expand with the window. A default weight of zero will not expand with the window and a value of 1 will evenly expand. You can also set it to more or less than 1 for variable of expansion. Here is a post on the topic of weight that already has a good answer: What does 'weight' do in tkinter? import tkinter as tk root=tk.Tk() root.columnconfigure(0, weight=1) # allows widgets placed on row zero to expand left and right. root.rowconfigure(0, weight=1) # allows widgets placed on column zero to expand up and down. tk.Label(root, text="This label resizes with window", background="grey").grid(row=0, column=0, sticky="nsew") root.mainloop() If you really want to work with place() then you might want to try using a bind() and a function to update the placement. We can bind() the event that handles the resizing of the root window to the function that updates the placement of the label. Take a look at the below code: import tkinter as tk root=tk.Tk() lbl = tk.Label(root, text="This label resizes with window", background="grey") lbl.place(x=10, y=10, width=100, height=20) def update_label(event): w,h = event.width, event.height lb…
score: 0

http://stackoverflow.com/q/49858791
score: 0
has comment: http://stackoverflow.com/comment/86732665
tagged with: http://stackoverflow.com/tag/csv
has title: Python csv file tokenizing
has comment: http://stackoverflow.com/comment/86732460
has body: I am new to Python programming and recently I am trying to read a csv file and then save the data from that csv file to a text file. This is the code I am using csv_file = open('example.csv', 'r') txt_file = open('example.txt', 'w') with open(txt_file, 'w') as my_output_file: with open(csv_file, 'r') as my_input_file: [my_output_file.write(" ".join(row)+'\n') for row in csv.reader(my_input_file)] my_output_file.close() I am getting this error File "c:\Users\Desktop\Folder\tokenizing.py", line 41, in &lt;module&gt; with open(txt_file, 'w') as my_output_file: TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper Does anyone knows why is it complaining?
type: Question
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49858877
has comment: http://stackoverflow.com/comment/86732799
has answer: http://stackoverflow.com/a/49858877
type: AnsweredQuestion

http://stackoverflow.com/comment/131903608
score: 0
comment on: http://stackoverflow.com/a/53734041
type: Comment
type: AnswerComment
has text: where to write export PATH=${PYENV_PYTHON_VERSIONS_HOME}/3.6/bin and where to find piplock ? Please

http://stackoverflow.com/q/49845036
type: Question
has title: Change ASCII to characters in string
has comment: http://stackoverflow.com/comment/86705084
score: 0
has body: i'm trying to convert ASCII values in string to normal characters, but whatever i'll try to do, i'll get output like this\032is\032my\032\output\000 and I need this is my output Thanks for your help!
accepted answer: http://stackoverflow.com/a/49845179
tagged with: python
has answer: http://stackoverflow.com/a/49845179
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/86705819
tagged with: ascii
has answer: http://stackoverflow.com/a/49845128
type: AnsweredQuestion
tagged with: python-3.x
answer count: 2
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/49845128
favorite count: 0

http://stackoverflow.com/comment/86829361
type: AnswerComment
comment on: http://stackoverflow.com/a/49906388
type: Comment
has text: This won't work when value of key_e contains empty lines or special characters too.
score: 0

http://stackoverflow.com/comment/86667406
score: 0
has text: Possible duplicate of https://stackoverflow.com/questions/2568673/inverse-dictionary-lookup-in-python?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
comment on: http://stackoverflow.com/q/49825817
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86746345
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49865394
has text: I tried but I was getting 0 as points all the time

http://stackoverflow.com/comment/86657668
score: 0
type: AnswerComment
has text: you would get delay from the execution time of the code so it would be inaccurate because it would be more than a second.
type: Comment
comment on: http://stackoverflow.com/a/49762284

http://stackoverflow.com/comment/86600656
score: 0
comment on: http://stackoverflow.com/q/49792965
type: Comment
type: QuestionComment
has text: @ytu Is it critical to do this in a single regex? It would be much simpler to handle the two scenarios (string does/does not start with a bracket) with an if-else statement.

http://stackoverflow.com/comment/86569108
comment on: http://stackoverflow.com/q/49776885
has text: Only look at your lat1, lng1, lat2, lng2. In my opinion 609km it's the wrong answer and 3,6km it's the right answer.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49884302
answer count: 2
has body: I'm getting error HOOK-ERROR in before_all: KeyError: 'environment' when running behave from command line Project Structure: features/ * all feature files go here features/steps * all steps go here features/environment.py behave.ini (at the project level) [behave.userdata] environment = int environment.py def before_all(context): userdata = context.config.userdata print(userdata) print(userdata['environment']) output {} HOOK-ERROR in before_all: KeyError: 'environment' On a site note, if i run the features files using pycharm, I dont get this error and the environment printed out. Behave v1.2.6 Any help will be much appreciated
has title: behave HOOK Error empty dict from behave.ini
possible better answer: http://stackoverflow.com/a/60727926
has answer: http://stackoverflow.com/a/60727926
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49947037
has answer: http://stackoverflow.com/a/49947037
tagged with: python-behave
tagged with: python
type: Question

http://stackoverflow.com/comment/86598563
type: Comment
comment on: http://stackoverflow.com/a/49791869
has text: @yamad Why do you care how the input is quoted? It's not like the quotes make any difference in csv (except for empty strings and strings that contain commas, but you get the idea). As long as the csv module reads your file back correctly, what do the quotes matter?
score: 0
type: AnswerComment

http://stackoverflow.com/a/49827053
has body: As the documentation said: A Q() object, like an F object, encapsulates a SQL expression in a Python object that can be used in database-related operations so the Q objects can receive all the fields of a model field or annotated column. so if you define a model like: class Home(models.Model): address = models.CharField(max_length=255) You can use: Home.objects.filter(Q(address="user address")) so you can use any field from your model with the Q objects. you can also use the all built-in fields lookups and your custom-lookups in your queries.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49824321
downvote count: 0
upvote count: 1

vlookup
tag name: vlookup
tags question: http://stackoverflow.com/q/49876778
type: Tag

http://stackoverflow.com/q/49875544
has title: Obtain the boundary of the keyboard by open cv
type: Question
has comment: http://stackoverflow.com/comment/86913193
score: 0
has body: I'm working on a virtual keyboard in opencv and python. I need to detect the largest contour to obtain the boundary of the keyboard and the coordinates of the corners. Here is what I actually need: Here is my code : import numpy as np import cv2 import requests url = 'http://192.168.1.100:8080/shot.jpg' while (True): imgResp = requests.get(url) imgNp = np.array(bytearray(imgResp.content), dtype=np.uint8) frame = cv2.imdecode(imgNp, -1) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ret1, thresh1 = cv2.threshold(hsv, 100, 255, cv2.THRESH_BINARY) thresh1, contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) cv2.drawContours(frame, contours, -1, (0, 255, 0), 3) cv2.imshow('thresh1', thresh1) cv2.imshow('frame', frame) # Q Quit if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cv2.destroyAllWindows()
answer count: 2
has answer: http://stackoverflow.com/a/49890967
type: UnansweredQuestion
tagged with: opencv
has answer: http://stackoverflow.com/a/49876499
tagged with: python

http://stackoverflow.com/a/49885303
accepted answer of: http://stackoverflow.com/q/49879161
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49879161
has comment: http://stackoverflow.com/comment/86815381
has comment: http://stackoverflow.com/comment/86818854
has body: You are really close, but just not quite there. For this sort of thing, there is no need to wrap the menu creation code inside a class, so I changed that to just a function. Here's menu.py: from wx import Menu, MenuBar, MenuEvent, MenuItem, Frame, EVT_MENU def build_main_menu(frame): fileMenu = Menu() exitMenuItem = fileMenu.Append(101, "E&amp;xit", "Close the application") menuBar = MenuBar() menuBar.Append(fileMenu, "&amp;File") frame.Bind(EVT_MENU, frame.onExit, exitMenuItem) frame.SetMenuBar(menuBar) Note that you need to call the onExit using the frame instance, not by trying to call it via a class (MainFrame) that you haven't even imported. Also you do not call an event handler in the bind operation. It will get called when the button is pressed. Next I updated your main.py: import wx import menus class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "My App Title", size=(1200, 800)) self.panel = wx.Panel(self, wx.ID_ANY) mainMenu = menus.build_main_menu(self) def onExit(self, event): self.Close() if __name__ == "__main__": app = wx.App(False) frame = MainFrame() frame.Show() app.MainLoop() There are two changes here. First we don't need to create an instance of the menu module's class as there is no class any longer. Secondly event handlers take two arguments: self and event. Now it works!
type: Answer
score: 0

http://stackoverflow.com/a/49777557
score: 0
type: Answer
has body: turns out that the native matplotlib coming with Anaconda was outdated, so i fixed this error by upgrading it: pip install matplotlib --upgrade
answers question: http://stackoverflow.com/q/49765460

http://stackoverflow.com/comment/86620596
has text: Thanks. I have got clarity from your idea now. I will try this approach.
type: Comment
comment on: http://stackoverflow.com/a/49800494
type: AnswerComment
score: 1

http://stackoverflow.com/q/49858774
tagged with: python-3.7
has answer: http://stackoverflow.com/a/49858921
downvote count: 0
answer count: 1
score: 17
tagged with: python-dataclasses
favorite count: 0
upvote count: 17
type: Question
has title: Why don't Python 3.7 dataclasses support < > <= and >=, or do they?
tagged with: python
has body: For version 3.7.1 of the Transcrypt Python to JavaScript compiler I am currently using the new @dataclass decorator. I had expected that ==, !=, &lt;, &gt;, &gt;=, &lt;= would be supported, as per the PEP's abstract, but it doesn't seem to be the case: from dataclasses import dataclass @dataclass class C: x: int = 10 Some comparisons are not working: &gt;&gt;&gt; c1 = C(1) &gt;&gt;&gt; c2 = C(2) &gt;&gt;&gt; c1 == c2 # ok False &gt;&gt;&gt; c1 &lt; c2 # crash TypeError: '&lt;' not supported between instances of 'C' and 'C' Why are the comparison operators not supported, except for == and !=? Or did I overlook something?
tagged with: transcrypt
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49858921

http://stackoverflow.com/q/49900836
tagged with: pandas
has body: This is a working minimal example of the problem: import pandas as pd example = pd.DataFrame(index=pd.np.arange(2) , columns=['A', 'B', 'C']).astype('object') example.loc[0] = [['a'], 'b', [1,2,3]] example.loc[1] = ['a', 'b', [1,2,3]] I get a ValueError: setting an array element with a sequence Here is what the DataFrame looks like in spyder: I do not understand why the first element has to be "nested". Why is the second row not working? What am I doing wrong? Please have a look at the second column where 'b' can directly be inserted. I voted for the answer I personally like best of all three working solutions which were kindly provided. I find it a bit more pythonic then the other answers and additionally it is also the fastest. For a speed comparison please see this post
upvote count: 3
linked to: http://stackoverflow.com/q/48910956
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49901147
has answer: http://stackoverflow.com/a/49901046
tagged with: python-3.x
has title: pandas Dataframe using loc to insert a row Value Error is raised if the first argument ist not a list?
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/49900998
has answer: http://stackoverflow.com/a/49943035
has answer: http://stackoverflow.com/a/49900998
tagged with: python
possible better answer: http://stackoverflow.com/a/49901046
answer count: 4

http://stackoverflow.com/comment/99616833
has text: the question very clearly says ImportError not a permissions error
comment on: http://stackoverflow.com/a/56162357
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86767022
score: 0
comment on: http://stackoverflow.com/q/49875778
has text: I know ``numpy`` has its own ``numpy.mean()`` function, ``scipy.stats`` has ``scipy.stats.mean()`` I'm interested here in why I can't seem to combine ``numpy`` with ``statistics``.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86830706
has text: *I should not use getter/setters in Python but rather utilize properties. Is this correct?* Yes, there is nearly never a reason to use getter/setter instead of properties.
type: Comment
comment on: http://stackoverflow.com/q/49907111
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86638741
comment on: http://stackoverflow.com/q/49811881
has text: @Zinki: in the end the user should just focus on translating the slice to the other language; they got themselves all confused over precedence while all they need is to understand slicing. Precedence is a red herring here.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86858682
type: Comment
comment on: http://stackoverflow.com/q/49913956
score: 0
type: QuestionComment
has text: I paste it in https://github.com/Yensan/ecdh/blob/master/util/ecdh.py

http://stackoverflow.com/q/49870594
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/86764123
has body: I am trying to install few of the python packages from within a python script and I am using pip.main(install) for that. Below is code snippet try: import requests except: import pip pip.main(['install', '-q', 'requests==2.0.1','PyYAML==3.11']) import requests I have tried using importing main from pip._internal and using pipmain instead of pip.main() but it did not help. I am on pip version 9.0.1 and python 2.7
score: 3
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49875538
has answer: http://stackoverflow.com/a/49882973
has comment: http://stackoverflow.com/comment/86756670
upvote count: 3
has comment: http://stackoverflow.com/comment/86757654
downvote count: 0
has answer: http://stackoverflow.com/a/53197663
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/61891681
answer count: 5
type: UnansweredQuestion
has title: pip.main install fails with 'module' object has no attribute 'main'
has comment: http://stackoverflow.com/comment/86758150
has answer: http://stackoverflow.com/a/49994584

http://stackoverflow.com/comment/86658609
comment on: http://stackoverflow.com/a/49821193
type: AnswerComment
score: 0
type: Comment
has text: Then make them Timestamps with `df.Date = pd.to_datetime(df.Date)`

http://stackoverflow.com/comment/86658419
score: 2
has text: In that case, it doesn't even exist until you have Python objects, so it's not possible to create a query based on that property (since the query generates pure SQL). Performing a list comprehension on the Python objects that get created from your query, like you show, seems like the right thing to do.
type: Comment
comment on: http://stackoverflow.com/q/49821426
type: QuestionComment

http://stackoverflow.com/comment/86706623
type: QuestionComment
comment on: http://stackoverflow.com/q/49845841
score: 0
has text: I thought it might works with `b'test test'` instead of encoding it as utf-8, but it doesn't seem to...
type: Comment

http://stackoverflow.com/comment/86730207
comment on: http://stackoverflow.com/q/49857526
type: QuestionComment
score: 0
type: Comment
has text: you can do that with the random package of numpy. poisson distribution : https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.random.poisson.html gaussian distribution : https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html

http://stackoverflow.com/q/49866905
type: Question
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86749596
tagged with: url
upvote count: 1
tagged with: http
has comment: http://stackoverflow.com/comment/86749704
favorite count: 0
accepted answer: http://stackoverflow.com/a/49867123
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/49867123
score: 1
has comment: http://stackoverflow.com/comment/86749637
has title: check if url is relative to website
has comment: http://stackoverflow.com/comment/86749454
tagged with: python
tagged with: regex
has body: I have big DataFrame of urls from various websites. I would like to check which website it is relative to. Characteristic to define website is its root url cleaned from extra info (for example, for http://www.agpu.net/ root url will be agpu.net So the main goal is to find to which root given url relates. For example, http://www.mordgpi.ru/ should get tag mordgpi.ru but not gpi.ru. Also this should work not for root webpage url only, for example, https://www.mordgpi.ru/our-life/news/46/55116/ Dataset for urls look like: url --------------------- http://pnu.edu.ru/ru/ https://www.dvfu.ru/ http://donstu.ru/ http://www.elsu.ru/ http://ivgpu.com/ http://ivanovo.ac.ru/ http://www.isuct.ru/ And for roots: root ------------- pnu.edu.ru/ru dvfu.ru donstu.ru elsu.ru ivgpu.com ivanovo.ac.ru isuct.ru For given url I tried to get root following way, but this doesn't work well: root = roots['root'].str.lower().apply(lambda x: x in url).to_frame() root = root[root.root] Can I achieve this with regexp or somehow else? Appreciate any help

http://stackoverflow.com/comment/86771783
score: 0
comment on: http://stackoverflow.com/q/49854626
type: Comment
type: QuestionComment
has text: Actually single byte write and read is working fine.. so I had to post this long code to show the problem..

http://stackoverflow.com/comment/86710253
score: 0
type: Comment
has text: Thank you! I couldn't figure out how to account for the numbers.
comment on: http://stackoverflow.com/a/49847680
type: AnswerComment

http://stackoverflow.com/q/49885266
has answer: http://stackoverflow.com/a/49885372
tagged with: regex
type: Question
has comment: http://stackoverflow.com/comment/86786608
has body: Here is my string sample: "#31,456 in this category (Top 100 of category)" My tasks are: get rid of first hashtag (make sure the sentence begins with hashtag) Take all the digits after hashtag (digits may or may not have semicolon in between) Take all the text which is after 31,456 digits and before first parenthesis. get rid of parenthesis with the text inside. Here the regex I came up with. (^\#)(\d+[,]?\d+)(.*)([\(+]) Expected result: Group 2 - 31,456 Group 3 - in this category Basically I need to take the first digits and the sentence after it, grouped separately. This regex does the job only if the string contains parenthesis. But there are cases when it doesn't contain, and in that case it doesn't take anything at all. Please spread some light. I am doing the task with python 3, if that matters.
score: 1
has title: Regular expression with multiple groups can't catch parenthesis
has comment: http://stackoverflow.com/comment/86787190
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86786698
has comment: http://stackoverflow.com/comment/86786570
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49885372
has comment: http://stackoverflow.com/comment/86786663
tagged with: python

http://stackoverflow.com/q/49905640
has comment: http://stackoverflow.com/comment/86827876
has answer: http://stackoverflow.com/a/49905785
type: UnansweredQuestion
tagged with: homebrew
linked to: http://stackoverflow.com/q/13354207
has body: I am trying to link python2.7 to the most recent brew install, which corresponds to python 2.7.13. I know of answers like this link python with brew. But it's still confusing for me. What I need is to have python2.7 link to /usr/local/Cellar/python/2.7.13/bin/python2.7. I can achieve python to link to /usr/local/Cellar/python/2.7.13/bin/python2.7. The problem is I have scripts that call python2.7 and no matter what I do it always returns the old MacOS installation of python2.7.5. I have also tried brew link --overwrite python@2 but the same thing happens. Ideally I would like python to link to python3.6 and python2.7 to link to python2.7.13
tagged with: python
score: 0
answer count: 1
has title: MacOS link recent python2.7 version
tagged with: macos
type: Question

http://stackoverflow.com/comment/86654229
type: QuestionComment
comment on: http://stackoverflow.com/q/49819611
has text: `np.zeros((n, 1))`?
score: 3
type: Comment

http://stackoverflow.com/comment/86684568
has text: @Constantin you can always put it ask a new question . we can help you with that as well :)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49833942

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/49825205
tags question: http://stackoverflow.com/q/49886163
type: Tag
tags question: http://stackoverflow.com/q/49874680
tags question: http://stackoverflow.com/q/49863071
tags question: http://stackoverflow.com/q/49900336
tags question: http://stackoverflow.com/q/49853441
tags question: http://stackoverflow.com/q/49762808
tags question: http://stackoverflow.com/q/49847027
tags question: http://stackoverflow.com/q/49867858
tags question: http://stackoverflow.com/q/49827411
tags question: http://stackoverflow.com/q/49886924
tags question: http://stackoverflow.com/q/49798888
tags question: http://stackoverflow.com/q/49845554
tags question: http://stackoverflow.com/q/49863921
tags question: http://stackoverflow.com/q/49853114
tag name: csv
tags question: http://stackoverflow.com/q/49886000
tags question: http://stackoverflow.com/q/49879688
tags question: http://stackoverflow.com/q/49829614
tags question: http://stackoverflow.com/q/49884740
tags question: http://stackoverflow.com/q/49839176
tags question: http://stackoverflow.com/q/49782869
tags question: http://stackoverflow.com/q/49850258
tags question: http://stackoverflow.com/q/49869562
tags question: http://stackoverflow.com/q/49852719
tags question: http://stackoverflow.com/q/49872584
tags question: http://stackoverflow.com/q/49776386
tags question: http://stackoverflow.com/q/49829618
tags question: http://stackoverflow.com/q/49780330
tags question: http://stackoverflow.com/q/49818842
tags question: http://stackoverflow.com/q/49830757
tags question: http://stackoverflow.com/q/49781283
tags question: http://stackoverflow.com/q/49851509
tags question: http://stackoverflow.com/q/49807004
tags question: http://stackoverflow.com/q/49870829
tags question: http://stackoverflow.com/q/49902448
tags question: http://stackoverflow.com/q/49856675
tags question: http://stackoverflow.com/q/49775314
tags question: http://stackoverflow.com/q/49844685
tags question: http://stackoverflow.com/q/49858791
tags question: http://stackoverflow.com/q/49914567
tags question: http://stackoverflow.com/q/49817091
tags question: http://stackoverflow.com/q/49867987
tags question: http://stackoverflow.com/q/49800487
tags question: http://stackoverflow.com/q/49836505
tags question: http://stackoverflow.com/q/49882935
tags question: http://stackoverflow.com/q/49788330
tags question: http://stackoverflow.com/q/49813964
tags question: http://stackoverflow.com/q/49861147
tags question: http://stackoverflow.com/q/49882804
tags question: http://stackoverflow.com/q/49780054
tags question: http://stackoverflow.com/q/49905403
tags question: http://stackoverflow.com/q/49797091
tags question: http://stackoverflow.com/q/49763919
tags question: http://stackoverflow.com/q/49887948
tags question: http://stackoverflow.com/q/49869483
tags question: http://stackoverflow.com/q/49833487
tags question: http://stackoverflow.com/q/49859957
tags question: http://stackoverflow.com/q/49908389
tags question: http://stackoverflow.com/q/49837899
tags question: http://stackoverflow.com/q/49772590
tags question: http://stackoverflow.com/q/49897887
tags question: http://stackoverflow.com/q/49892444
tags question: http://stackoverflow.com/q/49916371
tags question: http://stackoverflow.com/q/49867472
tags question: http://stackoverflow.com/q/49905198
tags question: http://stackoverflow.com/q/49775963
tags question: http://stackoverflow.com/q/49854979
tags question: http://stackoverflow.com/q/49827677
tags question: http://stackoverflow.com/q/49768234
tags question: http://stackoverflow.com/q/49806028
tags question: http://stackoverflow.com/q/49770126
tags question: http://stackoverflow.com/q/49899165
tags question: http://stackoverflow.com/q/49837060
tags question: http://stackoverflow.com/q/49848563
tags question: http://stackoverflow.com/q/49847311
tags question: http://stackoverflow.com/q/49833283
tags question: http://stackoverflow.com/q/49847153
tags question: http://stackoverflow.com/q/49864359

http://stackoverflow.com/comment/100750866
has text: Can you please help with firefox, I set `binaries=[("C:\\python36\\geckodriver.exe", '.')],`, I get ** No module named 'selenium'**
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49853701

http://stackoverflow.com/comment/86786398
comment on: http://stackoverflow.com/q/49885049
score: 1
has text: By decoding the string using the same codec as that which was using to encode it. How did you create that string?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/126071164
type: Comment
comment on: http://stackoverflow.com/a/71276805
has text: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31166141)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86692173
has text: What is `DataList`?? can you post a `print(DataList)`
comment on: http://stackoverflow.com/q/49837899
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49808218
has comment: http://stackoverflow.com/comment/86691551
has body: Solving the error by assign a mocked_hello to mocked.patch assign a side_effect to mocked func def bonjour(name): return 'bonjour {}'.format(name) def hello(name): return 'Hello {}'.format(name) def my_function(): return hello('Sam') def test_hellow_differnt_from_module(mocker): # mocked func with `test_hello.py` as module name mocked_hello = mocker.patch('test_hello.hello') # assign side_effect to mocked func mocked_hello.side_effect = bonjour # the mocked func return_value changed by side_effect assert mocked_hello('Sam') == 'bonjour Sam' # the mocked func called with Sam, but with different return value mocked_hello.assert_called_with('Sam') call a real function my_function() and the verify that it called hello def test_my_function(mocker): mocker.patch('test_hello.hello', side_effect=bonjour) mf = my_function() hello.assert_called_with('Sam') assert mf == 'bonjour Sam'
has comment: http://stackoverflow.com/comment/135082682
type: AcceptedAnswer
score: 17
has comment: http://stackoverflow.com/comment/86633305
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49807449
has comment: http://stackoverflow.com/comment/86633158
has comment: http://stackoverflow.com/comment/124657600
answers question: http://stackoverflow.com/q/49807449
upvote count: 18
type: Answer

http://stackoverflow.com/comment/86778724
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49879465
score: 0
has text: It doesn't work for me. Firefox on Ubuntu.

http://stackoverflow.com/q/49896788
upvote count: 2
has answer: http://stackoverflow.com/a/49897969
downvote count: 2
has body: i have a file file.txt i want to search a data in a file using phone number for example if i entered 996452544 then result will be Alex 996452544 alex@gmail how to do that in python i do not know i am newbie help me. file.txt Alex 996452544 alex@gmail Jhon 885546694 jhon@gmail Arya 896756885 arya@gmail code.py def searchContact(): number=raw_input("Enter phone number to search data : ") obj1=open("file.txt","r") re=obj1.read() print re obj1.close() searchContact()
tagged with: wxpython
tagged with: python
tagged with: python-requests
answer count: 4
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has title: search data in file using python?
has answer: http://stackoverflow.com/a/49917359
has answer: http://stackoverflow.com/a/49897436
has answer: http://stackoverflow.com/a/49980894
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49917359
possible better answer: http://stackoverflow.com/a/49897436

http://stackoverflow.com/comment/86584890
comment on: http://stackoverflow.com/q/49784739
score: 4
has text: Please post the complete error message including traceback.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49778642
tagged with: python-3.x
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86573353
possible better answer: http://stackoverflow.com/a/49778813
has answer: http://stackoverflow.com/a/49778705
has comment: http://stackoverflow.com/comment/86573502
has comment: http://stackoverflow.com/comment/86573556
tagged with: python
has comment: http://stackoverflow.com/comment/86573386
has title: python eliminating leading zeros in function
has comment: http://stackoverflow.com/comment/86572748
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/86572870
has comment: http://stackoverflow.com/comment/86572864
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/86573865
has answer: http://stackoverflow.com/a/49778813
upvote count: 0
score: -4
has comment: http://stackoverflow.com/comment/86573531
has comment: http://stackoverflow.com/comment/86572705
has comment: http://stackoverflow.com/comment/86572652
has comment: http://stackoverflow.com/comment/86574612
has comment: http://stackoverflow.com/comment/86573243
has comment: http://stackoverflow.com/comment/86573407
favorite count: 0
accepted answer: http://stackoverflow.com/a/49778705
has body: i have a function foo(): that take bytes, concatenates them and returns the int value. however when i pass foo('99', '00'), the leading 0 of a byte will get trimmed. resulting in string '990' instead of '9900'. def foo(value1, value2): return int(value1+value2, 16) I was wondering if there was a graceful way of telling python that the I want the parameters to be treated as a string instead of ints. I am able to do a workaround (shown below) to make sure there are two digits to each parameter. Just wondering if there is another way to go about this def foo(value1,value2): if(len(str(value1)) != 2): value1 = "0"+str(value1) if(len(str(value2)) != 2): value2 = "0"+str(value2) return int(str(value1)+str(value2), 16) Edit: foo(99,00), not foo('99','00') is what is giving me the issues I am dealing with
type: Question

http://stackoverflow.com/a/49881611
type: Answer
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86779036
answers question: http://stackoverflow.com/q/49881391
score: 2
has body: I would ask the user for all the names in the script first. Then ask which name they want the words for. I would search the text word by word till I found the name wanted and copy the following words into a variable until I hit a name that matches someone else in the script. Now people could say the name of another character, but if you assume titles for people speaking are either all caps, or on a single line, the text should be rather easy to filter. for word in script: if word == speaker and word.isupper(): # you may want to check that this is on its own line as well. recording = True elif word in character_names and word.isupper(): # you may want to check that this is on its own line as well. recording = False if recording: spoken_text += word + " "

http://stackoverflow.com/q/49859625
type: Question
tagged with: numpy
has title: Linear Regression: How to find the distance between the points and the prediction line?
linked to: http://stackoverflow.com/q/39840030
upvote count: 6
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/49859875
type: AnsweredQuestion
has body: I'm looking to find the distance between the points and the prediction line. Ideally I would like the results to be displayed in a new column which contains the distance, called 'Distance'. My Imports: import os.path import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.linear_model import LinearRegression %matplotlib inline Sample of my data: idx Exam Results Hours Studied 0 93 8.232795 1 94 7.879095 2 92 6.972698 3 88 6.854017 4 91 6.043066 5 87 5.510013 6 89 5.509297 My code so far: x = df['Hours Studied'].values[:,np.newaxis] y = df['Exam Results'].values model = LinearRegression() model.fit(x, y) plt.scatter(x, y,color='r') plt.plot(x, model.predict(x),color='k') plt.show() Any help would be greatly appreciated. Thanks
downvote count: 0
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/86734529
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/49859875
favorite count: 0

http://stackoverflow.com/a/49793781
upvote count: 30
type: Answer
score: 30
has comment: http://stackoverflow.com/comment/86621244
accepted answer of: http://stackoverflow.com/q/49785904
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86639097
has body: Assuming you are doing binary classification, it's quite easy: threshold = 0.4 predicted_proba = random_forest.predict_proba(X_test) predicted = (predicted_proba [:,1] &gt;= threshold).astype('int') accuracy = accuracy_score(y_test, predicted)
answers question: http://stackoverflow.com/q/49785904

http://stackoverflow.com/comment/86695488
has text: @Ry they are literally objects but they behave differently because there is no way to recreate any of them in pure python
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49839406
type: Comment

http://stackoverflow.com/a/79407906
score: 0
has body: If you are training a machine learning model in Pytorch, and have a list that's in tensor and convert to Numpy array: test_loss_values = [] # list in tensor print(test_loss_values) [tensor(0.4470, grad_fn=&lt;MeanBackward0&gt;), tensor(0.3318, grad_fn=&lt;MeanBackward0&gt;), tensor(0.2166, grad_fn=&lt;MeanBackward0&gt;), tensor(0.1014, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0447, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0390, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0355, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0320, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0286, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0252, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0217, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0183, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0149, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0114, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0080, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0046, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0040, grad_fn=&lt;MeanBackward0&gt;), tensor(0.0040, grad_fn=&lt;MeanBackward0&gt;)] test_loss_values = np.array(torch.tensor(test_loss_values).numpy())
type: Answer
answers question: http://stackoverflow.com/q/49768306

http://stackoverflow.com/comment/102093471
score: 12
type: AnswerComment
comment on: http://stackoverflow.com/a/49833102
type: Comment
has text: Yes, it's possible via **classifier__base_estimator__loss: ['hinge','modified_huber']** for example, where *classifier* is name of your calibration step in the pipeline, and *loss* is name of your base estimator parameter which you want to grid search.

http://stackoverflow.com/a/49804213
has body: For a self-contained example, from tkinter import * def go(line): print(line) root = Tk() menu=Menu(root) subMenu=Menu(menu) root.config(menu=menu) menu.add_cascade(label="Search History", menu=subMenu) commands = [] f=open('search_menu.txt','r+') # text file with one search entry per line for line in f: commands.append(subMenu.add_command(label=line[:-1], command=lambda x=line[:-1]:go(x))) # [:-1] is getting rid of \n root.mainloop()
answers question: http://stackoverflow.com/q/49803705
type: Answer
score: 0

http://stackoverflow.com/a/49784780
type: Answer
score: 2
has body: Squish not only views the QTableView GUI surface but will also access the underlying QAbstractItemModel. The data you see in your checks should therefore be live already. But Qt GUIs are indeed full of asynchronous processing through timers, sometimes threads and signals. If you want to be notified on changes that are accompanied by a signal there's the installSignalHandler() function. If you want to wait for a particular state of to appear there's the waitFor() function. In the case of the table you may want to use waitFor("mytable.model().rowCount() == 30") for example.
answers question: http://stackoverflow.com/q/49782429
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49805350
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: user-interface
downvote count: 0
tagged with: x11
upvote count: 1
type: Question
tagged with: docker
has title: Can't display tkinter gui from within docker
has comment: http://stackoverflow.com/comment/86644110
has body: No matter what I try, I'm getting the error: _tkinter.TclError: couldn't connect to display "*whatever I set as DISPLAY*" while trying to run GUI within docker. I tried adding -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY flags to the docker run command, but it didn't help at all. The setup I'm trying to run currently is: Computer1 with Ubuntu 17.10 is running a docker container (Ubuntu as well), I want to run the GUI on Computer1 display - :1. However, the end goal would be to have Computer1 run without any display connected and have the docker use the display of Computer2 (Ubuntu as well) that connects to Computer1 via ssh.
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86626083
favorite count: 0

http://stackoverflow.com/q/49858013
type: Question
has comment: http://stackoverflow.com/comment/86730766
has comment: http://stackoverflow.com/comment/86731793
has title: Execute scp using Popen without having to enter password
has comment: http://stackoverflow.com/comment/86731729
upvote count: 2
downvote count: 0
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/43526330
has comment: http://stackoverflow.com/comment/86731916
has comment: http://stackoverflow.com/comment/86731236
has comment: http://stackoverflow.com/comment/86731678
tagged with: scp
has comment: http://stackoverflow.com/comment/86731238
tagged with: passwords
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86730848
has body: I have the following script test.py #!/usr/bin/env python2 from subprocess import Popen, PIPE, STDOUT proc = Popen(['scp', 'test_file', 'user@192.168.120.172:/home/user/data'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) out, err = proc.communicate(input='userpass\n') print('stdout: ' + out) print('stderr: ' + str(err)) which is meant to copy test_file in a remote directory /home/user/data located at 10.0.0.2 using login for a given user user. In order to do that I must use scp. No key authentification is allowed (don't ask why, it's just how things are and I cannot change them). Even though I am piping userpass to the process I still get a prompt inside the terminal to enter password. I want to just run test.py on the local machine and then the remote gets the file without any user interaction. I though that I'm not using communicate() correctly so I manually called proc.stdin.write('userpass\n') proc.stdin.flush() out, err = proc.communicate() but nothing changed and I still got that password prompt.
accepted answer: http://stackoverflow.com/a/49859201
tagged with: popen
tagged with: pipe
has answer: http://stackoverflow.com/a/49859201
has comment: http://stackoverflow.com/comment/86740772
has comment: http://stackoverflow.com/comment/86741567
favorite count: 0

http://stackoverflow.com/q/49766806
downvote count: 0
upvote count: 1
tagged with: scipy
tagged with: signal-processing
has comment: http://stackoverflow.com/comment/86576736
favorite count: 0
type: Question
has title: Understand Scipy's Savitzky- Golay filter implementation
type: UnansweredQuestion
has body: Scipy's cookbook documentation gives the following code def savitzky_golay(y, window_size, order, deriv=0, rate=1): r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter. The Savitzky-Golay filter removes high frequency noise from data. It has the advantage of preserving the original shape and features of the signal better than other types of filtering approaches, such as moving averages techniques. Parameters ---------- y : array_like, shape (N,) the values of the time history of the signal. window_size : int the length of the window. Must be an odd integer number. order : int the order of the polynomial used in the filtering. Must be less then `window_size` - 1. deriv: int the order of the derivative to compute (default = 0 means only smoothing) Returns ------- ys : ndarray, shape (N) the smoothed signal (or it's n-th derivative). Notes ----- The Savitzky-Golay is a type of low-pass filter, particularly suited for smoothing noisy data. The main idea behind this approach is to make for each point a least-square fit with a polynomial of high order over a odd-sized window centered at the point. Examples -------- t = np.linspace(-4, 4, 500) y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape) ysg = savitzky_golay(y, window_size=31, order=4) import matplotlib.pyplot as plt plt.plot(t, y, label='Noisy signal') plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal') plt.plot(t, ysg, 'r', label='Filtered signal') plt.legend() plt.show() References ---------- .. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8), pp 1627-1639. .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery Cambridge University Press ISBN-13: 9780521880688 """ import numpy as np from math import factorial try: window_size = np.abs(np.int(window_size)) order = np.abs(np.int(order)) except ValueError,…
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86551142
has comment: http://stackoverflow.com/comment/86550478
has comment: http://stackoverflow.com/comment/86550056
linked to: http://stackoverflow.com/q/49322932
answer count: 0
has comment: http://stackoverflow.com/comment/86552115

http://stackoverflow.com/comment/86583416
has text: yeah I was on rush, as tag I read only python and I wrote without think seeing that I use to use more python 2 than 3... but it's a very easy class, not so much to understand, anyway I'll keep on mind your advice and I'll try to answer better next time, even if I want just help the community seeing that some time I ask question too
comment on: http://stackoverflow.com/a/49780259
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86619263
type: Comment
has text: Good suggestion @piRSquared, I didnt think of that one.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49802136

http://stackoverflow.com/q/49829320
has comment: http://stackoverflow.com/comment/86685835
type: Question
tagged with: python-asyncio
tagged with: python
accepted answer: http://stackoverflow.com/a/49937680
tagged with: discord
has body: I am trying to and Song-Objects to my Queue-Object, to get the actual songs I loop over a Playlist-Object from the libary Pafy. playlist = pafy.get_playlist("playlist url here") counter = 0 for s in playlist["items"]: counter += 1 s = s["pafy"] song = Song.Song(s.watchv_url, msg.author.name, s.title, s.description, s.author, s.published, s.duration, s.likes, s.dislikes, s.viewcount, s.thumb) if queue.add_song(song=song): print("Song " + str(counter) + " finished") else: print("Song " + str(counter) + " not added") class Song: def __init__(self, url, requested_by, title, description, uploader, upload_date, duration, likes, dislikes, views, thumbnail): self.url = url self.requested_by = requested_by self.title = title self.description = description self.uploader = uploader self.upload_date = upload_date self.duration = duration self.likes = likes self.dislikes = dislikes self.views = views self.thumbnail = thumbnail class PlayerQueue: list_of_songs = [] length = 0 current_song = [] replaying = False random = False def add_song(self, song): try: self.length += 1 self.list_of_songs.append(song) return True except Exception: return False def remove_song(self, song): if song in self.list_of_songs: self.length -= 1 self.list_of_songs.remove(song) return True else: return False def replay(self): self.replaying = True def randomize(self): self.random = True def clear(self): self.list_of_songs = [] self.length = 0 self.replaying = False self.random = False Should I make the add_song-Method async too? it takes approximately 1-2 sec for looping over this code once. This leads me into a problem with asyncio, because it will throw an TimeoutError. This error occurs after 30 seconds and for 70 Songs the loop takes more than one minute. Is this loop so slow, because it's run in a async def function? Can I even make it faster? Here is the error: ERROR:asyncio:Task exception was never retrieved future: &lt;Task finished coro=&lt;VoiceClient.poll_voice_ws() done, defined at C:\Users\u…
has comment: http://stackoverflow.com/comment/86674593
has title: Python slow for-loop in async func
has answer: http://stackoverflow.com/a/49937680
has comment: http://stackoverflow.com/comment/86677840
tagged with: pafy
has comment: http://stackoverflow.com/comment/86685273
tagged with: for-loop
has comment: http://stackoverflow.com/comment/86692558
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86676108
score: 0
has comment: http://stackoverflow.com/comment/86678147
has comment: http://stackoverflow.com/comment/86678381
has comment: http://stackoverflow.com/comment/86702179
answer count: 1
has comment: http://stackoverflow.com/comment/86674293

http://stackoverflow.com/a/49902794
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86822652
has comment: http://stackoverflow.com/comment/86823024
has body: Why oh why do people insist on making their lives more difficult by extracting arrays from dataframes? sklearn plays well with pandas!! Once you solve the error that @ely has shown, another error is because you are writing: imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = '0') when I think you mean to write: imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0) In the documentation, it says: axis : integer, optional (default=0) The axis along which to impute. If axis=0, then impute along columns. If axis=1, then impute along rows.
type: Answer
answers question: http://stackoverflow.com/q/49899973

http://stackoverflow.com/comment/86817352
comment on: http://stackoverflow.com/q/49900798
type: Comment
has text: @sascha: Are you saying that (2) or (3) is more efficient than using `tfrecord`s?
score: 0
type: QuestionComment

http://stackoverflow.com/q/49904313
tagged with: jupyter
type: Question
has answer: http://stackoverflow.com/a/49904494
type: UnansweredQuestion
tagged with: python
score: 0
has body: I have scheduled a Jupyter notebook to run periodically using jupyter nbconvert utility. It create a single html file that contains embedded images. I would like to send an email with the html file's content in the mail body (rather than as an attachment). How do I do that? I'm using Linux. I don't mind using any command line utilities or even a Python script.
tagged with: jupyter-notebook
answer count: 1
has title: send html email with embedded images

http://stackoverflow.com/comment/86557756
comment on: http://stackoverflow.com/q/49764402
type: Comment
has text: I can post the answer if you wish to accept. Note that PyPi regex module is used there. Not the regular `re`.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86550799
type: Comment
has text: What use case are you trying to cater?
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49767738

http://stackoverflow.com/q/49900714
has comment: http://stackoverflow.com/comment/86816985
upvote count: 0
downvote count: 4
duplicate of: http://stackoverflow.com/q/509211
linked to: http://stackoverflow.com/q/44385999
has comment: http://stackoverflow.com/comment/86817033
score: -4
has comment: http://stackoverflow.com/comment/86817105
answer count: 1
has body: OK I understand the basics, but can someone explain code copied from Greg's answer here: a[1::-1] # the first two items, reversed a[:-3:-1] # the last two items a[-3::-1] # everything except the last two items, reversed To me the first one reads: slice from 2nd position to end, then reverse it. The second one is slice from beginning to the -2 position then reverse it. The third one is slice from -3rd position to end then reverse it. Obviously I am wrong since they work as suggested, but can you please tell me why?
has comment: http://stackoverflow.com/comment/86829111
tagged with: python
linked to: http://stackoverflow.com/q/509211
favorite count: 0
type: AnsweredQuestion
has title: Python slicing explained
has comment: http://stackoverflow.com/comment/86816981
has comment: http://stackoverflow.com/comment/86816977
has answer: http://stackoverflow.com/a/49906839
accepted answer: http://stackoverflow.com/a/49906839
has comment: http://stackoverflow.com/comment/86816923
has comment: http://stackoverflow.com/comment/86828198
type: Question
has comment: http://stackoverflow.com/comment/86816982
has comment: http://stackoverflow.com/comment/86828462

http://stackoverflow.com/q/49907823
has comment: http://stackoverflow.com/comment/86831516
upvote count: 0
accepted answer: http://stackoverflow.com/a/49908910
tagged with: web-scraping
has answer: http://stackoverflow.com/a/49908910
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49908436
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/86831819
has title: Python & BeautifulSoup beginner: how do I extract a tag out of this code
tagged with: python
score: -1
has body: I'm looking for a bit of guidance here. I'm completely new to Python, BS, Selenium, etc so please go easy on me. My ISP doesn't provide alerts for my internet usage and I wanted to create my own monitoring for this. I managed to scrape the page I need using selenium and BeautifulSoup but now I'm a bit stuck. I have a container that has the following HTML code in it: [&lt;div class="usage_circle"&gt; &lt;center&gt; &lt;div data-perc="69" data-transitiongoal="0.69" data-usage="150.29"&gt; &lt;/div&gt; &lt;/center&gt;&lt;/div&gt;] I'd like to extract the data-usage value of 150.29. I've tried using the findAll function (previously used to get the above HTML), but it doesn't work in this case. Could anyone guide me as to what I need to do to get this number into a variable? Thank you in advance.
possible better answer: http://stackoverflow.com/a/49908436
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/49859607
has answer: http://stackoverflow.com/a/49902764
score: 0
linked to: http://stackoverflow.com/q/89228
has comment: http://stackoverflow.com/comment/86735926
has title: Running pip install from Django Management commands
has comment: http://stackoverflow.com/comment/86736157
tagged with: django-management-command
has body: Let me know if this question is obvious enough and there are also duplicates of this question which I am failed for search beforehand. I am trying to run pip install requirements/dev.txt from Django management command. I have a logic which is, do not try to run the script pip ... if the cache is unchanged. I am trying to figure out how to run this command from the DMC? Usage: python manage.py install_prepreqs Cache is unchanged, skipping.... install_prepreqs.py # I want to run `pip install requirements/dev.txt` with some additional logic.
type: Question
tagged with: django
type: UnansweredQuestion
tagged with: python
answer count: 1

http://stackoverflow.com/comment/86536928
comment on: http://stackoverflow.com/q/49760656
type: QuestionComment
has text: Ah, you need to combine the relative path to your source with the relative path _of_ the source, and _then_ call `resolve`.
score: 0
type: Comment

http://stackoverflow.com/a/49887692
score: 9
upvote count: 9
type: Answer
has comment: http://stackoverflow.com/comment/92259201
answers question: http://stackoverflow.com/q/49887524
has body: sum([a, b, c], d) produces d + a + b + c. In your example, a, b, c, and d are [1, 2], [3, 4], [5, 6], and []. sum([[1, 2], [3, 4], [5, 6]], []) produces [] + [1, 2] + [3, 4] + [5, 6], which is [1, 2, 3, 4, 5, 6] because + is concatenation for lists. This is absurdly inefficient, because every + operation involved requires copying all the data from each of its arguments: In [7]: x = [[i] for i in range(30000)] In [8]: %timeit sum(x, []) 1 loop, best of 3: 2.06 s per loop In [9]: %timeit [elem for sublist in x for elem in sublist] 1000 loops, best of 3: 1.91 ms per loop sum(x, []) takes quadratic time, whereas a more efficient implementation takes linear time. Never do sum(x, []).
downvote count: 0

membership
tag name: membership
tags question: http://stackoverflow.com/q/49909061
type: Tag

http://stackoverflow.com/comment/86737129
type: AnswerComment
comment on: http://stackoverflow.com/a/49859875
has text: What's the length of your dataframe? That error indicates that the problem is coming from the `df["Distance"] = ` part rather than the `y - model.predict(x)` part. You could also do `df["Distance"] = df['Exam Results'].values - model.predict(df['Hours Studied'].values[:,np.newaxis])`.
score: 1
type: Comment

edges
tags question: http://stackoverflow.com/q/49860638
tag name: edges
type: Tag

http://stackoverflow.com/comment/86738402
comment on: http://stackoverflow.com/q/49860638
has text: See how it should be done in [this answer](https://stackoverflow.com/a/40834276/6499160).
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/102444289
type: Comment
score: 4
comment on: http://stackoverflow.com/a/51462434
type: AnswerComment
has text: in the latest version `pip3` , the `main()` is moved to `pip._internal`. The import statement should be changed to `from pip._internal import main`

http://stackoverflow.com/comment/86771664
has text: In the link I pointed to, a 32bits version of Python is installed on a 64 bits windows 10. The issue was solved by changing python to the 32 bits version. Which anaconda did you install? 32 or 64 bits? Is your windows platform 64 bits?
comment on: http://stackoverflow.com/q/49859885
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86788926
score: 0
type: Comment
has text: Just to clarify, I should reset my workspace to stop the tpot optimization and read current results? I can reset my variables, but wouldn't that not stop the code execution?
type: QuestionComment
comment on: http://stackoverflow.com/q/49885598

http://stackoverflow.com/comment/86821739
type: AnswerComment
comment on: http://stackoverflow.com/a/49902276
score: 0
has text: Since all you've done is rearrange the code, I don't see how this does anything to solve the problem. If the OP's list comprehension throws a TypeError, so does yours. All you've done is change the output - which wasn't even incorrect to begin with.
type: Comment

http://stackoverflow.com/a/49896631
has comment: http://stackoverflow.com/comment/86808747
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49896450
has comment: http://stackoverflow.com/comment/86808662
type: Answer
accepted answer of: http://stackoverflow.com/q/49896450
has body: Use the desired date format on the index: grouped.plot(x=grouped.index.strftime('%Y-%m-%d'), kind='bar', stacked=True)
score: 2
upvote count: 2

http://stackoverflow.com/q/49770856
has comment: http://stackoverflow.com/comment/86558642
upvote count: 2
accepted answer: http://stackoverflow.com/a/49771948
tagged with: timezone
has answer: http://stackoverflow.com/a/49771948
downvote count: 0
has body: A reproducible example: import pandas as pd now = pd.Timestamp('2018-04-09 09:10') start_of_today = pd.datetime(now.year, now.month, now.day, 0) print(pd.to_datetime(start_of_today.timestamp(), unit='s')) The last line will return 2018-04-08 22:00:00 instead of 2018-04-09 00:00, why does this happen?
possible better answer: http://stackoverflow.com/a/49771977
has title: Inconsistent pandas datetime conversion
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49771977
tagged with: pandas
tagged with: datetime
tagged with: python
favorite count: 0
type: Question
score: 2
answer count: 2

ghc
type: Tag
tags question: http://stackoverflow.com/q/49813434
tag name: ghc

http://stackoverflow.com/q/49770379
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/86555665
favorite count: 0
type: Question
tagged with: terminal
has title: How to print out to terminal a list of option to choose from?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49770549
score: -3
has comment: http://stackoverflow.com/comment/86555607
upvote count: 0
has body: I'm doing an application for fun in python. One of the things i want to do, is print out to terminal a list of option to choose from by navigating up and down using arrow keys (If it's possible). for example: Hey, please choose one of the following options: 1-XXXXX 2-YYYYY 3-ZZZZZ and the user chooses the one highlighted. and how do i bind what the customer chose to a variable? Thanks!
linked to: http://stackoverflow.com/q/70797

http://stackoverflow.com/q/49847677
linked to: http://stackoverflow.com/q/21583758
has body: So, I'm trying to complete an exercise in URI Online Judge but I'm having trouble with checking if a float is an whole number. Here's my code: I = 0.0 J = 1.0 while I &lt;= 2: for y in range(3): if I.is_integer(): print("I=%d J=%d" % (I, J)) else: print("I=%.1f J=%.1f" %(I, J)) J += 1.0 J -= 2.8 I += 0.2 Well, the output works fine until the last loop. In the first two loops where the values are whole numbers, it prints as it's supposed to: with floating point, because it's a whole number. But in the last loop, I get a whole number with a floating point, any ideas to fix this? Here's the output: I=0 J=1 #working fine here I=0 J=2 I=0 J=3 I=0.2 J=1.2 I=0.2 J=2.2 I=0.2 J=3.2 I=0.4 J=1.4 I=0.4 J=2.4 I=0.4 J=3.4 I=0.6 J=1.6 I=0.6 J=2.6 I=0.6 J=3.6 I=0.8 J=1.8 I=0.8 J=2.8 I=0.8 J=3.8 I=1 J=2 # also works fine here I=1 J=3 I=1 J=4 I=1.2 J=2.2 I=1.2 J=3.2 I=1.2 J=4.2 I=1.4 J=2.4 I=1.4 J=3.4 I=1.4 J=4.4 I=1.6 J=2.6 I=1.6 J=3.6 I=1.6 J=4.6 I=1.8 J=2.8 I=1.8 J=3.8 I=1.8 J=4.8 I=2.0 J=3.0 # got messed up here I=2.0 J=4.0 I=2.0 J=5.0 [EDIT] - Working as expected now I = 0.0 J = 1.0 while I &lt;= 2: for y in range(3): if I.is_integer() or I &gt; 1.9: if 1.9 &lt; I &lt; 2.1: # Made some workarounds here I += 0.1 print("I=%d J=%d" % (I, J)) else: print("I=%.1f J=%.1f" %(I, J)) J += 1.0 J -= 2.8 I += 0.2
score: 3
has comment: http://stackoverflow.com/comment/86710336
downvote count: 1
has comment: http://stackoverflow.com/comment/87161106
favorite count: 0
duplicate of: http://stackoverflow.com/q/21583758
type: Question
upvote count: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86710540
has comment: http://stackoverflow.com/comment/86710322
has title: float check for is_integer value not working as expected?
has comment: http://stackoverflow.com/comment/86710315
has comment: http://stackoverflow.com/comment/86749008
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/86710333
has comment: http://stackoverflow.com/comment/86710359
answer count: 0

http://stackoverflow.com/comment/99050714
type: Comment
comment on: http://stackoverflow.com/a/49825412
score: 0
type: AnswerComment
has text: @deets, the script is working great, but how do i crop the text boxes using python and create new images from the boxes?

http://stackoverflow.com/comment/86772448
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49877928
has text: Not sure why this question is pickup up all the downvotes and a close flag. It's pretty clear if you know gremlinpython, though i don't know why you'd get that specific error for that particular traversal. I don't see anything invalid about it. Did you try to issue the same script from the Gremlin Console to see if that works?

http://stackoverflow.com/q/49904996
downvote count: 0
tagged with: python
score: 2
has title: Converting a string of list to list in pandas
tagged with: pandas
has comment: http://stackoverflow.com/comment/86825873
has body: I have a pandas column whose values are list of words. But the whole list is datatype string. For example one cell value of this column is a= ['expert executive', 'internal committee period', 'report name', 'entry'] type(a) Out[23]: str But this is stored as string. Now issue is I want to access this value as a list as I want to use list operation of extending this list with another list. However since currently it is typed as string, list operations doesn't work on this. Any idea how can I access this value as list instead of string. I tried doing list(a), it will break it all down to individual character since whole a is a string.
has answer: http://stackoverflow.com/a/49905028
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49905246
answer count: 2
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/49817816
score: 0
has comment: http://stackoverflow.com/comment/86650371
has title: Django: int() argument must be a string, a bytes-like object or a number, not 'Games'
answer count: 1
has body: I have a model named Games with some fields, I'm trying to query 2 latest games &amp; 2 random games in a single variable from the database. Here's what I tried, data1 = Games.objects.order_by('-id')[:2] data2 = sorted(Games.objects.exclude(id__in=data1), key=lambda x: random.random())[:2] But now I'm stuck, I couldn't combine the games present in data1 &amp; data2 variables into a single variable data3. Here's what I tried, data3 = Games.objects.filter(Q(id__in=data1) | Q(id__in=data2)) But it's raising an error, int() argument must be a string, a bytes-like object or a number, not 'Games'. How can we do that? Thank You :)
type: Question
has comment: http://stackoverflow.com/comment/86650205
has comment: http://stackoverflow.com/comment/86650276
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49817922
accepted answer: http://stackoverflow.com/a/49817922
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86650466

http://stackoverflow.com/a/49786780
has body: Yes, the only difference is that the name Y is bound to X.Y. Either way, binding Y to something else isn't going to affect anything in X. If it makes it easier, consider this parallel: &gt;&gt;&gt; y = 2 &gt;&gt;&gt; x = y &gt;&gt;&gt; x = 3 Do you expect this to change y to 3? Of course not. But that's exactly the same thing you're doing. If it's still not clear, let's break down what those imports actually do. When you import sys, it's equivalent to: sys.modules['sys'] = __import__('sys') sys = sys.modules['sys'] sys.stdout = open(text, "w") But with the from sys import stdout: sys.modules['sys'] = __import__('sys') stdout = sys.modules['sys'].stdout stdout = open(text, "w")
upvote count: 4
answers question: http://stackoverflow.com/q/49786743
has comment: http://stackoverflow.com/comment/86589116
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49786743
has comment: http://stackoverflow.com/comment/86589104
has comment: http://stackoverflow.com/comment/86589078
score: 4
has comment: http://stackoverflow.com/comment/86588983
type: Answer

http://stackoverflow.com/comment/87427742
type: Comment
comment on: http://stackoverflow.com/a/49812722
score: 0
type: AnswerComment
has text: @spectre What Python version are you using?

http://stackoverflow.com/q/49828755
score: 1
tagged with: classpath
favorite count: 0
tagged with: pycharm
type: Question
tagged with: intellij-idea
has title: Add local python module to the classpath in IntelliJ
has comment: http://stackoverflow.com/comment/86778491
tagged with: django
upvote count: 1
tagged with: python
has body: I am trying to run/debug my python project from IntelliJ Ultimate 2018.1. I have defined a python SDK, a Django local server (as the project uses Django as a template language), the PYTHONPATH is properly defined, etc. If I execute python manage.py runserver from my MacOS terminal, the server starts normally. When I am trying to run my IntelliJ configuration, it fails, with message: /usr/bin/python2.7 -d /Users/my_user/dev/github/my_project/manage.py runserver 8000 Traceback (most recent call last): File "/Users/my_user/dev/github/my_project/manage.py", line 19, in &lt;module&gt; paths = importlib.import_module('settings.' + server + '.paths') File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/my_user/dev/github/my_project/settings/__init__.py", line 11, in &lt;module&gt; paths = importlib.import_module('my_project.settings.' + server + '.paths') File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named my_project.settings.local.paths The settings.local folder does contains the __init__.py file, and also settings folder and the root folder of my project. Doing a few hours of research over the internet I have realised that the main problem is to include local modules on the classpath, so they are available for server startup. For PyCharm, this is clearly explained here, and I was able to run the server from PyCharm. However, when trying to do the same thing in IntelliJ, this never works. Some people write about it here for example, but that didn't worked out for me. I have tried using a system interpreter and also a virtual environment, created with PyCharm, with no luck. I am using python 2.7, Django 1.11 and MacOS High Sierra. Is this even possible with IntelliJ? I wonder why would people buy PyCharm if the same things can be accomplished (and so m…
has comment: http://stackoverflow.com/comment/86809313
linked to: http://stackoverflow.com/q/17198319
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49922880
linked to: http://stackoverflow.com/q/13994846
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49922880

http://stackoverflow.com/q/49857964
has answer: http://stackoverflow.com/a/49858007
accepted answer: http://stackoverflow.com/a/49858059
tagged with: python-3.x
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/49858059
has title: How to add parent object in JSON with python
possible better answer: http://stackoverflow.com/a/49858007
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has body: I have this json which has 3 parents and several child elements under each parent. I want to add one more common parent for all 3 current parents. Currently I have: { "Parent1": { "Key1": "Value", "Key2": "Value", "Key3": "Value" }, "Parent2": { "Key1": "Value", "Key2": "Value", "Key3": "Value" }, "Parent3": { "Key1": "Value", "Key2": "Value", "Key3": "Value" } } What I want to have: { "Main parent": { "Parent1": { "Key1": "Value", "Key2": "Value", "Key3": "Value" }, "Parent2": { "Key1": "Value", "Key2": "Value", "Key3": "Value" }, "Parent3": { "Key1": "Value", "Key2": "Value", "Key3": "Value" } } } Below python3 code doesn't do the job: with open ("myfile.json", 'r') as f: myjson = json.load(f) myjson["Main Parent"] = myjson I would appreciate if you spread some light on this situation.
tagged with: python
tagged with: dictionary
upvote count: 6

http://stackoverflow.com/comment/86777221
comment on: http://stackoverflow.com/q/49879993
has text: If you're running Linux, and staying on the same WiFi network is acceptable, KDE Connect has a very nice command line client you can use to ping your phone. `kdeconnect-cli -d <DEVICE_ID> --ping-msg 'Script complete!'`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86658335
has text: To be honest, I was under the impression that a `GET` request was the right protocol for simple select queries. Thought `POST` was more suited for adding data to the DB. @Jean Rostan made a similar comment in the answer below. I'm going to have to think about revising
comment on: http://stackoverflow.com/q/49803518
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86850358
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49916232
has text: From the traceback it seems `is_group` is actually **not** a function, but a simple `bool` attribute. Try replacing `item.is_group()` with `item.is_group` and see if things improve
score: 1

http://stackoverflow.com/q/49791848
has answer: http://stackoverflow.com/a/49792122
score: 8
upvote count: 8
possible better answer: http://stackoverflow.com/a/76030490
has answer: http://stackoverflow.com/a/76030490
tagged with: python
has title: Matplotlib remove all patches from figure
type: AnsweredQuestion
answer count: 2
tagged with: matplotlib
has body: I am trying to plot various rectangles on top of an image stream. Before displaying the next image, all former rectangles should be removed again. From this question I found a first possible solution. Below is a simplified example of what I am doing at the moment. fig, ax = plt.subplots(1) im = ax.imshow(np.zeros((800, 800, 3))) for i in range(100): img = plt.imread('my_image_%03d.png' % i) im.set_data(img) rect_lst = getListOfRandomRects(n='random', dim=img.shape[0:2]) patch_lst = [patches.Rectangle((r[0], r[1]), r[2], r[3], linewidth=1, facecolor='none') for r in rect_lst] [ax.add_patch(p) for p in patch_lst] plt.pause(0.1) plt.draw() [p.remove() for p in patch_lst] What I don't like about this is that I have to keep track of of the patch_lst in order to remove them again. I would prefer to simply remove all patches and get something like this: for i in range(100): [...] rect_lst = getListOfRandomRects(n='random', dim=img.shape[0:2]) [ax.add_patch(patches.Rectangle((r[0], r[1]), r[2], r[3], linewidth=1, facecolor='none')) for r in rect_lst] plt.pause(0.1) plt.draw() ax.clear_all_patches() # &lt;-- this is what I am looking for I did try ax.clear(), however this also removes the underlying image. Any suggestions?
downvote count: 0
accepted answer: http://stackoverflow.com/a/49792122
favorite count: 0
linked to: http://stackoverflow.com/q/21687571
type: Question

http://stackoverflow.com/comment/86834120
type: Comment
type: AnswerComment
has text: The first box is useless without the second box. It doesn't sound like you understand at all the constructs that I'm using. Please go read about them, that is essential to solving your problem and an important part of learning to code.
comment on: http://stackoverflow.com/a/49908832
score: 0

http://stackoverflow.com/a/50066679
downvote count: 0
has body: Following @Anupam's answer on OS X resulted in the following error for me, regardless of permissions I ran it with: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: ... What eventually worked was to download a newer pip package (9.0.3) from PyPI directly from my browser - https://pypi.org/simple/pip/, extract the contents, and then pip install the package locally: pip install ./pip-9.0.3/ This fixed my [SSL: TLSV1_ALERT_PROTOCOL_VERSION] errors.
upvote count: 9
score: 9
type: Answer
answers question: http://stackoverflow.com/q/49768770

http://stackoverflow.com/comment/86631831
type: AnswerComment
has text: Yes, it works. However, how it works in a Table where text here is just a column?
comment on: http://stackoverflow.com/a/49808418
score: 0
type: Comment

http://stackoverflow.com/q/49775505
type: UnansweredQuestion
tagged with: python
has body: I've installed Python module "six" and it prints the same error: I've installed and i get the same error How can I fix this?
score: 0
answer count: 1
upvote count: 1
downvote count: 1
has title: Missing Xcode dependency: Python module "six"
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49869567

http://stackoverflow.com/q/49805906
answer count: 1
has body: When I do `M-x run-python' it opens an interpreter but it is python 2.7. I would like the command `M-x run-python' to open it as is in my anaconda3 installation. I want to do this, as none of my packages are importable currently. So I followed advice from "this answer" and added the following to my /.emacs.d/init.el file. (setq python-python-command "/home/eghx/anaconda3/bin/python") It doesn't work. I only end up opening python 2.7 Furthermore, anaconda's python works with spyder (IDE), works in my terminal and everywhere else except by default with emacs. As you can tell I am a noob and would greatly appreciate any help. Thanks Specs Ubuntu 16 recent install, Emacs 27.0.5, Anaconda 3
tagged with: emacs
has comment: http://stackoverflow.com/comment/86628556
has comment: http://stackoverflow.com/comment/86628574
has comment: http://stackoverflow.com/comment/86660175
type: AnsweredQuestion
score: 0
tagged with: anaconda
has comment: http://stackoverflow.com/comment/86628940
accepted answer: http://stackoverflow.com/a/49806701
tagged with: python
has answer: http://stackoverflow.com/a/49806701
type: Question
linked to: http://stackoverflow.com/q/2515754
has title: running a different python version in emacs run-python

http://stackoverflow.com/comment/86686339
comment on: http://stackoverflow.com/a/49833737
type: Comment
score: 0
type: AnswerComment
has text: It worked, the function is called "load_yahoo_quote". But the data downloaded are a series of lists, can you tell me how to transfer it into dataframe? Thanks a lot!

http://stackoverflow.com/comment/86607290
comment on: http://stackoverflow.com/a/49796474
type: Comment
type: AnswerComment
score: 1
has text: Ok. I was not sure if there was a simpler method to extract 'n' lists. Thanks

http://stackoverflow.com/a/49808649
has comment: http://stackoverflow.com/comment/86632795
type: AcceptedAnswer
has body: What you can do is use .text_content() which aggregates a "text" of an HTML element: Returns the text content of the element, including the text content of its children, with no markup. texts = [col.text_content() for col in cols]
has comment: http://stackoverflow.com/comment/86632470
has comment: http://stackoverflow.com/comment/86632676
has comment: http://stackoverflow.com/comment/86632535
accepted answer of: http://stackoverflow.com/q/49808607
has comment: http://stackoverflow.com/comment/86632597
type: Answer
answers question: http://stackoverflow.com/q/49808607
has comment: http://stackoverflow.com/comment/86632490
has comment: http://stackoverflow.com/comment/86632548
score: 0

http://stackoverflow.com/a/49882758
has comment: http://stackoverflow.com/comment/86836094
has comment: http://stackoverflow.com/comment/86818215
has comment: http://stackoverflow.com/comment/86880576
has comment: http://stackoverflow.com/comment/86847222
has body: One way to do this is to define: def f(x,y,a): return np.sin(x + y) / np.sqrt(x**2 + y**2) - a where a can take the limits of your interval and then calculate the roots x0 and y0 of this function using scipy.optimize. These roots correspond to the x and y values of your function between which the function returns the desired values.
has comment: http://stackoverflow.com/comment/86801764
type: Answer
has comment: http://stackoverflow.com/comment/86819416
answers question: http://stackoverflow.com/q/49882469
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86815012
has comment: http://stackoverflow.com/comment/86791004

http://stackoverflow.com/q/49800952
tagged with: python
accepted answer: http://stackoverflow.com/a/49802033
tagged with: text
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49802033
score: 0
tagged with: flip
has body: I've just started to use PyGame and i'm trying to figure out how to flip text horizontally and / or vertically but, so far, no luck. Here's my code so far: import pygame, sys, datetime, os from pygame.locals import * os.environ['SDL_VIDEO_CENTERED'] = '1' now = datetime.datetime.now() dateoftime = (now.strftime("%d-%m-%Y")) pygame.init() screen = pygame.display.set_mode((768, 768), pygame.NOFRAME) clock = pygame.time.Clock() White=(255,255,255) Black=(0,0,0) basicfont = pygame.font.SysFont('pricedown', 100) text = basicfont.render((dateoftime), True, White, Black) textrect = text.get_rect() textrect.centerx = screen.get_rect().centerx textrect.centery = screen.get_rect().centery pygame.transform.flip(screen,True,False) screen.fill(Black) screen.blit(text, textrect) pygame.display.update() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() clock.tick(50) Another thing i wanted to do is centre the text but change the y value for it. For example, keep the x value as the centre (calculated from textrect) but change the y value to 200 or 600. Same for when i want to change the x value. Also, what parts do i need to change to show the current time, (H:M:S) that updates every second. I tried to change the amount in "clock.time(50)" but that doesn't cut it. If there are any errors in this in general, corrections will be well appreciated. Thank you.
answer count: 1
tagged with: pygame
type: Question
has title: Flip (or invert) text in Pygame

http://stackoverflow.com/q/49833108
has answer: http://stackoverflow.com/a/49833578
score: 1
upvote count: 1
answer count: 1
has title: Python attribute error after result is outputed
has body: My program reads a file line-by-line and uses reg-ex at every line. The program executes well for all lines, but throws the following at the end: Traceback (most recent call last): File "test.py", line 24, in &lt;module&gt; output = pattern.search(line).group() AttributeError: 'NoneType' object has no attribute 'group' My code is the following: import re pattern = re.compile(r'(?&lt;=\&gt;)(.*?)(?=\|)') # open input file input_file = open('input.fas', 'r') while True: line = input_file.readline() if line == '' or line is None: print('EOF') break else: output = pattern.search(line).group() print(output)
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86681472
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86682221
has comment: http://stackoverflow.com/comment/86682152
downvote count: 0

http://stackoverflow.com/comment/100749173
comment on: http://stackoverflow.com/a/57114773
has text: Could you perhaps clarify how it will help/+ remove any condescending comments?
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49857233
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49858052
has body: There's many questions on the topic but apparently none with my exact use-case. I'm running a long loop where each iteration takes a lot of time. I want to at the end of each loop plot (using matplotlib) the current progress. The basic setup is import matplotlib.pyplot as plt def plotStuff(data) plt.figure() plt.plot(data) plt.savefig('test.pdf') def main(): for iteration in range(1000): data = doStuff(oldData) if convergence(data, oldData): break plotStuff(data) oldData = data if __name__ == '__main__': main() However, the plotting routine takes a lot of time. My initial solution was to import threading and change the plotting part to plottingThread = threading.Thread(target=plotStuff, args=data) plottingThread.start() However, it appears that matplotlib is not thread save. My newest idea was then to import multiprocessing and def main(): pool = multiprocessing.Pool(processes=1) for iteration in range(1000): data = doStuff(oldData) if convergence(data, oldData): break res = pool.apply_async(plotStuff, args=(data,)) oldData = data However, it appears that this will only schedule the function call, and not actually execute it. Execution happens via pool.close(); pool.join() or res.get(). However, pool.join() and res.get() do block the main process until the pools are done. I believe my questoin is this: How can I asynchronously call plotStuff(data) without having to ever wait for the result? Additionally, I'd be happy if there's a way of controlling the jobs in the pool. Say, I only want to have at max 10 jobs in the pool, and the plotting is too slow -- would there be a way of deleting the oldest jobs such that we have a chance of catching up with the ``outer process''?
tagged with: multiprocessing
type: Question
has title: Asynchronous process that I do not wait for
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
tagged with: python-multiprocessing

http://stackoverflow.com/comment/86620522
has text: Sorry, mind reading machine is broken again. Can you post your code? :)
comment on: http://stackoverflow.com/q/49799080
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86696701
has text: Possible duplicate of [Popen.communicate() returns (None, None) even if script print results](https://stackoverflow.com/questions/27904943/popen-communicate-returns-none-none-even-if-script-print-results)
type: Comment
comment on: http://stackoverflow.com/q/49840572
type: QuestionComment
score: 2

http://stackoverflow.com/a/49877645
has comment: http://stackoverflow.com/comment/86779216
has comment: http://stackoverflow.com/comment/86778956
has comment: http://stackoverflow.com/comment/86772249
has comment: http://stackoverflow.com/comment/86776850
has comment: http://stackoverflow.com/comment/86776550
has body: The original code in the FCNN architecture example works with an input dimension of (416, 608). Whereas in your code, the input dimension is (192, 192) (ignoring the channel dimension). Now if you notice carefully, this particular layer x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool', data_format=IMAGE_ORDERING)(x) generates an output of dimension (6, 6) (you can verify in your model.summary()). The next convoltuion layer o = (Convolution2D(4096,(7,7) , activation='relu' , padding='same', data_format=IMAGE_ORDERING))(o) uses convolution filters of size (7, 7), but your input has already reduced to a size smaller than that (i.e. (6, 6)). Try fixing that first. Also if you look at the model.summary() output, you'll notice that it does not contain the layers defined after the block5_pool layer. There is a transposed convolution layer in it (which basically upsamples your input). You may want to take a look and try to resolve that as well. NOTE: In all my dimensions, I have ignored the channel dimension. EDIT Detailed Answer below First of all, this is my keras.json file. It uses Tensorflow backend, with image_ordering set at channel_last. { "floatx": "float32", "epsilon": 1e-07, "backend": "tensorflow", "image_data_format": "channels_last" } Next, I copy paste my exact model code. Please take special note of the inline comments in the code below. from keras.models import * from keras.layers import * IMAGE_ORDERING = 'channels_last' # In consistency with the json file def getFCN32(nb_classes = 20, input_height = 416, input_width = 608): img_input = Input(shape=(input_height,input_width, 3)) # Expected input will have channel in the last dimension #Block 1 x = Convolution2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1', data_format=IMAGE_ORDERING)(img_input) x = BatchNormalization()(x) x = Convolution2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2', data_format=IMAGE_ORDERING)(x) x = BatchNormalization()(x) x = MaxPoo…
answers question: http://stackoverflow.com/q/49844360
downvote count: 0
has comment: http://stackoverflow.com/comment/86777561
upvote count: 1
has comment: http://stackoverflow.com/comment/86772098
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86774525
has comment: http://stackoverflow.com/comment/86776337
has comment: http://stackoverflow.com/comment/86782520
has comment: http://stackoverflow.com/comment/86803752
has comment: http://stackoverflow.com/comment/86804259
has comment: http://stackoverflow.com/comment/86771880
has comment: http://stackoverflow.com/comment/86777690
has comment: http://stackoverflow.com/comment/86772332
score: 1
has comment: http://stackoverflow.com/comment/86804388
has comment: http://stackoverflow.com/comment/86771917
type: Answer
has comment: http://stackoverflow.com/comment/86804467
accepted answer of: http://stackoverflow.com/q/49844360
has comment: http://stackoverflow.com/comment/86780932
has comment: http://stackoverflow.com/comment/86776234
has comment: http://stackoverflow.com/comment/86777270

http://stackoverflow.com/q/49868352
type: UnansweredQuestion
tagged with: python
tagged with: excel
has title: Read json file and update existing excel using python pandas
score: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49870370
has body: excel_file name = exl.xlsx Excel data: name surname email a sname abc.com b sname2 efg.com json file name = input.json json data { "a": { "friend1":4444444444, "friend2":5555555555, "friend3":1111111111 }, "b": { "friend3":6565656565, "friend2":9999999999, "friend5":9999988888 } } import json import panda as pd json_data = json.load(open(input.json)) data = pd.read_json(json_data) excel_file = pd.read_excel(exl.xlsx, na_filter=False, header=0) I want to update excel file in such a way that you match the name from json to excel and add a new column in excel with name "listOfFriends" and for that matched name you update the column name surname email listOfFriends a sname abc.com friend1, friend2, friend3 b sname2 efg.com friend3, friend2, friend5
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/86693038
type: Comment
has text: Those are the row nos where the condition is true
type: AnswerComment
comment on: http://stackoverflow.com/a/49838036
score: 0

http://stackoverflow.com/q/49906329
has comment: http://stackoverflow.com/comment/86832142
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/86828885
has answer: http://stackoverflow.com/a/53011903
tagged with: python
has title: Good ArUco Marker Detection in DICT4X4 but not in DICT5x5
has body: I am trying to detect ArUco Markers to recognise some real moving objects, to write my Degree Thesis. Fisrt, I tried with some 4x4 ArUco Markers, i got good results, then i tried with an image that i got from my camera. This image contains 5x5 ArUco Markers, applying same code, except changing Dictionaries, 4x4 per 5x5, why is only detecting 4x4 markers ? Results: 4x4 Markers detected 1 5x5 Markers not detected 2 import cv2 import numpy as np from cv2 import aruco import camera_calibration path='/home/alejandrocruzado/Documents/Imaginni/aruco4.png' path_5 = '/home/alejandrocruzado/Documents/Imaginni/aruco5.jpg' path5x5 = '/home/alejandrocruzado/Documents/Imaginni/5x5.jpg' distCoeffs=[0.0189223469433419, -0.0206788674793396,0.003225513523750, 0.001510000668961] cameraMatrix=[[600.8293, 0, 330.2756],[0, 601.3519, 225.9791],[0, 0, 1.0000]] def MarkerDetection4x4(path): img = cv2.imread(path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) aruco_dict = cv2.aruco_Dictionary.get(aruco.DICT_4X4_1000) parameters = cv2.aruco_DetectorParameters.create() corners, ids, rejectedImgPoints = cv2.aruco.detectMarkers(gray, aruco_dict, parameters=parameters) cv2.aruco.drawDetectedMarkers(img,corners,ids,) cv2.imshow('Image', img) cv2.waitKey(0) cv2.destroyAllWindows() rvecs, tvecs, _objPoints = cv2.aruco.estimatePoseSingleMarkers(corners, 0.045, cameraMatrix, distCoeffs) cv2.aruco.drawAxis(img, cameraMatrix, distCoeff, rvecs, tvecs, 0.1) def MarkerDetection5x5(path): img = cv2.imread(path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) aruco_dict = cv2.aruco_Dictionary.get(aruco.DICT_5X5_250) parameters = cv2.aruco_DetectorParameters.create() corners, ids, rejectedImgPoints = cv2.aruco.detectMarkers(gray, aruco_dict, parameters=parameters) cv2.aruco.drawDetectedMarkers(img,corners,ids,) cv2.imshow('Image', img) cv2.waitKey(0) cv2.destroyAllWindows() rvecs, tvecs, _objPoints = cv2.aruco.estimatePoseSingleMarkers(corners, 0.045, cameraMatrix, distCoeffs) cv2.aruco.drawAxis(img, cameraMatrix…
tagged with: aruco

http://stackoverflow.com/q/49841474
has title: Django tasks, reminders, notifications
favorite count: 0
type: Question
upvote count: 4
tagged with: redis
has answer: http://stackoverflow.com/a/49841882
tagged with: django
has body: I have a fairly simple web app in Django (Apache, Ubuntu) for keeping some meetings documentation. Meetings have their appointment time stored in database (postgres) in datetime format. Now, I'd like to have a custom reminder module that would enable to user to setup their preferred reminders. For example: Meeting will be held at a certain date (let's say 25th of April 2018, 8:00 PM) and user should be able to setup a custom reminder (via SMS for example but the question is not about the sending texts or emails - I got this covered) to be fired up 24h before the time of meeting. It got me thinking that this requires some kind of a permanent process browsing through the meetings table and checking if now() is the appointment time -24h and if yes then perform the reminder. I started with rabbitmq and celery but these look a bit complicated at first glance (here's one of the tutorials I found) and looks like it's not designed for what I need. So, question is - how to setup a permanent process that would check if a set reminder time is now and if yes - perform the reminder task? EDIT: some errors after trying to follow the tutorial in answer. Got stuck at step 3: (dj2_env) adrian@dev:~$ celery -A dj2 worker -l info Traceback (most recent call last): File "/home/adrian/dj2_env/lib/python3.5/site-packages/celery/app/utils.py", line 361, in find_app found = sym.app AttributeError: module 'dj2' has no attribute 'app' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/adrian/dj2_env/bin/celery", line 11, in &lt;module&gt; sys.exit(main()) File "/home/adrian/dj2_env/lib/python3.5/site-packages/celery/__main__.py", line 14, in main _main() File "/home/adrian/dj2_env/lib/python3.5/site-packages/celery/bin/celery.py", line 326, in main cmd.execute_from_commandline(argv) File "/home/adrian/dj2_env/lib/python3.5/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execu…
tagged with: python
tagged with: rabbitmq
score: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49841882
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/49841578
has answer: http://stackoverflow.com/a/49841578
tagged with: celery
has comment: http://stackoverflow.com/comment/86698121

http://stackoverflow.com/a/49833241
has body: try: filter = {} for field in fields_list: filter.update({field: 20}) qs = qs.filter(**filter) return qs
has comment: http://stackoverflow.com/comment/86681836
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49833183
has comment: http://stackoverflow.com/comment/86681731

stack
tags question: http://stackoverflow.com/q/49833843
tags question: http://stackoverflow.com/q/49829288
type: Tag
tag name: stack
tags question: http://stackoverflow.com/q/49779606

http://stackoverflow.com/comment/86557925
comment on: http://stackoverflow.com/a/49759429
type: Comment
has text: Thank you, that works very well and that is very simple. I now see where you got the url where the data comes from but how did you get it? I can see it in the source but couldn't find it with the F12 table of Chrome…
score: 0
type: AnswerComment

http://stackoverflow.com/q/49859931
tagged with: cron
has answer: http://stackoverflow.com/a/49910624
tagged with: google-bigquery
type: Question
has title: Bigquery cron job does not work when user is not logged in to Google Cloud shell
has body: My cron job runs python code from App Engine on a scheduled time, but works only when I am logged in to the Google Cloud shell. When I quit Google Cloud shell, the cron job is still executed, but the python code takes no effect in BigQuery, where it should write data (as it does when I am logged in). My guess it has something to do with authentication, but due to the docs, it should "just work" with my credentials. http://google-cloud-python.readthedocs.io/en/latest/core/auth.html Any guesses what to do to make it work?
type: UnansweredQuestion
tagged with: google-app-engine
answer count: 1
tagged with: python
score: 0
tagged with: google-cloud-platform

http://stackoverflow.com/q/49907785
type: AnsweredQuestion
score: 0
tagged with: multithreading
has title: Simple multithreaded loop in Python
answer count: 1
accepted answer: http://stackoverflow.com/a/49907893
has answer: http://stackoverflow.com/a/49907893
type: Question
has comment: http://stackoverflow.com/comment/86831641
has body: I have a functioning loop that runs a series of sequential tests on each of a list of elements. Unfortunately the list is growing quickly, as are the number of tests, and I'd like to see if I can add threading to it in such a way that it can perform the tests on several different elements simultaneously. The tests themselves must be run sequentially as each may rely on previous data returned by the tests to perform the next one, but each element is independent and doesn't require data from another element. Only after each element is complete would something need to be done on the entire dataset. def do_some_tests_on_a_list_of_elements(element_list): do_some_stuff_here_to_set_up() for index, element in enumerate(element_list, start=1): element = do_some_stuff_on_element(index, element) do_some_stuff_after_each_element_has_finished() For example in this code, I'd want to do the setup, then allow the loop to process more than one element at a time via threading, and then after all elements are finished, do the final step on the dataset. What would be the simplest mechanism to achieve this?
tagged with: python

http://stackoverflow.com/q/49836827
tagged with: vector-graphics
has title: python - 3D visualisation of surfaces and shapes in vector graphics
favorite count: 0
type: Question
has body: In view of a comment to the original question, I want to stress the following two points that should apply to an answer to this question: 1) The final plot should be a true vector graphic, similar to what the pgfplots/tikz package in latex produce. 2) The final plot should be a correct 3D plot containing several elements, so the plotting package will probably need to use z-buffering to project and render correctly. I would like to visualise/plot 3D surfaces and geometric shapes in a single image using python. I am interested in 3D visualisation in general, but for now I am trying to do the following: I would like to plot a saddle shape in 3D (as a surface plot of an appropriate function, for example) and in addition display a 3D sphere that is tangent at a certain point of the saddle. Can this be done using matplotlib alone or do I need to use more sophisticated 3D packages like VTK? Even if it can be done in matplotlib, would you recommend matplotlib for such an application or should I use a program specifically built for this purpose? To give you an idea of what I want to achieve using only python, see here. This was done using pgfplots in latex, but as I mention in that question, there are limitations for that package. It's not python, either. I am not interested in a photorealistic appearance or fancy rendering. This is for a physics/maths application and I would like the image to have the "look" of plots you get with mplot3D or pgfplots in latex (so that surfaces are rendered like this in appearance). I have had a look at 3D rendering packages for python and though I cannot really quantify the reason for this (I think it might be the lighting and raster graphics), the output of many of them looks more like something out of a video game than a scientific publication (though this is probably intended for those renderers). I am aware that this is a rather broad question and if there are objections to this I am happy to rephrase the question or make it more specifi…
has comment: http://stackoverflow.com/comment/86689832
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49844090
score: 3
upvote count: 3
linked to: http://stackoverflow.com/q/12193709
tagged with: visualization
downvote count: 0
has comment: http://stackoverflow.com/comment/86698188
has comment: http://stackoverflow.com/comment/86697637
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86720606
answer count: 1

http://stackoverflow.com/a/49811328
answers question: http://stackoverflow.com/q/49810315
upvote count: 2
downvote count: 0
type: Answer
score: 2
has body: you can do something using regex : &gt;&gt;&gt; import re &gt;&gt;&gt; b=sum([re.findall(r'^[^,]+(?=,)', i) for i in a], []) &gt;&gt;&gt; b ['AIG', 'Baylor\xa0College\xa0of\xa0Medicine', 'CGG', 'Citi', 'ExxonMobil', 'Flow-Cal\xa0Inc.', 'Global\xa0Shop\xa0Solutions']

http://stackoverflow.com/q/49776310
has comment: http://stackoverflow.com/comment/86568824
downvote count: 0
has title: numpy 2d boolean array count consecutive True sizes
answer count: 1
favorite count: 0
type: Question
score: 3
has body: I'm interested in finding out individual sizes of the 'True' patches in a boolean array. For instance in the boolean matrix: [[1, 0, 0, 0], [0, 1, 1, 0], [0, 1, 0, 0], [0, 1, 0, 0]] The output would be: [[1, 0, 0, 0], [0, 4, 4, 0], [0, 4, 0, 0], [0, 4, 0, 0]] I'm aware that I can do this recursively, but I'm also under the impression that python array operations are costly on large scale and is there an available library function for this?
has answer: http://stackoverflow.com/a/49776605
accepted answer: http://stackoverflow.com/a/49776605
tagged with: python
tagged with: flood-fill
tagged with: numpy
type: AnsweredQuestion
tagged with: boolean
upvote count: 3

http://stackoverflow.com/a/49821927
type: Answer
score: -1
upvote count: 0
downvote count: 1
has body: why don't you use some javascript? get all the html code/text var wholeText = document.documentElement.innerHTML; then split by "Airport" var repeat = wholeText.split("Airport"); finally count the elements in your repeat array total = repeat.length -1 this should give you all the airports in the whole code (including backend) another easy approach is just use your Ctrl + F and find the occurrences manually
answers question: http://stackoverflow.com/q/49821837

http://stackoverflow.com/q/49831540
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86678726
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86678369
has comment: http://stackoverflow.com/comment/86694141
has body: I am a python newbie and I've been trying to scrap my University's Website to get a list of my grades with no luck so far. I try to log in making a POST request with the form-data that's shown in the code and then make a GET request for request_URL. However when I try to print the requested url's content login url's content comes up. So it is pretty clear that I can't get past login page. import requests from bs4 import BeautifulSoup login_URL = 'http://gram-web.ionio.gr/unistudent/login.asp' request_URL = 'http://gram-web.ionio.gr/unistudent/stud_CResults.asp?studPg=1&amp;mnuid=mnu3&amp;' payload = { 'userName': 'username', 'pwd': 'password', 'submit1': 'Login', 'loginTrue': 'login' } with requests.Session() as session: post = session.post(login_URL, data=payload) r = session.get(request_URL) root = BeautifulSoup(r.text, "html.parser") print(root) I assume there is some kind of token value involved in the process because that's what the POST request looks like when I try to log in manually. Has anybody seen this before ? Is this the cause why I cannot log in ? These are also the request headers.
has title: Can't login into a webpage using python
score: 0
has comment: http://stackoverflow.com/comment/86678557
answer count: 0
has comment: http://stackoverflow.com/comment/86678694
tagged with: authentication
has comment: http://stackoverflow.com/comment/86688088
tagged with: web-scraping
upvote count: 1
tagged with: python-requests

http://stackoverflow.com/comment/86667575
type: Comment
type: QuestionComment
has text: @eyllanesc and thank you for the tip, I'm in year 10 UK so I've only been coding like this for about 4 months and very basic stuff at that.
score: 0
comment on: http://stackoverflow.com/q/49825857

http://stackoverflow.com/comment/99936538
type: Comment
type: AnswerComment
has text: Very nice workaround, with very few impact on code structure. Thanks!
comment on: http://stackoverflow.com/a/49786016
score: 0

http://stackoverflow.com/q/49887144
has comment: http://stackoverflow.com/comment/86917809
has comment: http://stackoverflow.com/comment/87026502
possible better answer: http://stackoverflow.com/a/50009412
upvote count: 12
accepted answer: http://stackoverflow.com/a/50046123
has answer: http://stackoverflow.com/a/50045712
downvote count: 2
has answer: http://stackoverflow.com/a/50009412
has comment: http://stackoverflow.com/comment/86917744
has answer: http://stackoverflow.com/a/50046123
has comment: http://stackoverflow.com/comment/87107631
has body: I need to get all descendants point of links represented with side_a - side_b (in one dataframe) until reach for each side_a their end_point (in other dataframe). So: df1: side_a side_b a b b c c d k l l m l n p q q r r s df2: side_a end_point a c b c c c k m k n l m l n p s q s r s The point is to get all points for each side_a value until reach end_point from df2 for that value. If it has two end_point values (like "k" does) that it should be two lists. I have some code but it's not written with this approach, it drops all rows from df1 if df1['side_a'] == df2['end_points'] and that causes certain problems. But if someone wants me to post the code I will, of course. The desired output would be something like this: side_a end_point a [b, c] b [c] c [c] k [l, m] k [l, n] l [m] l [n] p [q, r, s] q [r, s] r [s] And one more thing, if there is the same both side, that point doesn't need to be listed at all, I can append it later, whatever it's easier. import pandas as pd import numpy as np import itertools def get_child_list(df, parent_id): list_of_children = [] list_of_children.append(df[df['side_a'] == parent_id]['side_b'].values) for c_, r_ in df[df['side_a'] == parent_id].iterrows(): if r_['side_b'] != parent_id: list_of_children.append(get_child_list(df, r_['side_b'])) # to flatten the list list_of_children = [item for sublist in list_of_children for item in sublist] return list_of_children new_df = pd.DataFrame(columns=['side_a', 'list_of_children']) for index, row in df1.iterrows(): temp_df = pd.DataFrame(columns=['side_a', 'list_of_children']) temp_df['list_of_children'] = pd.Series(get_child_list(df1, row['side_a'])) temp_df['side_a'] = row['side_a'] new_df = new_df.append(temp_df) So, the problem with this code is that works if I drop rows where side_a is equal to end_point from df2. I don't know how to implement condition that if catch the df2 in side_b column, then stop, don't go further. Any help or hint is welcomed here, truly. Thanks in advance.
has comment: http://stackoverflow.com/comment/86917908
favorite count: 0
tagged with: tree
tagged with: recursion
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86938524
answer count: 3
tagged with: pandas
score: 10
has title: Find all descendants for points in Python
tagged with: python
has comment: http://stackoverflow.com/comment/87033706
has comment: http://stackoverflow.com/comment/86935258
tagged with: descendant
type: Question

http://stackoverflow.com/q/49894665
has comment: http://stackoverflow.com/comment/86805423
has comment: http://stackoverflow.com/comment/86804859
tagged with: python-2.7
upvote count: 0
has body: I saved tweets in a json file This is my code : def on_data(self, data): try: with codecs.open('python.json', 'a', encoding='utf-8') as f: f.write(data) print("Tweet ajoute au JSON") return True except BaseException as e: print("Error on_data: %s" % str(e)) return True but I get this type of character : \u0e40\u0e21\u0e19\u0e0a I tried everything to not have this kind of character but nothing works(utf-8, latin2...)
has comment: http://stackoverflow.com/comment/86805142
has answer: http://stackoverflow.com/a/49896022
has comment: http://stackoverflow.com/comment/86805150
has comment: http://stackoverflow.com/comment/86805050
answer count: 1
has comment: http://stackoverflow.com/comment/86843656
has comment: http://stackoverflow.com/comment/86804789
tagged with: unicode
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86805019
has comment: http://stackoverflow.com/comment/86805384
has comment: http://stackoverflow.com/comment/86805169
downvote count: 3
tagged with: nltk
type: UnansweredQuestion
has title: Unicode issue in Python 2.7
has comment: http://stackoverflow.com/comment/86805400
score: -3
has comment: http://stackoverflow.com/comment/86804964
has comment: http://stackoverflow.com/comment/86804871
tagged with: python

http://stackoverflow.com/comment/86814474
score: 0
type: AnswerComment
has text: @zipa how can I improve the title to make the question more clear?
comment on: http://stackoverflow.com/a/49899275
type: Comment

http://stackoverflow.com/comment/86748593
score: 0
has text: @Alex...I didn't post my code because all I've done so far is to hardwire the name of the button I want to click. So I use Selenium to successfully navigate to the page listing the rooms and then my code is hardwired to the Room 34 button as it stands today (but it will change in the future based on which other rooms are available and used to build the table on the page). I'll add that code above to my original question.
type: Comment
comment on: http://stackoverflow.com/q/49863598
type: QuestionComment

http://stackoverflow.com/q/49871436
score: 1
tagged with: matplotlib
has title: Scatterplot with 'continuous bivariate' color palette in python
tagged with: gradient
answer count: 1
downvote count: 0
duplicate of: http://stackoverflow.com/q/41966600
linked to: http://stackoverflow.com/q/15207255
favorite count: 0
type: Question
tagged with: seaborn
duplicate of: http://stackoverflow.com/q/15207255
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49872194
has body: I have been able to plot scatter with color palette representing the continuous variable using following script: import numpy as np import seaborn as sns import matplotlib.pyplot as plt x, y, z = np.random.rand(3, 50) cmap = sns.cubehelix_palette(start=5, light=1, as_cmap=True) fig, ax = plt.subplots() points = ax.scatter(x, y, c=z, s=20, cmap=cmap) fig.colorbar(points) Output univariate palette However, I need to create a map with 'bivariate color palette'. I will ultimately be creating map like this but at the time being I am looking for plotting scatter in such a way. (Source : https://www.linkedin.com/feed/update/urn:li:activity:6378928737907466240) Bivariate palette I am looking to plot scatter such that the color represents both variables RMSE and R as in the map.
tagged with: plot
has answer: http://stackoverflow.com/a/49872194
type: AnsweredQuestion

http://stackoverflow.com/comment/86664675
comment on: http://stackoverflow.com/q/49823091
score: 0
type: Comment
type: QuestionComment
has text: If you're trying to create some form of audit log (which I think you are) then there are a number of packages availables. Take a look here: https://djangopackages.org/grids/g/model-audit/

http://stackoverflow.com/comment/87967034
comment on: http://stackoverflow.com/a/50446803
type: AnswerComment
score: 1
has text: @constructor, anyway, from the point of view of the OP, they should have been separated initially - it's a bad idea to run some of the Matlab calculations in one thread with a graphical interface. However, if they were separated in the first place, then the described problem wouldn't occur!
type: Comment

http://stackoverflow.com/q/49765684
has answer: http://stackoverflow.com/a/49765724
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86546949
has comment: http://stackoverflow.com/comment/86546936
downvote count: 5
tagged with: python
score: -5
has comment: http://stackoverflow.com/comment/86546902
has body: enter image description here I do not how to tackle with the exponent function with complex in powerenter image description here
has answer: http://stackoverflow.com/a/49765696
favorite count: 0
type: Question
answer count: 2
has title: what is wrong with exp(1 - 1j).real

http://stackoverflow.com/q/49864892
has answer: http://stackoverflow.com/a/50686367
tagged with: obd-ii
has title: OBD returns different number of commands supported everytime I run it
score: 0
answer count: 1
tagged with: elm327
type: Question
has body: I am using python OBD library and every time I run connection_to_obd = obd.OBD("/dev/rfcomm0", baudrate=38400, protocol="5", fast=False) even with auto protocol to establish a connection this happens 7 commands supported or 45 commands supported. Why does it work sometimes and others not?
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/86579895
type: Comment
comment on: http://stackoverflow.com/a/49782233
type: AnswerComment
score: 1
has text: @npatel I might use `.has_key()` as a more robust check for existence over handling an exception after attempting access, but yes, the concept is that those variables will exist (or not) depending upon the parent environment.

http://stackoverflow.com/comment/86727599
has text: Hi again, can you tell me please where is my mistake? I try to download 5 times the file but I receive only 1 file. http://collabedit.com/8ysuf Name: aa
comment on: http://stackoverflow.com/a/49855564
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49791526
has answer: http://stackoverflow.com/a/75319282
favorite count: 0
type: Question
has body: I have a python script that gets information from a Google Spreedsheet using gspread. scope = ['https://spreadsheets.google.com/feeds'] creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope) client = gspread.authorize(creds) sheet_programar = client.open("FILE").worksheet("SHEET") # Extract and print all of the values list_of_hashes = sheet_programar.get_all_records() this is part of script that is contatly running, but the gspread part only runns on a few ocations during the day. this all works, but if i try to use the same credentials on another script to access the same sheet, i get an error that i dont have permision. My understanding of the problem is that the first script is not closing the connection, hence i can't log in with the same credentials. i can't find anywhere information on how this can be closed ?
has comment: http://stackoverflow.com/comment/93875937
tagged with: python
tagged with: gspread
has answer: http://stackoverflow.com/a/69484762
score: 4
upvote count: 4
has title: Close connection on gspread
has comment: http://stackoverflow.com/comment/126854286
answer count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/92079041

http://stackoverflow.com/q/49849336
score: -1
tagged with: many-to-many
has title: Django adding to duplicate model object with Many-to-Many Relation to same model ('self') result with add to original object
downvote count: 1
favorite count: 0
has body: I have a duplicate method of an object that contains a Many-to-Many Relation to same 'self', to duplicate I used the 'copy' method. Problem: I noticed that when later adding to this field new (self) objects, they were added also to the original object many-to-many field. class CanvasOperation(models.Model): dependencies = models.ManyToManyField("self", related_name="+", blank=True) def duplicate(self): duplicated = copy.copy(self)
type: Question
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49849380
tagged with: addition
answer count: 1
tagged with: django
tagged with: python

http://stackoverflow.com/comment/86669885
has text: Ah shoot. I don't think it's going to fix the problem. The idea with the a array is that it is using the values in the array to look up the first value in the b array, then storing the latter three values in the b array to be used in the e array.
type: Comment
comment on: http://stackoverflow.com/a/49826991
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86817635
type: AnswerComment
has text: I believe it should be <=
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49901127

http://stackoverflow.com/a/49776488
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49775762
has comment: http://stackoverflow.com/comment/86569743
has comment: http://stackoverflow.com/comment/86568673
has comment: http://stackoverflow.com/comment/86571416
type: Answer
has body: You can use tkinter's messagebox. Tkinter has a built in method that can be used for all kinds of pop-up messages or questions. Here we will use messagebox.showinfo. I am working on Python 3.X so I added a import method that will work for both 3.X and 2.X versions of python. from threading import Thread from time import sleep try: import Tkinter as tk import tkMessageBox as mb import ttk except ImportError: import tkinter as tk from tkinter import messagebox as mb import tkinter.ttk as ttk class SmallGui: def __init__(self, master): self.master = master self.master.title('test gui') self.button_1 = ttk.Button(self.master, text='Start 1', command=lambda: self.init_thread(1)) self.button_2 = ttk.Button(self.master, text='Start 2', command=lambda: self.init_thread(2)) self.button_1.pack() self.button_2.pack() def init_thread(self, work): if work == 1: t = Thread(target=self.work_1) t.start() else: t = Thread(target=self.work_2) t.start() @staticmethod def work_1(): print ('Work 1 started') # Do some Task and return a list sleep(1) mb.showinfo("test", "Work 1 complete") @staticmethod def work_2(): print ('Work 2 Started') # Do some Task and return a list sleep(1) mb.showinfo("test", "Work 2 complete") if __name__ == '__main__': root = tk.Tk() run_gui = SmallGui(root) root.mainloop() UPDATE: For whatever reason my above solution works in python 3 but no in 2.7.14. The below example however does work in 2.7.14 and should work for you. What I have done here is create 2 class attributes to monitor each thread. I have created a method that will check ever 1 second if a thread is active and if the thread becomes inactive a messagebox will popup. from threading import Thread from time import sleep import Tkinter as tk import tkMessageBox as mb import ttk class SmallGui(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.master = master self.master.title('test gui') self.button_1 = ttk.Button(self.master, text='Start 1', command=lambda: self.init_thread(…
has comment: http://stackoverflow.com/comment/86568442
has comment: http://stackoverflow.com/comment/86569784
accepted answer of: http://stackoverflow.com/q/49775762
score: 3

django-tests
tags question: http://stackoverflow.com/q/49861004
type: Tag
tag name: django-tests

http://stackoverflow.com/q/49910982
tagged with: lxml
tagged with: python
type: Question
has title: How do I use lxml to interact with the page and pull up a menu to be scraped?
has body: For reference, this is the page that I will use as an example. It is the one that best demonstrates what I am trying to accomplish. If you look at the page, there is a brands banner at the top of the screen. In the top right hand corner, there is a see all button which pulls up a menu. The data from this menu is not in the html, it is generated by the click of that button. Is there any way to have lxml perform the action of clicking that button and pulling up that menu? I took a look at the network log. There does not appear to me that there is any file or url in there that would contain the data from that menu. I believe selenium does have this functionality, but I would prefer to not have to use only lxml.
answer count: 1
has answer: http://stackoverflow.com/a/49911760
accepted answer: http://stackoverflow.com/a/49911760
tagged with: web-scraping
tagged with: python-requests
type: AnsweredQuestion
score: 0

flask
tags question: http://stackoverflow.com/q/49777115
tags question: http://stackoverflow.com/q/49883996
tags question: http://stackoverflow.com/q/49856496
tags question: http://stackoverflow.com/q/49888276
tags question: http://stackoverflow.com/q/49820972
tags question: http://stackoverflow.com/q/49781878
tags question: http://stackoverflow.com/q/49901197
tags question: http://stackoverflow.com/q/49893574
tags question: http://stackoverflow.com/q/49848965
tags question: http://stackoverflow.com/q/49824778
tags question: http://stackoverflow.com/q/49848692
tags question: http://stackoverflow.com/q/49808046
tags question: http://stackoverflow.com/q/49816063
tags question: http://stackoverflow.com/q/49898842
tags question: http://stackoverflow.com/q/49849300
tags question: http://stackoverflow.com/q/49890583
tags question: http://stackoverflow.com/q/49915758
tags question: http://stackoverflow.com/q/49785019
tags question: http://stackoverflow.com/q/49884433
tags question: http://stackoverflow.com/q/49871020
tags question: http://stackoverflow.com/q/49837294
tags question: http://stackoverflow.com/q/49794694
tags question: http://stackoverflow.com/q/49776101
tags question: http://stackoverflow.com/q/49862691
tags question: http://stackoverflow.com/q/49822676
tags question: http://stackoverflow.com/q/49844449
tags question: http://stackoverflow.com/q/49907018
tags question: http://stackoverflow.com/q/49868005
tags question: http://stackoverflow.com/q/49773141
tags question: http://stackoverflow.com/q/49889702
tags question: http://stackoverflow.com/q/49887159
tags question: http://stackoverflow.com/q/49884143
tags question: http://stackoverflow.com/q/49814358
tags question: http://stackoverflow.com/q/49783442
tags question: http://stackoverflow.com/q/49909363
tags question: http://stackoverflow.com/q/49776619
tags question: http://stackoverflow.com/q/49768961
tags question: http://stackoverflow.com/q/49778389
tags question: http://stackoverflow.com/q/49777383
tags question: http://stackoverflow.com/q/49849435
tags question: http://stackoverflow.com/q/49762540
tags question: http://stackoverflow.com/q/49827095
tags question: http://stackoverflow.com/q/49906207
tags question: http://stackoverflow.com/q/49803518
tags question: http://stackoverflow.com/q/49874195
tags question: http://stackoverflow.com/q/49824049
tags question: http://stackoverflow.com/q/49805707
tags question: http://stackoverflow.com/q/49759170
tags question: http://stackoverflow.com/q/49882466
tags question: http://stackoverflow.com/q/49807446
tags question: http://stackoverflow.com/q/49793830
tags question: http://stackoverflow.com/q/49861846
tags question: http://stackoverflow.com/q/49769131
tags question: http://stackoverflow.com/q/49887289
tags question: http://stackoverflow.com/q/49913805
tags question: http://stackoverflow.com/q/49868455
tags question: http://stackoverflow.com/q/49770999
tags question: http://stackoverflow.com/q/49808367
tags question: http://stackoverflow.com/q/49797786
tags question: http://stackoverflow.com/q/49832425
tags question: http://stackoverflow.com/q/49903579
tags question: http://stackoverflow.com/q/49904483
tags question: http://stackoverflow.com/q/49848329
tags question: http://stackoverflow.com/q/49770492
tags question: http://stackoverflow.com/q/49763571
tags question: http://stackoverflow.com/q/49842873
tags question: http://stackoverflow.com/q/49900340
tags question: http://stackoverflow.com/q/49860830
tags question: http://stackoverflow.com/q/49777605
tags question: http://stackoverflow.com/q/49792619
tags question: http://stackoverflow.com/q/49864298
tags question: http://stackoverflow.com/q/49847076
tags question: http://stackoverflow.com/q/49881566
tags question: http://stackoverflow.com/q/49814750
tags question: http://stackoverflow.com/q/49846917
tags question: http://stackoverflow.com/q/49870587
tags question: http://stackoverflow.com/q/49902115
tags question: http://stackoverflow.com/q/49804665
tags question: http://stackoverflow.com/q/49843914
tags question: http://stackoverflow.com/q/49834210

http://stackoverflow.com/comment/86569357
type: Comment
type: AnswerComment
has text: print(lps('abac'))
comment on: http://stackoverflow.com/a/49776790
score: 0

http://stackoverflow.com/q/49814554
answer count: 2
has answer: http://stackoverflow.com/a/49814704
upvote count: 2
accepted answer: http://stackoverflow.com/a/49814704
downvote count: 0
tagged with: loops
has answer: http://stackoverflow.com/a/49814837
possible better answer: http://stackoverflow.com/a/49814837
has body: I am trying to run my model for all 3 input-scenarios using a loop instead of having to copy paste the script 3 times and changing the input-data manually. I have 3 arrays of input-data and would like to store the results (also arrays of the same length) in separate nested arrays within the same variable. Currently, I only know how to append the results. However, it is incorrect and I want to store the results for the different scenario-runs in separate elements within the same variable. import numpy as np # Scenarios years = np.arange(50) sc0 = np.arange(50) sc1 = np.arange(50)+100 sc2 = np.arange(50)+200 scenarios = [sc0, sc1, sc2] results = [] # Model computes something for sc in range(3): for t in years: outcome = scenarios[sc][t] / 10 results.append(outcome) In a nutshell, the solution should allow me to access the results for all model runs using results[0], results[1], and results[2]
favorite count: 0
type: Question
tagged with: python
has title: Iterating through input-scenarios and storing results as nested arrays in Python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/86842358
type: AnswerComment
comment on: http://stackoverflow.com/a/49815956
score: 0
type: Comment
has text: I don't know enough about `dynamodb` to answer that question sorry. Maybe create a new question for this.

http://stackoverflow.com/a/62287552
answers question: http://stackoverflow.com/q/49848517
score: 0
has body: In my case, i got an error while trying to install BioPython, "BioPython requires python version greater than 3.6" So installing the latest version fixed it for me.
type: Answer

http://stackoverflow.com/comment/86619747
type: Comment
comment on: http://stackoverflow.com/q/49802172
type: QuestionComment
has text: The dupe I marked is about colorbars, however the same solution can be applied to the second y axis
score: 1

http://stackoverflow.com/a/49850082
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49848152
upvote count: 2
downvote count: 0
has body: Clever use of numpy.argpartition. We start with a boolean array of where things not equal to zero. Then we partition each row into the three lowest values and the rest. If there are at least 3 zeros, then all of the first three elements will come back false. df[~(df.values != 0).argpartition(3, 1)[:, :3].all(1)] ind_key prtCnt fldCnt TmCnt bmCnt 1 2 2 0 0 3 3 4 0 1 1 0

http://stackoverflow.com/a/49832491
answers question: http://stackoverflow.com/q/49832443
upvote count: 1
score: 0
has body: you can use set that returns unique value In [44]: def func1(l): ...: return [x for x in set(l)] ...: In [45]: l=['a','b','b','c','d','d','d','e','f'] ...: In [46]: func1(l) Out[46]: ['a', 'c', 'b', 'e', 'd', 'f'] In [47]:
downvote count: 1
type: Answer

http://stackoverflow.com/a/49830579
has comment: http://stackoverflow.com/comment/86676855
type: AcceptedAnswer
has body: You may have issues depending on what codecs and other elements of gstreamer you have available on your system but this worked for me: gst-launch-1.0 ximagesrc startx=0 use-damage=0 ! video/x-raw,framerate=30/1 ! videoscale method=0 ! video/x-raw,width=1280,height=1080 ! videoconvert ! x264enc ! avimux ! filesink location=output2.avi So the videoconvert is required because x264enc has a different input type to ximagesink. x264enc is the codec itself, avimux puts the compressed video in an avi container and filesink is used to write the file out. For the Python API, an easy MCVE is: #!/usr/bin/python import os import gi import sys import time gi.require_version('Gtk', '3.0') gi.require_version('Gst', '1.0') from gi.repository import Gst, GObject, Gtk Gtk.init(sys.argv) # initialize GStreamer Gst.init(sys.argv) pipeline = Gst.parse_launch ("ximagesrc startx=0 use-damage=0 ! video/x-raw,framerate=30/1 ! videoscale method=0 ! video/x-raw,width=1280,height=1080 ! videoconvert ! x264enc ! avimux ! filesink location=output4.avi") pipeline.set_state(Gst.State.PLAYING) time.sleep(15) pipeline.set_state(Gst.State.NULL)
accepted answer of: http://stackoverflow.com/q/49829072
type: Answer
answers question: http://stackoverflow.com/q/49829072
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/86788620
score: 0
has text: ctrl+c should stop the code execution. Try to reset your workspace if you have one.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49885598

http://stackoverflow.com/comment/86598506
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49791536
has text: The elements in the line, I understand how they're being displayed now, but now I'm stuck on how I'm going to reference them in the e-mails themselves. Because they'll arrive in a single string.

http://stackoverflow.com/q/49829618
accepted answer: http://stackoverflow.com/a/49829693
upvote count: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: http://stackoverflow.com/tag/csv
has body: I want to write different column and its value into a single CSV file, But its overriding the previous lines. My code is , import csv onlyKeys=['date'] def samp(date,field): onlyKeys.append(field) myFile = open('fulltest.csv', 'wb') with myFile: writer1 = csv.DictWriter(myFile, fieldnames=onlyKeys) writer1.writeheader() writer1.writerow({'date' : date, field: 1}) print('row written') myFile.close() samp('jan 10 2018 23:34:55','Video Error1') samp('jan 10 2018 23:34:56','Video Error2') samp('jan 10 2018 23:34:57','Video Error3') My Expected output is date,Video Error1,Video Error2,Video Error3 jan 10 2018 23:34:55,1,0,0 jan 10 2018 23:34:56,0,1,0 jan 10 2018 23:34:57,0,0,1 But What I'm getting is, date,Video Error1,Video Error2,Video Error3 jan 10 2018 23:34:57,,,1 How to write each row on seperate line. Thanks
has answer: http://stackoverflow.com/a/49829693
answer count: 1
has title: How to Create proper CSV using Dict Writer in python?
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49832373
favorite count: 0
has answer: http://stackoverflow.com/a/56037843
type: Question
has body: from selenium import web driver from browsermobproxy import Server from selenium.webdriver.common.by import By import json import time server = Server(r'D:\browsermob-proxy-2.1.4\bin\browsermob-proxy.bat') server.start() proxy = server.create_proxy({'captureHeaders': True, 'captureContent': True, 'captureBinaryContent': True}) profile = webdriver.FirefoxProfile() profile.set_proxy(proxy.selenium_proxy()) driver = webdriver.Firefox(firefox_profile=profile) proxy.new_har('xxx') driver.get('XXX') proxy.wait_for_traffic_to_stop(1, 60) This is all I get: I want to get the response from the body but failed, are there any arguments I need to set?
score: 3
tagged with: python
has title: Can`t get response body in HAR, Browsermobproxy + selenium + FireFox in Python
upvote count: 3
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86691798
tagged with: browsermob-proxy

http://stackoverflow.com/a/49874282
downvote count: 0
has body: You have created the subplots, however you are not using them when you are plotting the graph. You need pass the subplots as arguments into the plotting function by doing ax=gh1. You code should look like: fig = plt.figure(figsize=(8,6)) gh1 = fig.add_subplot(121) temp1.plot(kind='bar', ax=gh1) # pass in subplot as an argument gh1.set_xlabel('credit_history') gh1.set_ylabel('count of credit history') gh1.set_title('Applicants by credit history') gh2 = fig.add_subplot(122) temp2.plot(kind='bar', ax=gh2) # pass in subplot as an argument gh2.set_xlabel('credit_history') gh2.set_ylabel('Probability of loan by credit history') gh2.set_title('Probability of getting loan by credit history') plt.show()
has comment: http://stackoverflow.com/comment/86811327
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86810262
type: Answer
accepted answer of: http://stackoverflow.com/q/49869847
answers question: http://stackoverflow.com/q/49869847
type: AcceptedAnswer

http://stackoverflow.com/a/49805801
has body: Numpy is notoriously difficult to install as it contains dependencies (optional or selectable) on various non-Python packages. I would suggest to use a different environment manager such as Enthought or Anaconda (which I would recommend). If you want to do a quick start, use the full-blown anaconda distribution. If you need more explicit control, use miniconda. Once you have anaconda installed, all you need to do to create a new conda environment (similar to a virtual environment, but with non-python packages included in the environment itself) is conda create -n my_shining_environment quandl The above will include quandl (at the time of writing v3.3.0), numpy and all other dependencies for quandl.
type: Answer
score: -1
answers question: http://stackoverflow.com/q/49805576
downvote count: 2
upvote count: 1

http://stackoverflow.com/q/49910137
has answer: http://stackoverflow.com/a/49923048
tagged with: django
tagged with: python
has body: I have a FileField Serializer for uploaded base64 audio, I noticed that the Base64 string does not start with data:****. How do I determine the Mime Type of the uploaded file? i_need_the_file_extension_mimetype() class AudioField(serializers.FileField): def to_internal_value(self, data): if isinstance(data, basestring): data = re.sub(r"^data\:.+base64\,(.+)$", r"\1", data) # Try to base64 decode the data url. try: decoded = base64.b64decode(data) except TypeError: raise serializers.ValidationError(_('Not a valid file')) file_name, file_ext, mime_type = self.i_need_the_file_extension_mimetype(decoded) data = ContentFile(decoded, name=file_name) return super(AudioField, self).to_internal_value(data)
has comment: http://stackoverflow.com/comment/86842052
has comment: http://stackoverflow.com/comment/86837732
has comment: http://stackoverflow.com/comment/86848704
type: AnsweredQuestion
tagged with: audio
linked to: http://stackoverflow.com/q/43580
has comment: http://stackoverflow.com/comment/86850478
upvote count: 3
has comment: http://stackoverflow.com/comment/86850591
has title: Determine base64 uploaded file extension and mime type
answer count: 1
has comment: http://stackoverflow.com/comment/86838480
downvote count: 0
has comment: http://stackoverflow.com/comment/86836989
tagged with: django-rest-framework
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86849403
score: 3
accepted answer: http://stackoverflow.com/a/49923048
has comment: http://stackoverflow.com/comment/86837644
tagged with: mime-types
has comment: http://stackoverflow.com/comment/86848697
linked to: http://stackoverflow.com/q/34287819

http://stackoverflow.com/q/49900521
has answer: http://stackoverflow.com/a/49922175
tagged with: openssl
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87044798
answer count: 1
has title: Not able to install any library [SSL: TLSV1_ALERT_PROTOCOL_VERSION]
type: Question
linked to: http://stackoverflow.com/q/49768770
tagged with: terminal
tagged with: ssl
tagged with: python
accepted answer: http://stackoverflow.com/a/49922175
tagged with: ssl-certificate
has body: Operating system: Mac OS 10.12.6 Python: I would like to install on 3.5 but there might be a confusion as you can see down here pip version: 8.1.2 First I was trying to install a library called scrapy using pip install scrapy. This happened: Could not fetch URL https://pypi.python.org/simple/pip/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:646) - skipping Requirement already up-to-date: pip in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages You are using pip version 8.1.2, however version 10.0.0 is available. You should consider upgrading via the 'pip install --upgrade pip' command. It suggested me to upgrade my pip, so I did pip install --upgrade pip and surprise: Could not fetch URL https://pypi.python.org/simple/pip/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:646) - skipping Requirement already up-to-date: pip in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages You are using pip version 8.1.2, however version 10.0.0 is available. You should consider upgrading via the 'pip install --upgrade pip' command. One thing I noticed is that terminal is "talking" to Python 3.5 (as you can see in the error text above) however if I python --version it returns Python 2.7.10. So then I tried pip3 install scrapy. Same result. I tried many suggestions from other posts and nothing works. I'm going nuts here. Could someone help?

http://stackoverflow.com/a/49909014
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49906207
answers question: http://stackoverflow.com/q/49906207
type: Answer
has body: Try printing this line: l_sortedQueue.insert(n_queue_position, l_sortedQueue.pop(i)). You will see that it prints to None. This is because insert is a function, which doesn't return a value. So what you think you're doing is assigning l_SortedQueue to l_queue, but what you're actually doing is overwriting your l_queue list with the None. What you should change it to: sortedQueue.insert(n_location, sortedQueue.pop()) que = sortedQueue However, it looks like you're looping in a pretty hacky way which I'm not really following. I think there are better solution to your problem than this solution though.
downvote count: 0
score: 1

http://stackoverflow.com/comment/86710678
has text: @Chriskim That comment looks a bit dense. If this is supposed to be clarification of the original question, you should use the little gray 'edit' button in the lower left corner to update the question. Comments don't preserve formatting so crucial for python code.
comment on: http://stackoverflow.com/a/49847046
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/49913578
accepted answer of: http://stackoverflow.com/q/49902780
has body: There are multiple bugs in the code: As Pointed out in the comment by @Y. Luo: x_batch = sequence.pad_sequences(x_train, maxlen=None) # gives 25000 samples x_batch = sequence.pad_sequences(x_batch, maxlen=None) # gives batch_size When loading the imdb dataset you have to give num_words=max_features otherwise your embedding layer will expect input max_words as max_features but will end up getting word_ids bigger than that. (x_train, y_train), (_,_) = imdb.load_data(num_words=max_features) It's recommended that while using padding you provide maxlen otherwise maxlen of batch will be used which might change from batch to batch x_batch = sequence.pad_sequences(x_batch, maxlen=maxlen, padding='post') You were using your embedding layer without training it and keeping the input and output dimension as same. Didn't make sense to me so I changed that. primary_model.add(Embedding(input_dim = max_features, output_dim = embedding_dim, trainable=True, weights=[(np.eye(max_features,embedding_dim))], mask_zero=True)) To evaluate your model on test data you have to load it first and then convert it into padded sequence (_,_), (x_test, y_test) = imdb.load_data(num_words=max_features) x_test = sequence.pad_sequences(x_test, maxlen=maxlen, padding='post') score, acc = primary_model.evaluate(x_test, y_test, batch_size=batch_size) print('Test score:', score) print('Test accuracy:', acc) While using a Generator for training over multiple epochs, we have to make sure that the generator keeps on yielding values. For this once the data set is over we need to start yielding from 0 again. def generate_batch(batchsize): (x_train, y_train), (_,_) = imdb.load_data(num_words=max_features) print("train_size", x_train.shape) while True: for i in range(0, len(x_train), batchsize): x_batch = x_train[i:(i+batchsize)] y_batch = y_train[i:(i+batchsize)] x_batch = sequence.pad_sequences(x_batch, maxlen=maxlen, padding='post') yield(x_batch, y_batch) Complete working code is linked (updated with fix for …
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86864090
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49902780

http://stackoverflow.com/comment/86832888
comment on: http://stackoverflow.com/q/49908444
score: 1
type: QuestionComment
has text: `((100/6)*14)/60` = about 4 minutes. His math is right.
type: Comment

http://stackoverflow.com/a/49781625
has comment: http://stackoverflow.com/comment/86582924
downvote count: 0
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/49781573
has comment: http://stackoverflow.com/comment/86579559
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86578755
has comment: http://stackoverflow.com/comment/86579148
upvote count: 6
has body: use logging # this logger will always now be logging.DEBUG level logging.getLogger("my_logger").setLevel(logging.DEBUG if args.debug else logging.WARNING) then use log = logging.getLogger("my_logger") ... log.warn("some text that should always be seen!") log.debug("some debug info!") you can then do things where you have multiple levels of logging log_level = logging.WARNING if args.verbose &gt; 0: log_level = logging.INFO elif args.verbose &gt; 3: log_level = logging.DEBUG if for some reason you needed to retrieve the currentEffectiveLogLevel (you really shouldnt in most cases ... simply use log.debug when you want debug level output) logging.getLogger("my_logger").getEffectiveLevel() [edit to clarify] log = logging.getLogger('my_logger') def summation(x, y, z): log.debug('I am going to add %s %s and %s' % (x, y, z)) # will not print if my_logger does not have an effective level of debug return x + y + z print(summation(2, 3, 4)) log.setLevel(logging.DEBUG) print(summation(4, 5, 6)) or you can wrie a helper funtion def is_debug(): return logging.getLogger("my_logger").getEffectiveLevel() == logging.DEBUG of coarse you can always do some horrible hacky crap also like writing it to a flat file and reading it in or using truly global variables (harder than you might think and lots of edge cases to worry about)
answers question: http://stackoverflow.com/q/49781573

http://stackoverflow.com/comment/128330038
comment on: http://stackoverflow.com/q/49817409
type: Comment
score: 1
has text: I tried this, but the command appends '.py' to the end of the file. I'm using Jupyter Lab 3.2.4
type: QuestionComment

python-imageio
type: Tag
tags question: http://stackoverflow.com/q/49819971
tag name: python-imageio

http://stackoverflow.com/comment/86541646
score: 0
type: QuestionComment
has text: @Primusa, I tried set doesn't work
comment on: http://stackoverflow.com/q/49762947
type: Comment

http://stackoverflow.com/a/49803677
score: 0
type: Answer
has body: You could make the initial list a set, but if you want to look up a word like 'hello' it wont work because you'll need both l's. One way to solve this is to use a dictionary to check and see how we are doing so far. letterList = ['H', 'E', 'L', 'X', 'L', 'I', 'O'] toBeFound = ['H', 'E', 'L', 'L', 'O'] # build dictionary to hold our desired letters and their counts toBeFoundDict = {} for i in toBeFound: if i in toBeFoundDict: toBeFoundDict[i] += 1 else: toBeFoundDict[i] = 1 letterListDict = {} # dictionary that holds values from input output_list = [] # dont use list its a reserved word for letter in letterList: if letter in letterListDict: # already in dictionary # if we dont have too many of the letter add it if letterListDict[letter] &lt; toBeFoundDict[letter]: output_list.append(letter) # update the dictionary letterListDict[letter] += 1 else: # not in dictionary so lets add it letterListDict[letter] = 1 if letter in toBeFoundDict: output_list.append(letter) if output_list == toBeFound: print('Success') else: print('fail')
answers question: http://stackoverflow.com/q/49803339

http://stackoverflow.com/a/49923443
has comment: http://stackoverflow.com/comment/87566103
has body: Answer: The fix was the JSON formatting for the schema. I still have no idea why the schema format in question would work on dev but not when deployed. Below is the schema formatting that worked on deploy. "schema": { "fields" : [ {"name": "date2", "type": "DATE"}, {"name": "username", "type": "STRING"}, {"name": "age", "type": "INTEGER"}, {"name": "favorite_number", "type": "FLOAT"} ] }
type: AcceptedAnswer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49881215
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49881215

merge
type: Tag
tags question: http://stackoverflow.com/q/49783669
tags question: http://stackoverflow.com/q/49815778
tags question: http://stackoverflow.com/q/49826378
tags question: http://stackoverflow.com/q/49873535
tag name: merge
tags question: http://stackoverflow.com/q/49850716
tags question: http://stackoverflow.com/q/49868820
tags question: http://stackoverflow.com/q/49875520
tags question: http://stackoverflow.com/q/49822030
tags question: http://stackoverflow.com/q/49827504
tags question: http://stackoverflow.com/q/49884863
tags question: http://stackoverflow.com/q/49886199

http://stackoverflow.com/a/49778047
has body: First create your dump file. file = open('filename', 'r') obj = file.read() pickle.dump(obj, open('file.pickle', 'wb')) then with open(file.pickle, 'rb') as fo: dict = pickle.load(fo, encoding='bytes')
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49777853

http://stackoverflow.com/q/49814299
has comment: http://stackoverflow.com/comment/86643171
has comment: http://stackoverflow.com/comment/86642874
downvote count: 1
has body: I want to print out the sum of str and float number by using the type function but somehow it's not working var1,var2,var3=[str(2),float(3.0),str(5)] print([var1,var2,var3]) if I simply apply plus function print(var1+var2+var3) it gives an error which I don't understand TypeError: must be str, not float
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86642932
has comment: http://stackoverflow.com/comment/86642992
accepted answer: http://stackoverflow.com/a/49814529
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49814529
linked to: http://stackoverflow.com/q/2823211
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46583409
duplicate of: http://stackoverflow.com/q/2823211
upvote count: 0
has comment: http://stackoverflow.com/comment/86643284
has title: sum of str and float number by using the type function not working?
answer count: 1

http://stackoverflow.com/q/49880673
has comment: http://stackoverflow.com/comment/86777222
has title: Python 3 File Indexing Parallel
tagged with: indexing
has comment: http://stackoverflow.com/comment/86777286
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86782596
has comment: http://stackoverflow.com/comment/86782552
has body: I have a question about python 3 file indexing. I have a code, it will list all file in my Computer into a file named test.txt. All I wanna do is to make this code paralel for faster processing time. import os import time start = time.time() handle = open("test.txt","w") rootDir = '/' for dirName, subdirList, fileList in os.walk(rootDir): for fname in fileList: handle.write("%s\n" %os.path.abspath(os.path.join(dirName,fname)).encode('utf-8')) handle.close() end = time.time() print (end-start) I hope you all can help me. Thanks a lot and have a nice day.
score: 0
tagged with: file
answer count: 0

http://stackoverflow.com/comment/86705100
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49845128
has text: @Brykyz why? Are you getting numbers from user input that you are trying to convert?

http://stackoverflow.com/q/49836217
has comment: http://stackoverflow.com/comment/86692465
type: Question
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86692597
has comment: http://stackoverflow.com/comment/86692574
has answer: http://stackoverflow.com/a/49838811
score: 0
has comment: http://stackoverflow.com/comment/86687952
has body: I am getting the below error even after doing a python setup.py install for xlwt. ImportError: No Module named xlwt I have tried installing using python wheel pip3 install xlwt-1.3.0-py2.py3-none-any.whl and I have also tried easy_installer, however the error is still there What might be the issue? I am using a windows 7 environment.
tagged with: python
has comment: http://stackoverflow.com/comment/86692572
has comment: http://stackoverflow.com/comment/86694052
has title: Error in importing xwlt package
has comment: http://stackoverflow.com/comment/86693960

http://stackoverflow.com/a/49780063
answers question: http://stackoverflow.com/q/49780018
upvote count: 0
downvote count: 2
has body: if you want to use class variable , you need to use self to reference it and try to not using same name for variable and method. btw you need to create instance of class to use class UserFullName: def FirstName(self): self.firstName = input("enter your first name:\n".title()) return self.firstName def LastName(self): self.lastName = input("enter your last name:\n".title()) return self.lastName def FullName(self): print('welcome', "{} {}".format(self.firstName, self.lastName).title()) userFullName = UserFullName() userFullName.FirstName() userFullName.LastName() userFullName.FullName() Enter Your First Name: 1 Enter Your Last Name: 2 ('welcome', '1 2') or if you prefer class method class UserFullName: @classmethod def FirstName(self): self.firstName = input("enter your first name:\n".title()) return self.firstName @classmethod def LastName(self): self.lastName = input("enter your last name:\n".title()) return self.lastName @classmethod def FullName(self): print('welcome', "{} {}".format(self.firstName, self.lastName).title()) UserFullName.FirstName() UserFullName.LastName() UserFullName.FullName() Enter Your First Name: 1 Enter Your Last Name: 2 ('welcome', '1 2')
type: Answer
has comment: http://stackoverflow.com/comment/86575586
score: -2
has comment: http://stackoverflow.com/comment/86575655

http://stackoverflow.com/q/49825186
has comment: http://stackoverflow.com/comment/86666944
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/86666387
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: How can Python give dfferent results for the same data set?
tagged with: python
has body: I am running the code below. import xml.etree.ElementTree as ET import csv tree = ET.parse('C:\\path\\Recon.xml') root = tree.getroot() with open('C:\\path\\data.txt', 'w') as f: writer = csv.writer(f) for neighbor in root.iter('outputColumn'): writer.writerow(neighbor.attrib) print(neighbor.attrib) In the console window I see this: {'refId': 'Package\\RAW DATA PORTFOLIO SPLIT\\Sequence Container\\RAW DATA WHOLESALE\\TBL_FR2052A_RAW_DATA_P_WHOLESALE.Outputs[OLE DB Destination Error Output].Columns[ErrorColumn]', 'dataType': 'i4', 'lineageId': 'Package\\RAW DATA PORTFOLIO SPLIT\\Sequence Container\\RAW DATA WHOLESALE\\TBL_FR2052A_RAW_DATA_P_WHOLESALE.Outputs[OLE DB Destination Error Output].Columns[ErrorColumn]', 'name': 'ErrorColumn', 'specialFlags': '2'} In the text file I see this: refId,dataType,lineageId,name,specialFlags What gets printed is exactly right. I would expect to see the same thing in the text file, but it is completely different. How can I get the writer to write what is being printed?
accepted answer: http://stackoverflow.com/a/49825227
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49825227

http://stackoverflow.com/a/49815510
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86646315
answers question: http://stackoverflow.com/q/49815405
has comment: http://stackoverflow.com/comment/86646609
has body: Probably you are passing a string as db. Try this (I assume you are using sqlite3): db = sqlite3.connect("your_db") # not db = "your_db" resultset = employee_list(db)

http://stackoverflow.com/comment/86646849
type: QuestionComment
has text: We need to know how your data looks like. Can you please indicate the shape of your input arrays?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49816000

http://stackoverflow.com/comment/86840149
has text: Here are two links to screenshots of eclipse https://drive.google.com/file/d/1_9Pnwvp6_sbSKQXiLShUnrnpMrwqFOqb/view?usp=sharing https://drive.google.com/file/d/1asH5YokYcx1lBMzceOiRCIj5_ubnbk1a/view?usp=sharing
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49911814

http://stackoverflow.com/comment/86612039
has text: @sciroccorics ok, just read your answer, thanks for the explanation !
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49797743
score: 0

http://stackoverflow.com/a/49778990
has comment: http://stackoverflow.com/comment/86573766
score: 11
answers question: http://stackoverflow.com/q/49778527
has comment: http://stackoverflow.com/comment/86573680
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49778527
has body: Rather than messing about with collections.defaultdict to make it do what we want, it seems easier to implement our own: class DefaultDict(dict): def __init__(self, default_factory, **kwargs): super().__init__(**kwargs) self.default_factory = default_factory def __getitem__(self, key): try: return super().__getitem__(key) except KeyError: return self.default_factory() This works the way you want: d = DefaultDict(int) res = d[5] d[8] = 1 d[3] += 1 print(d) # {8: 1, 3: 1} However, it can behave unexpectedly for mutable types: d = DefaultDict(list) d[5].append('foobar') print(d) # output: {} This is probably the reason why defaultdict remembers the value when a nonexistant key is accessed. Another option is to extend defaultdict and add a new method that looks up a value without remembering it: from collections import defaultdict class DefaultDict(defaultdict): def get_and_forget(self, key): return self.get(key, self.default_factory()) Note that the get_and_forget method calls the default_factory() every time, regardless of whether the key already exists in the dict or not. If this is undesirable, you can implement it with a sentinel value instead: class DefaultDict(defaultdict): def get_and_forget(self, key): _sentinel = object() value = self.get(key, _sentinel) if value is _sentinel: return self.default_factory() return value This has better support for mutable types, because it allows you to choose whether the value should be added to the dict or not.
upvote count: 11
downvote count: 0
type: Answer

http://stackoverflow.com/q/49842718
upvote count: 1
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49842856
type: Question
has answer: http://stackoverflow.com/a/49842856
has title: Jupyter notebook, output more than one expression from cell
tagged with: python
has answer: http://stackoverflow.com/a/61596441
tagged with: jupyter-notebook
tagged with: numpy
tagged with: python-3.x
tagged with: sympy
type: AnsweredQuestion
has body: I want to show the result of an intergation, done in SymPy as an Output in Jupyter with MathJax. Everything works, but I wanted to adjust the output a bit, so that instead of the following: I would get this output: (Please ignore the arctan() thing.) I have tried to achieve this by doing something like that: from IPython.display import Math from sympy.interactive import printing printing.init_printing(use_latex=True) f=(-2*x-1)/(pow(x,2)+2) Math('F(x)=') integrate(f,x) Math('+C') But unfortunately only the last output of the cell is shown, so my question is if it is possible to merge multiple outputs into one?
possible better answer: http://stackoverflow.com/a/61596441
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/86599410
type: AnswerComment
comment on: http://stackoverflow.com/a/49781472
has text: @Johnboy - Do you use `cols = df.columns.difference(['company_name', 'country_code', 'state_code']) df[cols] = df[cols].astype(float)` ?
score: 0
type: Comment

http://stackoverflow.com/q/49772684
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/64026632
tagged with: django
has comment: http://stackoverflow.com/comment/86563582
has comment: http://stackoverflow.com/comment/86560807
favorite count: 0
has title: Which Django Form Field can provide me a HTML output of ?
upvote count: 5
tagged with: django-models
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/86560431
has body: I've got a html form with this input: &lt;input id="duration_slider" type="range" min="1" max="168" value="48" /&gt; However I'd now like to convert this slider to a django form field, so I can use it in a Django form. The field name is duration so I'll change the id to id=id_duration. What would my models.py and forms.py looks like for this field? Currently it's just: class AdvertisePost(Post): ... duration = models.IntegerField(default=48) def __str__(self): return self.title class AdvertisePostForm(forms.ModelForm): duration = ? class Meta: model = AdvertisePost fields = [ ... #'duration' ] EDIT views if options_form.is_valid(): instance = options_form.save(commit=False) print(instance.duration) #prints the default value every time form field duration = forms.IntegerField(widget=forms.NumberInput(attrs={'type':'range', 'step': '1', 'min': '1', 'max': '148'}), required=False)
score: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86561788

http://stackoverflow.com/q/49883144
tagged with: python
has title: Store data from raspberry pi to MySQL server on remote desktop
has comment: http://stackoverflow.com/comment/86783403
answer count: 0
downvote count: 0
tagged with: remote-server
upvote count: 1
has comment: http://stackoverflow.com/comment/86783463
tagged with: mysql
favorite count: 0
type: Question
has body: I am getting data from sensor to raspberry pi and was storing locally but I was having trouble with memory so I decided to store data on my laptop via LAN and I had mysql server setup on my laptop. I had looked over google to figure it out but couldn't find a proper solution. TIA
type: UnansweredQuestion
score: 1
tagged with: database
has comment: http://stackoverflow.com/comment/86782805
has comment: http://stackoverflow.com/comment/86783289

http://stackoverflow.com/comment/86541773
type: AnswerComment
has text: assigning a new column with a dot-operator is iffy at best
comment on: http://stackoverflow.com/a/49762627
score: 0
type: Comment

http://stackoverflow.com/comment/86654176
has text: please check the code @Guybrush
type: QuestionComment
comment on: http://stackoverflow.com/q/49818688
score: 0
type: Comment

http://stackoverflow.com/q/49825421
has body: Hey i just did some research and found that i could download images from urls which end with filename.extension like 000000.jpeg. i wonder now how i could downoad a picture which doesnt have any extension. Here is my url which i want to download the image http://books.google.com/books/content?id=i2xKGwAACAAJ&amp;printsec=frontcover&amp;img=1&amp;zoom=1&amp;source=gbs_api when i put the url directly to the browser it displays an image furthermore here is what i tried: from six.moves import urllib thumbnail='http://books.google.com/books/content?id=i2xKGwAACAAJ&amp;printsec=frontcover&amp;img=1&amp;zoom=1&amp;source=gbs_api' img=urllib.request.Request(thumbnail) pic=urllib.request.urlopen(img) pic=urllib.request.urlopen(img).read() Anyhelp will be appreciated so much
has title: Download file using python without knowing its extension. - content-type - stream
tagged with: http-headers
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49825630
score: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/86666937
tagged with: stream
answer count: 1
has comment: http://stackoverflow.com/comment/86666679
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/49825630
favorite count: 0
type: Question
tagged with: python-3.x
downvote count: 2

http://stackoverflow.com/comment/86806227
has text: You'd want to make that a *set* instead, at which point you have an unbeatably fast solution. Use `valid_years = {str(x) for x in range(2000, 2021)}` (and avoid the `+ 1`). Sets let you test for membership in O(1) time, using a list has a linear O(length_of_list) cost.
type: AnswerComment
comment on: http://stackoverflow.com/a/49895484
type: Comment
score: 4

http://stackoverflow.com/a/49792193
score: 0
has body: you can make your model become like this: class Setting(models.Model): TYPE_CHOICES = ( (1, "Integer"), (2, "String"), (3, "Boolean"), (4, "Decimal") ) key = models.CharField(max_length=32) value = models.TextField() value_type = models.IntegerField(choices=TYPE_CHOICES) you can also add class function in this model to return value as its type like this: def get_typed_value(self): if self.value_type == self.INTEGER: return int(self.value) elif self.value_type == self.STRING: return self.value # ... do to other type
answers question: http://stackoverflow.com/q/49791845
type: Answer

http://stackoverflow.com/q/49762985
has comment: http://stackoverflow.com/comment/86560450
has comment: http://stackoverflow.com/comment/86572718
answer count: 0
has comment: http://stackoverflow.com/comment/86543843
downvote count: 0
upvote count: 1
tagged with: pip
score: 1
has comment: http://stackoverflow.com/comment/86543255
has title: Installing TensorFlow on Cygwin or pip problems
has comment: http://stackoverflow.com/comment/86542638
tagged with: tensorflow
has body: I tried this: $ pip install tensorflow Exception: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python2.7/site-packages/pip/commands/install.py", line 272, in run with self._build_session(options) as session: File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/usr/lib/python2.7/site-packages/pip/download.py", line 336, in __init__ retries = urllib3.Retry( AttributeError: 'module' object has no attribute 'Retry' Traceback (most recent call last): File "/usr/bin/pip", line 11, in &lt;module&gt; sys.exit(main()) File "/usr/lib/python2.7/site-packages/pip/__init__.py", line 233, in main return command.main(cmd_args) File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 251, in main timeout=min(5, options.timeout)) as session: File "/usr/lib/python2.7/site-packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/usr/lib/python2.7/site-packages/pip/download.py", line 336, in __init__ retries = urllib3.Retry( AttributeError: 'module' object has no attribute 'Retry' and that: $ pip3 install tensorflow Exception: Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python3.6/site-packages/pip/commands/install.py", line 272, in run with self._build_session(options) as session: File "/usr/lib/python3.6/site-packages/pip/basecommand.py", line 72, in _build_session insecure_hosts=options.trusted_hosts, File "/usr/lib/python3.6/site-packages/pip/download.py", line 336, in __init__ retries = urllib3.Retry( AttributeError: module 'pip' has no attribute 'Retry' Traceback (most recent call last): File "/usr/bin/pip3", line 11, in &lt;module&gt; sys.exit(main()) File "/usr/lib/python3.6/site-packages/pip/__init__.py", line 233, in m…
favorite count: 0
has comment: http://stackoverflow.com/comment/86542286
type: Question
has comment: http://stackoverflow.com/comment/86577135
has comment: http://stackoverflow.com/comment/86576217
has comment: http://stackoverflow.com/comment/86575897
has comment: http://stackoverflow.com/comment/86543855
has comment: http://stackoverflow.com/comment/86560064
has comment: http://stackoverflow.com/comment/86541963
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86567161
has comment: http://stackoverflow.com/comment/86577590
has comment: http://stackoverflow.com/comment/86544536
linked to: http://stackoverflow.com/q/29038889
tagged with: cygwin
tagged with: python
has comment: http://stackoverflow.com/comment/86542040
has comment: http://stackoverflow.com/comment/86543020

http://stackoverflow.com/comment/86791083
type: Comment
type: QuestionComment
has text: *Don't do that*, and also where the heck did the 6 go?
comment on: http://stackoverflow.com/q/49887524
score: 1

http://stackoverflow.com/comment/86633279
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49806893
has text: Your `ALLOWED_HOSTS` setting appears to be invalid - show us what that is.

http://stackoverflow.com/comment/86795846
comment on: http://stackoverflow.com/q/49889524
score: 0
type: Comment
type: QuestionComment
has text: Just the terminal

http://stackoverflow.com/a/49854999
has body: Do clf = GaussianNB().fit(text_train_tfidf.toarray() , list(zip(*train))[1]) The GaussianNB doesnt support sparse matrices as input for X, but the TfidfTransformer will by default return a sparse matrix. Hence the error. toarray() will convert that to dense. But note that it will lead to a high increase in memory usage. Update: When using a pipeline, you need to supply the data which you passed to transformer in the pipeline. In this case that is list(zip(*train))[0]. text_clf = text_clf.fit(list(zip(*train))[0] , list(zip(*train))[1]) That will solve your first error. But you will still get an error because of sparse matrix. See this answer for solving that :- https://stackoverflow.com/a/28384887/3374996
answers question: http://stackoverflow.com/q/49854899
has comment: http://stackoverflow.com/comment/86724785
has comment: http://stackoverflow.com/comment/86725200
has comment: http://stackoverflow.com/comment/86724637
type: Answer
has comment: http://stackoverflow.com/comment/86724907
has comment: http://stackoverflow.com/comment/86725781
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49854899
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86725681
has comment: http://stackoverflow.com/comment/86725636

http://stackoverflow.com/a/49905455
type: Answer
has comment: http://stackoverflow.com/comment/86827917
has body: Use the parse from dateutil.parser to parse the date appropriately. It is an easy access. The fastest way to parse dates. from dateutil.parser import parse df = pd.read_csv('filename.csv', date_parser = parse, index_..) our you can use to_datetime native to Pandas pd.to_datetime(df['Date Col']) In order to format the date properly, you should use the following: date_parser=lambda x: parse(x) #parse from dateutil.parser df['Date Col'] = df['Date Col'].strftime('%m/%d/%Y') df.to_csv('New File.csv')
accepted answer of: http://stackoverflow.com/q/49905403
has comment: http://stackoverflow.com/comment/86828150
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86829368
has comment: http://stackoverflow.com/comment/86828793
has comment: http://stackoverflow.com/comment/86828984
answers question: http://stackoverflow.com/q/49905403

http://stackoverflow.com/a/49891951
upvote count: 1
answers question: http://stackoverflow.com/q/49891820
type: Answer
accepted answer of: http://stackoverflow.com/q/49891820
has body: you probably got a null in one or more rows of that column. fill it with empty string like: df['CONTENT'] = df['CONTENT'].fillna('')
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49908943
has comment: http://stackoverflow.com/comment/86841050
accepted answer of: http://stackoverflow.com/q/49906101
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/86879524
upvote count: 4
has body: There is no built-in function in Python 2.7 to do the equivalent of int.from_bytes in 3.2+; that's why the method was added in the first place. If you don't care about handling any cases other than big-endian signed ints, and care about readability more than performance (so you can extend it or maintain it yourself), the simplest solution is probably an explicit loop over the bytes. For unsigned, this would be easy: n = 0 for by in b: n = n * 256 + by But to handle negative numbers, you need to do three things: Take off the sign bit from the highest byte. Since we only care about big-endian, this is the 0x80 bit on b[0]. That makes an empty bytearray a special case, so handle that specially. At the end, if the sign bit was set, 2's-complement the result. So: def int_from_bytes(b): '''Convert big-endian signed integer bytearray to int int_from_bytes(b) == int.from_bytes(b, 'big', signed=True)''' if not b: # special-case 0 to avoid b[0] raising return 0 n = b[0] &amp; 0x7f # skip sign bit for by in b[1:]: n = n * 256 + by if b[0] &amp; 0x80: # if sign bit is set, 2's complement bits = 8*len(b) offset = 2**(bits-1) return n - offset else: return n (This works on any iterable of ints. In Python 3, that includes both bytes and bytearray; in Python 2, it includes bytearray but not str.) Testing your inputs in Python 3: &gt;&gt;&gt; for b in (bytearray(b'\x8f\x0f\xfd\x02\xf4\x95s\x00\x00'), ... bytearray(b'\x00'), ... bytearray(b'\xef\xbc\xa9\xe5w\xd6\xd0\x00\x00'), ... bytearray(b'\x10CV\x1a\x88)0\x00\x00')): ... print(int.from_bytes(b, 'big', signed=True), int_from_bytes(b)) -2083330000000000000000 -2083330000000000000000 0 0 -300000000000000000000 -300000000000000000000 300000000000000000000 300000000000000000000 And in Python 2: &gt;&gt;&gt; for b in (bytearray(b'\x8f\x0f\xfd\x02\xf4\x95s\x00\x00'), ... bytearray(b'\x00'), ... bytearray(b'\xef\xbc\xa9\xe5w\xd6\xd0\x00\x00'), ... bytearray(b'\x10CV\x1a\x88)0\x00\x00')): ... print int_from_bytes(b) -208333000000000000000…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49906101
downvote count: 0

http://stackoverflow.com/q/49842343
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86700278
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86699406
has comment: http://stackoverflow.com/comment/86699363
has comment: http://stackoverflow.com/comment/86699294
type: Question
has answer: http://stackoverflow.com/a/49842462
has body: My data frame looks like this: ┌────┬──────┬──────┐ │ No │ col1 │ col2 │ ├────┼──────┼──────┤ │ 1 │ A │ 5.0 │ │ 1 │ B1 │ 10.0 │ │ 1 │ B2 │ 20.0 │ │ 2 │ A │ 0.0 │ │ 2 │ B1 │ 0.0 │ │ 2 │ C1 │ 0.0 │ │ 3 │ A │ 0.0 │ │ 3 │ B1 │ 5.0 │ │ 3 │ C1 │ 20.0 │ │ 3 │ C2 │ 30.0 │ └────┴──────┴──────┘ First I used groupby to group the data frame by column No. I would like to do three things now: get a list of values from column No where col2 == 0.0 in all rows of this group (in this case No.2) get a list of No's where col2 != 0.0 for col1 == 'A' but at least one other row of the group has col2 == 0.0 (in this case No.3) get a list of No's where minimum 1 row contains col2 == 0.0 (No.2 and 3) Sorry for asking three issues at once. Hope that is ok. Thank you:)
has title: Python: use apply on groups separatly after grouping dataframe
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49842462
tagged with: pandas-groupby

http://stackoverflow.com/q/49893941
type: Question
has title: Create a python function to run speedtest-cli/ping in terminal and output result to a log file
tagged with: python-3.x
has body: I am learning python and I'm trying to run some terminal command lines using python; eg: speed test and ping. I am using functional programming as my method of programming. However, upon reading more and browsing more with functional programming based from docs.python.org1. I don't think that I am doing it the right way. My question is: Is it good for a function to not have an argument/parameters and just input the command/s directly inside it? And is it really a good option to use os.system or is there a better module to use? Here is the sample of my code. #!/usr/bin/python3 # tasks.py import os def task_speedtest(): os.system("speedtest-cli &gt;&gt; /Desktop/logs") def task_ping(): os.system("ping www.google.com -c5 &gt;&gt; /Desktop/logs") task_speedtest() task_ping()
has comment: http://stackoverflow.com/comment/86804551
has answer: http://stackoverflow.com/a/49894195
possible better answer: http://stackoverflow.com/a/49894195
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49894417
answer count: 2
accepted answer: http://stackoverflow.com/a/49894417
downvote count: 0
has comment: http://stackoverflow.com/comment/86803658
tagged with: os.system
linked to: http://stackoverflow.com/q/2953462
favorite count: 0

http://stackoverflow.com/a/49909017
has comment: http://stackoverflow.com/comment/86833978
has comment: http://stackoverflow.com/comment/86834276
type: Answer
has body: You're reusing variable and parameter names. That is, when you create the for loops, you should be using new variables to loop over so you don't overwrite your parameters, column and tuple. I'd also change tuple to row to be more clear. your loop variables could be named c and r to keep things short. Additionally, you hardcoded 13 as your table size. You should make sure to loop from 1 to the number of columns and 1 to the number of rows. def mathTable(column, row): for r in range(1, row): #r is a temporary variable for the outer loop for c in range(1, column): #c is a temporary variable for the inner loop print("%6d" % (c * r), end = '') #note column and row don't change now, they just act as bounds for the loop print("") now, if you call mathTable(3, 4), you'd get a multiplication table of 1 2 3 4 2 4 6 8 3 6 9 12
answers question: http://stackoverflow.com/q/49908829
score: 0

http://stackoverflow.com/comment/86783475
has text: For a number to be divide by 10, it needs to end in a zero. Therefore you can start at 10 and move up in 10s. This will speed up your code 10x!
type: QuestionComment
comment on: http://stackoverflow.com/q/49883623
score: 0
type: Comment

http://stackoverflow.com/a/49786219
has comment: http://stackoverflow.com/comment/86615941
upvote count: 5
answers question: http://stackoverflow.com/q/49784218
type: Answer
has body: Well, let's start from the beginning. As you probably know, when you generate M2M rels with Django, you use the ManyToManyField. If you do not care about M2M table details, Django will manage it for you. If you want to specify the intermediary table you can use ManyToManyField.through. Exactly as you did. I'm going to semplify your model for explanation purposes. Something like this: class User(models.Model): username = models.CharField(null=True, unique=True, max_length=255) class Feed(models.Model): headline = models.CharField(max_length=255) reader = models.ManyToManyField(User, through='Bookmark') class Bookmark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) feed = models.ForeignKey(Feed, on_delete=models.CASCADE, null=True) Let's start Django interactive shell. I assume you have an empty database. $ django manage.py shell First of all import your models &gt;&gt;&gt; from yourAppName.models import * Now, create some data: &gt;&gt;&gt; from bat.models import * &gt;&gt;&gt; u1 = User(username = 'foo') &gt;&gt;&gt; u1.save() &gt;&gt;&gt; u2 = User(username = 'bar') &gt;&gt;&gt; u2.save() &gt;&gt;&gt; User.objects.all() # get Users u1 and u2 &lt;QuerySet [&lt;User: User object&gt;, &lt;User: User object&gt;]&gt; &gt;&gt;&gt; f1 = Feed(headline = 'How to use M2M in Django') &gt;&gt;&gt; f1.save() &gt;&gt;&gt; Feed.objects.all() # get Feed f1 &lt;QuerySet [&lt;Feed: Feed object&gt;]&gt; How do I add a bookmark (or rather feed) to the user? In this case, you cannot use Feed.reader.add(u1), you have to use the Bookmark's Manager since you specified that's your intermediary model. &gt;&gt;&gt; b1 = Bookmark(user=u1, feed = f1) # add Feed f1 to User u1 &gt;&gt;&gt; b1.save() # save into database We can also add another bookmark: &gt;&gt;&gt; f2 = Feed(headline = 'Fetching data in Django like a pro!') &gt;&gt;&gt; f2.save() &gt;&gt;&gt; b2 = Bookmark(user=u1, feed = f2) # add Feed f2 to User u1 &gt;&gt;&gt; b2.save() # save into database…
score: 5
downvote count: 0

http://stackoverflow.com/comment/119429701
type: AnswerComment
has text: Links dead. FYI it's __scrape__ (and __scraping__, __scraped__, __scraper__) not scrap. 'To scrap' means throw things away like rubbish :-(
comment on: http://stackoverflow.com/a/58524794
type: Comment
score: 0

http://stackoverflow.com/q/49779402
favorite count: 0
type: AnsweredQuestion
has title: How to do Thread Safe Dictionary Manipulation
tagged with: thread-safety
score: 1
has body: how to manipulate dict with thread-safe, i want to store dict to 2 different queue with different dict value (1 before manipulation, 1 after manipulation) but turns out both of them store dict after manipulation. here's my code from threading import Timer, Lock from queue import Queue q = Queue(maxsize=10000) k = Queue(maxsize=10000) k_lock = Lock() q_lock = Lock() def write_func(x): rows = [] while not x.empty(): rows.append(x.get()) if len(rows) == 0: return print('A Row is {} and total A row is {}'.format(rows, len(rows))) def write_k(x): rows = [] while not x.empty(): rows.append(x.get()) if len(rows) == 0: return print('B Row is {} and total B row is {}'.format(rows, len(rows))) def write_caller(sec=10): write_func(q) Timer(sec, write_caller, [sec]).start() def k_caller(sec=1): write_k(k) Timer(sec, k_caller, [sec]).start() write_caller() k_caller() while True: val = {"event": "lazada"} k.put(val) q_val = val with Lock(): q_val["dt"] = "2018-04-11" q.put(q_val) if q.qsize() &gt;= 10: write_func(q) the result of code above is like this A Row is [{'event': 'lazada', 'dt': '2018-04-11'}, ...] B Row is [{'event': 'lazada', 'dt': '2018-04-11'}, ...] but i want the B row only contain 'event' without 'dt'. so here's what i want A Row is [{'event': 'lazada', 'dt': '2018-04-11'}, ...] B Row is [{'event': 'lazada'}, ...]
type: Question
tagged with: python-3.x
tagged with: python-multithreading
accepted answer: http://stackoverflow.com/a/49779691
tagged with: multithreading
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49779691

http://stackoverflow.com/comment/86587860
type: QuestionComment
has text: Melissa, I provided a full answer below, tailored to your case. Hope this helps!
comment on: http://stackoverflow.com/q/49784218
type: Comment
score: 0

http://stackoverflow.com/comment/86572533
comment on: http://stackoverflow.com/q/49778297
type: Comment
type: QuestionComment
has text: You are accessing the class. You need to access the instance.
score: 0

http://stackoverflow.com/a/49861956
accepted answer of: http://stackoverflow.com/q/49861900
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49861900
score: 3
upvote count: 3
type: Answer
has body: Seems like there are issues with files.pythonhosted.org https://status.python.org/

http://stackoverflow.com/comment/87234862
has text: I tried using np.linalg.norm(x-y) for Euclidean and np.linalg.norm(x-y,1) for Mangattan, but I am getting NO results when I use those formulas. Not sure why you think that np.linalg.norm(x-y) and np.linalg.norm(x-y, 1) is same as the formula for Euclidean and Manhattan. In Euclidean we are squaring the result, but in the formula np.linalg.norm(x-y) we are not.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49895091

http://stackoverflow.com/q/49882929
upvote count: 2
type: AnsweredQuestion
score: 2
has title: sorting string dataframe by python pandas
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49883070
downvote count: 0
accepted answer: http://stackoverflow.com/a/49882998
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49883042
has answer: http://stackoverflow.com/a/49882998
possible better answer: http://stackoverflow.com/a/49883042
tagged with: dataframe
tagged with: python
tagged with: sorting
has body: I have a column like in the output and want to get in ascending order as starting from General-0 and increasing. I tried the below it doesn't work.How can I get this done? It's dtype shown as object. dt.sort_values('run') output run 717 General-25-20180121-15:27:27-3807 824 General-26-20180121-15:27:28-3812 931 General-27-20180121-15:27:29-3818 1038 General-28-20180121-15:27:30-3823 1145 General-29-20180121-15:27:30-3828 1252 General-30-20180121-15:27:31-3833 1359 General-31-20180121-15:27:31-3838 1466 General-32-20180121-15:27:32-3843 1573 General-33-20180121-15:27:33-3848 1680 General-34-20180121-15:27:33-3855 1787 General-0-20180121-15:27:08-3680 1894 General-1-20180121-15:27:09-3685 2001 General-2-20180121-15:27:10-3690 2108 General-3-20180121-15:27:11-3695 2215 General-4-20180121-15:27:11-3700 2322 General-5-20180121-15:27:12-3706

http://stackoverflow.com/comment/86810729
type: AnswerComment
has text: suppose there are 5 identical files: min17_q1, min17_q2, min17_q3, min17_q4, min18_q1. I want them to be one file, appended one after the other
comment on: http://stackoverflow.com/a/49897594
type: Comment
score: 0

recursion
type: Tag
tags question: http://stackoverflow.com/q/49842165
tags question: http://stackoverflow.com/q/49800747
tags question: http://stackoverflow.com/q/49837419
tags question: http://stackoverflow.com/q/49897107
tags question: http://stackoverflow.com/q/49882807
tags question: http://stackoverflow.com/q/49777249
tags question: http://stackoverflow.com/q/49862319
tags question: http://stackoverflow.com/q/49839547
tags question: http://stackoverflow.com/q/49851776
tags question: http://stackoverflow.com/q/49819842
tag name: recursion
tags question: http://stackoverflow.com/q/49793522
tags question: http://stackoverflow.com/q/49885287
tags question: http://stackoverflow.com/q/49877316
tags question: http://stackoverflow.com/q/49842184
tags question: http://stackoverflow.com/q/49887144
tags question: http://stackoverflow.com/q/49906109
tags question: http://stackoverflow.com/q/49880124

http://stackoverflow.com/a/49795644
type: Answer
has comment: http://stackoverflow.com/comment/86606029
score: 2
has body: This isn't working because { } is a dictionary (a data structure) and your code is trying to use it like a switch statement. Set up your equivalences first: translation = { "DR" :"Detection Rate", "FAR" :"False Alarm Rate", "FNR" :"False N Rate"} There is no need to translate literals that translate to themselves. for line in f.readlines(): ligne = line.split() ligne = [translation.get(ligne[0],ligne[0])] + ligne
downvote count: 0
answers question: http://stackoverflow.com/q/49795389
has comment: http://stackoverflow.com/comment/86605926
upvote count: 2

http://stackoverflow.com/a/49898372
score: 0
has body: As far as I know, those libraries you mentioned all do the same thing (with a few differences between them). You can choose the one which best suits your needs. If you are using DRF, then you don't need an aditional library (axes, ratelimit, etc.) because DRF already has the throttling functionality build in.
type: Answer
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/49897735

http://stackoverflow.com/q/49888276
upvote count: 0
has title: Why is the function from one file returns 'none' value when calling in another file in Flask Python
answer count: 1
downvote count: 3
tagged with: flask
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49888306
type: UnansweredQuestion
score: -3
has body: Good evening, everyone! I have a problem with returning the value while running my programming code below: # -*- coding: utf-8 -*- from flask import Flask, jsonify from aldd import * app = Flask(__name__) names1="" @app.route('/hashtags/'+b'&lt;name&gt;'.decode('utf-8'), methods=['GET']) def hash(name): name1 = "#" + name d=startet(name1) print(d) app.config['JSON_AS_ASCII'] = False return jsonify({'Segmentation hashtags': d}) if __name__ == '__main__': app.run(port=9876) In my file I call another file named "aldd.py" with it's internal function "def startet(nam)", which has one argument inside. However, when calling this function in my current file with the argument "name1", there's no error and all I get is a "None" value as output. Basically, I run the program in Chrome browser and it looks like following: My project structure looks like this: I guess the error might be caused by transferring the argument "name1" of this function to the same function in "aldd.py". But I might be mistaken. Help me, please! Thanks in advance!
tagged with: python
tagged with: function

http://stackoverflow.com/comment/86560256
type: QuestionComment
has text: "I want to initialize the values of the tuple to existing columns of DataFrame." What *precisely* does this mean? Can you show us with *desired output*?
comment on: http://stackoverflow.com/q/49772706
score: 0
type: Comment

http://stackoverflow.com/comment/86627068
score: 0
type: QuestionComment
type: Comment
has text: `take()` returns a value. It doesn't modify the rdd. Try `x = all_coord_iso_rdd.take(4)`. Then `print(type(x))` - you'll see that it's a list (of tuples). Then just convert it to string.
comment on: http://stackoverflow.com/q/49805687

http://stackoverflow.com/q/49767477
has comment: http://stackoverflow.com/comment/86550685
has comment: http://stackoverflow.com/comment/86550594
tagged with: sparse-matrix
score: 0
answer count: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86550950
has title: How can I read in a sparse matrix saved in a CSV file? (Python 3.6.4)
has comment: http://stackoverflow.com/comment/86550206
has comment: http://stackoverflow.com/comment/86550334
has body: Using countvectorizer, I extracted feature vectors from thousands of emails and saved it in a CSV file dictionary = open (r'''C:\Users\User\Desktop\csmp3\stemmedDictionary.txt''',"r") dic = list(set(dictionary.read().splitlines())) cv = CountVectorizer(vocabulary = dic, binary = True) #~PRESENCE FEATURE VECTOR~# #TRAIN pdt = open (r'''C:\Users\User\Desktop\csmp3\presence-dataset-training-stemmed.csv''',"w") matWriter = csv.writer(pdt,delimiter = ',') for i in range (1,2): #45252 processed_email = open(r'''C:\Users\User\Desktop\csmp3\processed\processed'''+str(i)+'''.txt''',"r") presence_array = cv.transform(processed_email) matWriter.writerow(presence_array) processed_email.close() pdt.close() This is part of a Spam Filtering using Naive Bayes project and our data set is rather large. I'm hoping to use this sparse matrix for Bernoulli Naive Bayes' partial fit method. I just can't quite figure out how to load the sparse matrix from the file. I've already tried numpy.loadtxt but it gives me "ValueError: could not convert string to float: " Any help would be appreciated! Thank you!
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86570408
tagged with: python
has comment: http://stackoverflow.com/comment/86551707

http://stackoverflow.com/q/49901679
has comment: http://stackoverflow.com/comment/86818974
score: 2
answer count: 2
upvote count: 2
downvote count: 0
tagged with: twitter
linked to: http://stackoverflow.com/q/35938188
has answer: http://stackoverflow.com/a/55639214
has comment: http://stackoverflow.com/comment/86820458
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/55641177
has title: twitter api retweet exclude
type: UnansweredQuestion
tagged with: python
has body: So i currently trying to mine tweets from Twitter account(s), but i wanted to exclude the retweets so i can get 200 of Tweets only data for my project. Currently I have a working code to mine the data feed, but still have Re-Tweets included. I have founded that to exclude Re-Tweets you need to put -RT in the code but i simply do not know where since i am pretty new to programming. (Currently using Twitter API for Python (Tweepy) with Python 3.6 using Spyder.) import tweepy from tweepy import OAuthHandler import pandas as pd consumer_key = 'consumer_key' consumer_secret = 'consumer_secret' access_token = 'access_token' access_secret = 'access_secret' auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) api = tweepy.API(auth) api = tweepy.API(auth) screen_name='screen_name' tweets = api.user_timeline(screen_name, count=200) save=['']*len(tweets) for i in range(len(tweets)): save[i]=tweets[i].text print(tweets[i].text) data = pd.DataFrame(save) data.to_csv("results.csv") Can anyone help me, preferrably with complete section for the code to remove the Retweets. Thank you very much

non-alphanumeric
tags question: http://stackoverflow.com/q/49764607
type: Tag
tag name: non-alphanumeric

http://stackoverflow.com/q/49787422
upvote count: 6
answer count: 4
has comment: http://stackoverflow.com/comment/86590223
has title: Converting list into Numpy ndarray
tagged with: numpy
has answer: http://stackoverflow.com/a/49787640
has body: I want to convert this list li = [3, 2 , 1 , 4] to the following NumPy ndarray [[3], [2], [1], [4]] I tried with np.asarray() but it is not converting it into an ndarray. Is there any way to mention the axis?
has answer: http://stackoverflow.com/a/49787449
has comment: http://stackoverflow.com/comment/86590256
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/86590390
duplicate of: http://stackoverflow.com/q/49765578
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49765578
has answer: http://stackoverflow.com/a/49787653
has comment: http://stackoverflow.com/comment/103903000
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49787502
tagged with: python

http://stackoverflow.com/comment/86656812
has text: Sidenote: I already tried this (specific for Mac), and tried to adapt it without any success: https://stackoverflow.com/q/26345972/1422096
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49820873
score: 0

http://stackoverflow.com/q/49858041
type: Question
has body: I am dealing with a matrix, sim_mat, which is a tensor of size (?,?,?). I want to use tf.slice on it like this: a=tf.slice(sim_matrix,[0,0,0],tf.stack([tf.shape(sim_matrix[0],tf.shape(sim_matrix)[1],3])) print(a) But this gives me tensor a with size (?,?,?) instead of (?,?,3). Moreover, when I use a for further functions, I got an error message: Input size (depth of inputs) must be accessible via shape inference, but saw value None. Is there a solution to this? Thanks.
type: UnansweredQuestion
tagged with: python
has title: How to use tf.slice on a tensor with unknown size
has answer: http://stackoverflow.com/a/49858281
answer count: 1
downvote count: 0
upvote count: 1
score: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/49910880
type: Question
score: 0
tagged with: layer
type: UnansweredQuestion
answer count: 1
tagged with: keras
tagged with: tensorflow
has body: Hi everyone i want to convert custom layer written with keras to tensorflow. I know how i can write custom layer keras, this is keras site's example: from keras import backend as K from keras.engine.topology import Layer import numpy as np class MyLayer(Layer): def __init__(self, output_dim, **kwargs): self.output_dim = output_dim super(MyLayer, self).__init__(**kwargs) def build(self, input_shape): # Create a trainable weight variable for this layer. self.kernel = self.add_weight(name='kernel', shape=(input_shape[1], self.output_dim), initializer='uniform', trainable=True) super(MyLayer, self).build(input_shape) # Be sure to call this somewhere! def call(self, x): return K.dot(x, self.kernel) def compute_output_shape(self, input_shape): return (input_shape[0], self.output_dim) I want know if should I build my tensorflow custom layer with a class? and also if it is possible with a example.
has answer: http://stackoverflow.com/a/50165166
has title: convert keras.engine.Layer to tensorflow
tagged with: python

scikit-learn
tags question: http://stackoverflow.com/q/49840087
tags question: http://stackoverflow.com/q/49805987
tags question: http://stackoverflow.com/q/49846726
tags question: http://stackoverflow.com/q/49916467
tags question: http://stackoverflow.com/q/49841324
tags question: http://stackoverflow.com/q/49828554
tags question: http://stackoverflow.com/q/49816754
tags question: http://stackoverflow.com/q/49911121
tag name: scikit-learn
tags question: http://stackoverflow.com/q/49844928
tags question: http://stackoverflow.com/q/49847493
tags question: http://stackoverflow.com/q/49762450
tags question: http://stackoverflow.com/q/49852925
tags question: http://stackoverflow.com/q/49843199
tags question: http://stackoverflow.com/q/49890487
tags question: http://stackoverflow.com/q/49817982
tags question: http://stackoverflow.com/q/49856936
tags question: http://stackoverflow.com/q/49909841
tags question: http://stackoverflow.com/q/49829023
tags question: http://stackoverflow.com/q/49837058
type: Tag
tags question: http://stackoverflow.com/q/49813239
tags question: http://stackoverflow.com/q/49839270
tags question: http://stackoverflow.com/q/49913330
tags question: http://stackoverflow.com/q/49776897
tags question: http://stackoverflow.com/q/49777898
tags question: http://stackoverflow.com/q/49854070
tags question: http://stackoverflow.com/q/49787878
tags question: http://stackoverflow.com/q/49801024
tags question: http://stackoverflow.com/q/49889661
tags question: http://stackoverflow.com/q/49906918
tags question: http://stackoverflow.com/q/49862136
tags question: http://stackoverflow.com/q/49838074
tags question: http://stackoverflow.com/q/49869887
tags question: http://stackoverflow.com/q/49840708
tags question: http://stackoverflow.com/q/49862211
tags question: http://stackoverflow.com/q/49850435
tags question: http://stackoverflow.com/q/49811556
tags question: http://stackoverflow.com/q/49859625
tags question: http://stackoverflow.com/q/49782120
tags question: http://stackoverflow.com/q/49789478
tags question: http://stackoverflow.com/q/49907180
tags question: http://stackoverflow.com/q/49785904
tags question: http://stackoverflow.com/q/49868348
tags question: http://stackoverflow.com/q/49854899
tags question: http://stackoverflow.com/q/49822699
tags question: http://stackoverflow.com/q/49838863
tags question: http://stackoverflow.com/q/49824788
tags question: http://stackoverflow.com/q/49910393
tags question: http://stackoverflow.com/q/49832981
tags question: http://stackoverflow.com/q/49770596
tags question: http://stackoverflow.com/q/49899973
tags question: http://stackoverflow.com/q/49849304
tags question: http://stackoverflow.com/q/49843361
tags question: http://stackoverflow.com/q/49866551
tags question: http://stackoverflow.com/q/49770851
tags question: http://stackoverflow.com/q/49805945
tags question: http://stackoverflow.com/q/49824027
tags question: http://stackoverflow.com/q/49843335
tags question: http://stackoverflow.com/q/49839298
tags question: http://stackoverflow.com/q/49891820
tags question: http://stackoverflow.com/q/49815346
tags question: http://stackoverflow.com/q/49899298
tags question: http://stackoverflow.com/q/49872386
tags question: http://stackoverflow.com/q/49800045
tags question: http://stackoverflow.com/q/49832658
tags question: http://stackoverflow.com/q/49890470
tags question: http://stackoverflow.com/q/49798269
tags question: http://stackoverflow.com/q/49803562
tags question: http://stackoverflow.com/q/49860969
tags question: http://stackoverflow.com/q/49894411
tags question: http://stackoverflow.com/q/49881024
tags question: http://stackoverflow.com/q/49808914
tags question: http://stackoverflow.com/q/49800026
tags question: http://stackoverflow.com/q/49852494
tags question: http://stackoverflow.com/q/49885007
tags question: http://stackoverflow.com/q/49826404
tags question: http://stackoverflow.com/q/49777743
tags question: http://stackoverflow.com/q/49869501
tags question: http://stackoverflow.com/q/49879428

http://stackoverflow.com/q/49858346
score: 6
has answer: http://stackoverflow.com/a/50113884
has comment: http://stackoverflow.com/comment/87221457
upvote count: 7
downvote count: 1
has title: How te retrieve stream statistics in Gstreamer?
favorite count: 0
type: Question
tagged with: video-streaming
accepted answer: http://stackoverflow.com/a/50113884
tagged with: python
has body: First of all I would like to start by saying that I'm really new to Gstreamer and its capabilities so pardon my ignorance if my understanding or implementation was wrong, I am still learning . I would like to build a small streaming application in PYTHON or JAVA (as I am not proficient in C) with QOS integrated in it, especially for the package drop count statistics, and RTP and RTCP seem the perfect match. For this purpose I implemented a SERVER #! /usr/bin/env python import gi import sys gi.require_version('Gst', '1.0') from gi.repository import GObject, Gst #gst-launch -v rtpbin name=rtpbin audiotestsrc ! audioconvert ! alawenc ! rtppcmapay ! rtpbin.send_rtp_sink_0 \ # rtpbin.send_rtp_src_0 ! udpsink port=10000 host=xxx.xxx.xxx.xxx \ # rtpbin.send_rtcp_src_0 ! udpsink port=10001 host=xxx.xxx.xxx.xxx sync=false async=false \ # udpsrc port=10002 ! rtpbin.recv_rtcp_sink_0 DEST_HOST = '127.0.0.1' AUDIO_SRC = 'audiotestsrc' AUDIO_ENC = 'alawenc' AUDIO_PAY = 'rtppcmapay' RTP_SEND_PORT = 5002 RTCP_SEND_PORT = 5003 RTCP_RECV_PORT = 5007 GObject.threads_init() Gst.init(sys.argv) # the pipeline to hold everything pipeline = Gst.Pipeline.new('rtp_server') # the pipeline to hold everything audiosrc = Gst.ElementFactory.make(AUDIO_SRC, 'audiosrc') audioconv = Gst.ElementFactory.make('audioconvert', 'audioconv') audiores = Gst.ElementFactory.make('audioresample', 'audiores') # the pipeline to hold everything audioenc = Gst.ElementFactory.make(AUDIO_ENC, 'audioenc') audiopay = Gst.ElementFactory.make(AUDIO_PAY, 'audiopay') # add capture and payloading to the pipeline and link pipeline.add(audiosrc) pipeline.add(audioconv) pipeline.add(audiores) pipeline.add(audioenc) pipeline.add(audiopay) audiosrc.link(audioconv) audioconv.link(audiores) audiores.link(audioenc) audioenc.link(audiopay) # the rtpbin element rtpbin = Gst.ElementFactory.make('rtpbin', 'rtpbin') pipeline.add(rtpbin) # the udp sinks and source we will use for RTP and RTCP rtpsink = Gst.ElementFactory.make('udpsink',…
tagged with: gstreamer
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87164310
tagged with: qos
answer count: 1

http://stackoverflow.com/comment/86726234
comment on: http://stackoverflow.com/a/49855827
type: Comment
type: AnswerComment
score: 1
has text: id is the memory position of a variable, right ? How two variables have the different values on the same memory position?

http://stackoverflow.com/comment/86789169
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49886416
type: Comment
has text: @gongzhitaao Just tried that, it didn't work. I get the same error `TypeError: Expected int32, got <tf.Variable 'lstm_5_W_i:0' shape=(100, 3) dtype=float32_ref> of type 'Variable' instead.`

http://stackoverflow.com/comment/86618718
type: QuestionComment
comment on: http://stackoverflow.com/q/49796041
score: 0
has text: Is it a bug or the intended behaviour ?
type: Comment

http://stackoverflow.com/comment/87939537
comment on: http://stackoverflow.com/q/49796024
has text: @Mike-SMT `import clr as my_clr` doesn't solve the issue
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86619754
type: Comment
type: AnswerComment
score: 0
has text: @shmee: Oh, huh. `id_object` just seemed weird enough compared to `object_id` that I thought `object_id` was the new one. Edited.
comment on: http://stackoverflow.com/a/49802489

tensor
tags question: http://stackoverflow.com/q/49781866
tags question: http://stackoverflow.com/q/49817131
tag name: tensor
tags question: http://stackoverflow.com/q/49856793
type: Tag
tags question: http://stackoverflow.com/q/49848078

http://stackoverflow.com/comment/86617152
type: Comment
comment on: http://stackoverflow.com/a/49801064
type: AnswerComment
has text: 'Trying' something is not answer.
score: 1

http://stackoverflow.com/q/49859322
score: 1
has title: Python - Get string after and before a Character
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49859447
tagged with: python
has answer: http://stackoverflow.com/a/49859367
has body: I've this strings: "I have been working - 8h by day" "Like - 9H by Month" I'm trying to get the number of Hours. Basically I'm trying to get this output: 8 9 I try this but without success: print(myString.split("H",1)[1] ) But I'm getting this: builtins.IndexError: list index out of range How can I get the string after "-" and before "H" in Python? Thanks!
tagged with: substring
answer count: 4
has answer: http://stackoverflow.com/a/49859402
tagged with: charindex
has answer: http://stackoverflow.com/a/49859363

parsing
tags question: http://stackoverflow.com/q/49888300
tags question: http://stackoverflow.com/q/49860301
tags question: http://stackoverflow.com/q/49893777
tags question: http://stackoverflow.com/q/49770126
tags question: http://stackoverflow.com/q/49886746
tags question: http://stackoverflow.com/q/49771089
tags question: http://stackoverflow.com/q/49807373
tags question: http://stackoverflow.com/q/49818428
tags question: http://stackoverflow.com/q/49787964
tags question: http://stackoverflow.com/q/49766216
tag name: parsing
tags question: http://stackoverflow.com/q/49773059
tags question: http://stackoverflow.com/q/49907219
tags question: http://stackoverflow.com/q/49781559
tags question: http://stackoverflow.com/q/49887782
tags question: http://stackoverflow.com/q/49783799
tags question: http://stackoverflow.com/q/49771433
tags question: http://stackoverflow.com/q/49780473
type: Tag

http://stackoverflow.com/q/49763061
type: Question
has title: Selecting specific rows from an array when a condition is met in python
has answer: http://stackoverflow.com/a/49763226
tagged with: python
possible better answer: http://stackoverflow.com/a/49763177
tagged with: numpy
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49763177
has body: I have a numpy array of IoU values with 300 rows and 4 columns. A row is selected if every element in that row is less than 0.5. I wrote a code which try to do this but it returns rows in which every element is zero. import numpy as np iou = np.random.rand(300,4) negative_boxes = [] for x in range(len(iou)): if iou[x,:].any() &lt; 0.5: negative_boxes.append(iou[x]) How to select rows in which every element is less than 0.5?
accepted answer: http://stackoverflow.com/a/49763226

http://stackoverflow.com/comment/86767889
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49875875
type: Comment
has text: @HadeerEl-Zayat That is just a warning (not error), irrelevant to your question. It is probably due to the small no. of epochs (see [here](https://github.com/keras-team/keras/issues/5008)), and it should appear with your own code, too, for `epochs=5`. Setting `epochs=200` may clear it...

http://stackoverflow.com/a/49901874
upvote count: 1
score: 1
has body: I haven't fully tested this, but I think this will work: (add-hook 'python-mode-hook (lambda () (setq-local python-shell-buffer-name (format "Python %s" (buffer-file-name))))) This should cause every buffer to use a different buffer name when launching a python shell. Each python shell buffer with a different name should have its own inferior python process.
has comment: http://stackoverflow.com/comment/86831338
downvote count: 0
has comment: http://stackoverflow.com/comment/86830220
type: Answer
answers question: http://stackoverflow.com/q/49886186
has comment: http://stackoverflow.com/comment/86891508

http://stackoverflow.com/q/49895472
has comment: http://stackoverflow.com/comment/86806890
has title: How to return a 403 in a ViewSet instead of 404
has answer: http://stackoverflow.com/a/49895988
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86807447
upvote count: 3
has comment: http://stackoverflow.com/comment/86807137
has comment: http://stackoverflow.com/comment/86806705
has body: I'm working on an API and have this ViewSet: class ProjectViewSet(viewsets.ModelViewSet): # API endpoint that allows projects to be viewed or edited. queryset = Project.objects.all() serializer_class = ProjectSerializer authentication_classes = used_authentication_classes permission_classes = (IsOwner,) @detail_route(methods=['get']) def functions(self, request, pk=None): project = self.get_object() if project is None: return Response({'detail': 'Missing project id'}, status=404) return Response([FunctionSerializer(x).data for x in Function.objects.filter(project=project)]) A permission system is attached to this API. The permissions work fine for a single resource. But when I call api/projects which should return all of the projects the user has access to, it does in fact return all of the projects, regardless whether the user should be able to GET a certain project in the list or not. So I overwrote the get_queryset method to only return the projects the user has access to: def get_queryset(self): if self.request.user.is_superuser or self.request.user.is_staff: return Project.objects.all() else: return Project.objects.filter(user=self.request.user.user) This works, but now the API returns a 404 instead of a 403 when I ask for a specific resource I don't have access to. I understand why, because the PK from the resource I try to get is undefined since I only return projects the user has access to. What I don't understand is how to fix this. Does anyone know how I can make it return a 403, or maybe an idea towards where I should look?
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86806652
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/86806751
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/49895988

http://stackoverflow.com/q/49852108
has title: I am not able to save the form data to databse in django
type: Question
tagged with: view
has comment: http://stackoverflow.com/comment/86719420
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/49854384
has comment: http://stackoverflow.com/comment/86719464
has answer: http://stackoverflow.com/a/49852194
has answer: http://stackoverflow.com/a/49852582
score: 0
has answer: http://stackoverflow.com/a/49852541
has comment: http://stackoverflow.com/comment/86718978
has body: I want to add data through form and see it queried in my template blog url: urlpatterns = [ url(r'^admin/',admin.site.urls), url(r'^blog/',include('content.urls',)), ] content url: urlpatterns = [ url(r'^add/$', views.add_content, name='content'), ] models.py from django.db import models class AddContent(models.Model): content_name = models.CharField(max_length=100, default='', blank=False, unique=True) def __str__(self): return self.content_name forms.py from django import forms from .models import AddContent class AddContentForm(forms.ModelForm): class Meta: model = AddContentModel fields = [ "content_name", ] views.py def add_content(request): form = AddContentForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() return redirect("/blog/content/") content_data = AddContent.objects.all() context = { "form":form, "content":content_data, } return render(request, "add_content.html", context) def view_content(request): view_data = AddContent.objects.all() context = { "show_content":view_data, } return render(request, 'show_content.html', context) templates: add_content.html {% extends 'base.html' %} {% block content %} {% csrf_token %} {{ form.as_p }} Recent content {% for show in show_content %} {{ show.content_name }} {% endfor %} {% endblock %} The form data is not being saved, when I add it through admin interface it gives the result but form fails. (this is just some useless content that I am writing in the bracket, stackoverflow didn't allow me posting as it looks like my post is mostly code; please add more details it said but i think the code has lot of details and i cant write anything just for the sake of length)
has comment: http://stackoverflow.com/comment/86719400
tagged with: models
has comment: http://stackoverflow.com/comment/86718953
tagged with: python
tagged with: forms
has comment: http://stackoverflow.com/comment/86718876
answer count: 4

http://stackoverflow.com/q/49810653
upvote count: 2
answer count: 0
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has body: I have a decoder function which contains a subfunction that runs an iterative summation across an input 2D Tensor and an 2xn shaped variable. This summation function works properly during training, however the variables that are used in the function - the 2xn shaped variable and a possible bias term - are not being saved in any of the model checkpoints. Thus, when I load a model for decoding, the function fails as the variables are not in the checkpoint. I tried moving the function out and using it as a normal function, and still didn't see the variables in the checkpoint. I suspect it could be a problem with the default save scope in saver.save()
type: UnansweredQuestion
tagged with: seq2seq
tagged with: python
has title: Subfunction variables not saving in tensorflow
has comment: http://stackoverflow.com/comment/86668787
score: 2

http://stackoverflow.com/comment/86700318
comment on: http://stackoverflow.com/a/49842389
type: Comment
has text: It doesn't refresh. I changed the Name of the item, so it can't find it, and it comes up with this. Message: no such element: Unable to locate element: {"method":"xpath","selector":"//div[contains(./h1/a/text(), "MLKS") and contains(./p/a/text(), "White")]/a"}
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86586669
type: Comment
type: QuestionComment
score: 0
has text: So, I have an html snippet web-scrapped from a site. And I need to extract the date from the string which is in this format. I tried re.search but the pattern returns none. print(re.search(r'^[1-3]*[1-9]*\b[a-zA-Z]*\b[1-9]{4}',str_mydivs)"
comment on: http://stackoverflow.com/q/49785391

http://stackoverflow.com/comment/86613799
has text: ForeignKey is used to relate one model to another. Not fields. Show us more. Not sure what you are trying to do as @Impulse says
score: 0
comment on: http://stackoverflow.com/q/49799351
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86788568
has text: KRKirov, thanks for the examples! I determined the data coming from the Google Sheet API was formatting the numbers as strings. I was able to use the valueRenderOption to put out unformatted numbers and now just have to convert the dates from strings to datetime format.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49848141
type: Comment

http://stackoverflow.com/q/49763203
tagged with: matplotlib
tagged with: python
type: Question
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86573950
has comment: http://stackoverflow.com/comment/86543710
type: UnansweredQuestion
has body: I have a problem with matplotlib.pyplot.bar, I allready searched for the error but none of the reccomended solutions have worked for me. I am trying to code a programm (as a homework assignement), that will let me count the number of occurences of each letter in a newspaper article and plot their relative frequency(relative to the number of all letters used) for two years side by side, which works fine up until I try to plot it. Then I get this error: ValueError: incompatible sizes: argument 'height' must be length 26 or scalar the function that is throwing the error is: def tazBarPlots(relFreq2015, relFreq2018): N = len(relFreq2015) ind = np.arange(N) width=0.1 relFreq5=np.asarray(relFreq2015) relFreq8=np.asarray(relFreq2018) print len(relFreq5), len(relFreq8) p = plt.subplot() rects2015 = p.bar(ind, width, relFreq5, color='red') rects2018 = p.bar(ind + width, width, relFreq8, color='blue') plt.show() relFreq2015 and relFreq2018 are both lists of float numbers with length 26, which contain the relative frequencies of every letter of the alphabet as an average over 20 articles (2015) and 19 (2018). Anyone got any idea what I am doing wrong?
has title: ValueError with matplotlib.pyplot.bar

http://stackoverflow.com/a/49758753
type: Answer
has body: A simple thing you can do is, thinking in terms of intervals, take the average of each function for each interval and multiply if by the interval length, then divide by the total time: import numpy as np matrix = ... data = np.asarray(matrix) t_diff = np.diff(data[:, 0]) means_sum = np.sum(t_diff[:, np.newaxis] * (data[:-1, 1:] + data[1:, 1:]) / 2, axis=0) means = means_sum / (data[-1, 0] - data[0, 0])
downvote count: 0
has comment: http://stackoverflow.com/comment/86532707
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49758371
answers question: http://stackoverflow.com/q/49758371
score: 1

http://stackoverflow.com/q/49835798
has comment: http://stackoverflow.com/comment/86687049
type: Question
has body: I'm working on a Django Project that has two apps, home and contact. I would like to send the context dictionary from the contact view to the contact_form.html template, which is included in the home.html template. I can't figure out the way to pass the values to the contact_form.html template because there's not a url for the contact\views.py. home\urls.py: from django.urls import path from . import views app_name = 'home' urlpatterns = [ path('', views.home, name='home'), ] home\views.py: from django.shortcuts import render def home(request): return render(request, "home/home.html", {}) templates\home\home.html: {% extends "base.html" %} {% block content %} Home template {% include 'contact/contact_form.html' %} {% endblock %} contact\views.py: def contact_view(request): context = {'hello_contact': 'hello from contact view'} return render(request, 'contact/contact_form.html', context) templates\contact\contact_form.html: Contact Template {{ hello_contact }} Thanks for your help :)
has comment: http://stackoverflow.com/comment/86687566
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49835853
has comment: http://stackoverflow.com/comment/86686756
has title: Django 2.0: Send data from a view to a template that is included in another template (2 different Apps)
score: 0
tagged with: django-templates
tagged with: view
answer count: 1
has comment: http://stackoverflow.com/comment/86686902

http://stackoverflow.com/q/49838439
has comment: http://stackoverflow.com/comment/86712308
favorite count: 0
type: Question
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: airflow
downvote count: 0
has comment: http://stackoverflow.com/comment/86712317
has comment: http://stackoverflow.com/comment/87298350
tagged with: celery
has body: I recently added a new machine to my Airflow celery cluster (one that is listening on a separate queue). Everything seemed to be running fine BUT the new worker keeps picking up the same couple of (completed) tasks over and over again. This is invisible from the airflow web interface, which just shows the old tasks as complete and no new tasks being picked up by the worker. Checking the old task logs gives me messages like the following: [2018-04-15 04:13:15,374] {base_task_runner.py:95} INFO - Subtask: [2018-04-15 04:13:15,373] {models.py:1120} INFO - Dependencies not met for &lt;TaskInstance: my_task 2018-04-13 03:05:00 [success]&gt;, dependency 'Task Instance State' FAILED: Task is in the 'success' state which is not a valid state for execution. The task must be cleared in order to be run. over and over again I've checked the metadata database and the tasks do show up as 'done'. I've tried restarting Celery, the scheduler, the worker and the servers themselves to no avail. Both the worker and the scheduler are running on UTC timezone as intended. setup info: EC2 cluster on AWS MySQL Celery backend Airflow 1.8.0 Has anyone ever run into anything like this?
has title: Airflow celery worker keeps trying to run completed tasks
tagged with: python
has comment: http://stackoverflow.com/comment/86692217

http://stackoverflow.com/q/49786276
tagged with: http://stackoverflow.com/tag/pdf
tagged with: selenium
has comment: http://stackoverflow.com/comment/86588532
has title: Download PDF with chrome plugin in python selenium
type: Question
type: UnansweredQuestion
has body: I'm trying to extract a PDF from this site that uses the native Google Chrome pdf viewer tool to open the pdf in the first place, it's content type is /application/pdf. The issue is that the site URLs that I get aren't actually links to the PDF but rather to a .zul site where the js will load the pdf, or fetch it. Here's my download code below: def download_pdf(url, idx, save_dir): options = webdriver.ChromeOptions() profile = {"plugins.plugins_list": [{"enabled":False,"name":"Chrome PDF Viewer"}], "download.default_directory" : save_dir} options.add_experimental_option("prefs",profile) driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver", chrome_options=options) driver.get(url) The problem that Im encountering with the above code is that I get the following readout from driver.source_page: Document Viewer Sorry, JavaScript must be enabled. Change your browser options, then try again. EDIT: Included the link
tagged with: python
has comment: http://stackoverflow.com/comment/86588488
score: 0
answer count: 0

drop-down-menu
tags question: http://stackoverflow.com/q/49868003
tags question: http://stackoverflow.com/q/49803705
tag name: drop-down-menu
type: Tag

http://stackoverflow.com/q/49770019
has comment: http://stackoverflow.com/comment/86555601
tagged with: pandas
has body: I'm attempting to plot a time series date against a float value on a scatter plot using Pandas, however I get the odd error 'Length mismatch: Expected axis has 3 elements, new values have 2 elements' when attempting to plot the data. Here is the Python code I am using get_ipython().magic('matplotlib inline') import matplotlib.pyplot as plt import seaborn; seaborn.set() import pandas as pandas base_rate_over_time = pandas.read_csv("/Users/clarkj84/Desktop/boe-all-time-base-rate.csv") base_rate_over_time = base_rate_over_time.drop(['SERIES'], axis=1) base_rate_dates_as_series = pandas.Series(base_rate_over_time['DATE']) base_rate_over_time['DATE'] = pandas.to_datetime(base_rate_dates_as_series) base_rate_over_time.plot(0, 0) base_rate_over_time.reset_index(inplace=True) base_rate_over_time.columns = ['DATE','VALUE'] base_rate_over_time.plot(kind = 'scatter', x = 'DATE', y = 'VALUE') plt.show() Here is a snippet of the dataset I am attempting to plot against index DATE VALUE 0 0 1975-01-02 11.50 1 1 1975-01-03 11.50 2 2 1975-01-06 11.50 3 3 1975-01-07 11.50 4 4 1975-01-08 11.50 5 5 1975-01-09 11.50 6 6 1975-01-10 11.50 7 7 1975-01-13 11.50 What is causing the column error here?
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/62707634
favorite count: 0
has title: Pandas/MatplotLib Length mismatch: Expected axis has 3 elements, new values have 2 elements
type: Question
linked to: http://stackoverflow.com/q/27472548
answer count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49770551
upvote count: 1
score: 1

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

http://stackoverflow.com/a/49815423
upvote count: 1
has body: Use map by Series created by drop_duplicates with keep='last' for last values per groups: mapping = df.drop_duplicates('Brand', keep='last').set_index('Brand')['Price'] df['Price'] = df['Brand'].map(mapping) print (df) Brand Price Color Category 0 A 60 Blue Shoes 1 A 60 Red Shoes 2 A 60 Yellow Shoes 3 A 60 Pink Shoes 4 A 60 Purple Shoes 5 B 150 Red Shoes 6 B 150 Green Shoes 7 B 150 Blue Shoes 8 C 20 Yellow Shoes 9 C 20 Green Shoes If need define groups by multiple columns (e.g. Brand and Category) is possible use transform with last: df['Price'] = df.groupby(['Brand', 'Category'])['Price'].transform('last') print (df) Brand Price Color Category 0 A 60 Blue Shoes 1 A 60 Red Shoes 2 A 60 Yellow Shoes 3 A 60 Pink Shoes 4 A 60 Purple Shoes 5 B 150 Red Shoes 6 B 150 Green Shoes 7 B 150 Blue Shoes 8 C 20 Yellow Shoes 9 C 20 Green Shoes
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49815376
answers question: http://stackoverflow.com/q/49815376
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86778210
type: AnswerComment
has text: hey turo that seems to be working great for most of the fields! some of them return `TypeError: must be str, not NoneType`. Have you ever seen that?
comment on: http://stackoverflow.com/a/49866616
type: Comment
score: 0

http://stackoverflow.com/q/49788464
tagged with: union
answer count: 4
possible better answer: http://stackoverflow.com/a/49788531
linked to: http://stackoverflow.com/q/2151517
upvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49788742
score: 0
downvote count: 2
has answer: http://stackoverflow.com/a/49788742
has body: I am trying to find the intersection and union of two lists for an assignment, however, I cannot use sets. From set theory, an intersection between two sets is the elements that are in both sets. A union is all elements in both sets, without repetition. So far I have: setA = [1,2,3,4,5,6,7,8,9] setB = [1,5,0,9] def getUnion(a, b): return a + b def getIntersection(a, b): return My union function is returning duplicates. Is there a way to simply find the union? Also, what is the best approach to find the intersection?
has comment: http://stackoverflow.com/comment/86592077
favorite count: 0
has answer: http://stackoverflow.com/a/49788520
has comment: http://stackoverflow.com/comment/86591902
type: Question
has answer: http://stackoverflow.com/a/49788531
tagged with: intersection
has title: How to find Intersection and Union of a List (without using sets)
tagged with: python
has answer: http://stackoverflow.com/a/49788637

configuration-files
type: Tag
tags question: http://stackoverflow.com/q/49905650
tag name: configuration-files

http://stackoverflow.com/comment/86803034
type: AnswerComment
comment on: http://stackoverflow.com/a/49893238
score: 0
type: Comment
has text: pleasure all mine :)

http://stackoverflow.com/comment/86693951
comment on: http://stackoverflow.com/a/49838811
score: 0
type: AnswerComment
has text: cannot use pip install xlwt, proxy is blocked. That is why I downloaded the wheel file and then tried it by using: pip install <location>.whl
type: Comment

http://stackoverflow.com/a/49802767
answers question: http://stackoverflow.com/q/49802727
upvote count: 3
score: 3
downvote count: 0
has body: You can use value_counts(): In [120]: df[df.days_old &gt; 3]['fruit'].value_counts() Out[120]: apple 2 orange 1 Name: fruit, dtype: int64
type: Answer

http://stackoverflow.com/comment/86847976
comment on: http://stackoverflow.com/q/49916252
type: Comment
type: QuestionComment
score: 0
has text: Do you have any information about the error?

http://stackoverflow.com/a/50164643
upvote count: 1
has comment: http://stackoverflow.com/comment/87375902
has comment: http://stackoverflow.com/comment/87375291
has comment: http://stackoverflow.com/comment/90046997
type: Answer
has comment: http://stackoverflow.com/comment/87349534
has body: How can I know which part of my code is triggering this warning? Start with the parts of your code that invoke a GUI. Given that the OP appears to be a scientist, I'll take a wild guess that matplotlib is involved. I can reproduce the message with import matplotlib.pyplot as plt plt.plot([1, 2]) using the following package versions (from conda list): matplotlib 2.2.2 py36h0e671d2_1 defaults pyqt 5.9.2 py36h751905a_0 defaults qt 5.9.4 h4e5bff0_0 defaults
accepted answer of: http://stackoverflow.com/q/49799080
has comment: http://stackoverflow.com/comment/93391505
answers question: http://stackoverflow.com/q/49799080
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49854807
answer count: 1
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/49854836
has answer: http://stackoverflow.com/a/49854836
type: AnsweredQuestion
has title: TypeError: expected string or bytes-like object when using httplib2 with link
tagged with: python
type: Question
has body: I am unsure about this error I am getting. Traceback (most recent call last): File "C:\Users\MICHAEL\Desktop\Project X\dataprod.py", line 30, in status, response = http.request(quote_page) File "C:\Program Files (x86)\Python36-32\lib\site-packages\httplib2__init__.py", line 1368, in request (scheme, authority, request_uri, defrag_uri) = urlnorm(uri) File "C:\Program Files (x86)\Python36-32\lib\site-packages\httplib2__init__.py", line 175, in urlnorm (scheme, authority, path, query, fragment) = parse_uri(uri) File "C:\Program Files (x86)\Python36-32\lib\site-packages\httplib2__init__.py", line 171, in parse_uri groups = URI.match(uri).group TypeError: expected string or bytes-like object My code is below, could this be a permissions error? I am still new to coding and my apologies with this is a rookie error and for my appalling code. Basically trying to find links with in the page I am scraping. import shelve f = open("data.txt", 'w') print("...") from urllib.request import urlopen from urllib.request import urlopen from bs4 import BeautifulSoup, SoupStrainer import httplib2 quote_page = ['https://www.auspost.com'] #ERROR BELOW http = httplib2.Http() status, response = http.request(quote_page) for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')): if link.has_attr('href'): print(link['href']) info = [] for pg in quote_page: page = urlopen(pg) soup = BeautifulSoup(page, 'html.parser') name_box = soup.find('html') name = name_box.text.strip() info.append((name)) print("PULLED DATA") import csv from datetime import datetime with open("index.csv", 'a', encoding='utf-8') as csv_file: writer = csv.writer(csv_file) for name in info: writer.writerow([name]) f.write(name) print(f, name) Exit=input("Press '1' to save and close: ") if Exit == 1: f.close() exit()
score: 0

http://stackoverflow.com/comment/86775003
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49879471
has text: @IMCoins I want to visit a website using python requests, wait until that page updates and then print that it has changed. So I would use a while loop with my code above to keep checking every 5 seconds to see if the status is "exits". The reason I want to check HTML every 5 seconds is because I know that the initial page doesn't have that HTML, but the second one does. I can't just check for changes in the URL since it remains the same.

http://stackoverflow.com/q/49817353
downvote count: 0
has title: Method overloading of dynamically created Enum
favorite count: 0
tagged with: overloading
has answer: http://stackoverflow.com/a/49819063
tagged with: enums
type: Question
score: 3
has comment: http://stackoverflow.com/comment/86649239
accepted answer: http://stackoverflow.com/a/49817838
tagged with: python
has answer: http://stackoverflow.com/a/49817838
possible better answer: http://stackoverflow.com/a/49819063
tagged with: python-3.x
type: AnsweredQuestion
upvote count: 3
has body: The goal is to overload the __str__(self) method of an Enum with dynamically created attributes. A dynamic enum may be created with [1]: from enum import Enum, auto A = Enum('A', dict(('a_'+some_input, auto()) for some_input in ['1','2','3']), module=__name__) Method overloading may be done with [2]: class A(Enum): a_no_input = auto() def __str__(self): return str(self.name) Separatly, both examples work as needed. To combine both I tried: [1]: ... A.__class__.__str__ = lambda self: str(self.name) But this doesn't alter the output of print(A.a_1). and class A(Enum): def __init__(self): super('A', dict(('a_' + some_input, auto()) for some_input in ['1', '2', '3']), module=__name__) def __str__(self): return str(self.name) But this doesn't create static attributes that can be accessed via A.a_1. How do I dynamically create static attributes of an enum and overload the methods of the super class Enum?
answer count: 2

http://stackoverflow.com/comment/86544688
score: 0
has text: Is your problem that you almost always need to copy but occasionally don't, that you almost never need to copy but occasionally do, or that you always need to copy except when calling some specific method of this same class, or is it just sometimes yes and sometimes no haphazardly?
type: Comment
comment on: http://stackoverflow.com/q/49764481
type: QuestionComment

http://stackoverflow.com/comment/86616322
score: 0
type: Comment
type: AnswerComment
has text: The frame list gives just a relative measure, how long each frame is visible in comparison to the others. The parameter `interval` determines the delay between frames in ms. So if your time list contains a value in seconds, then you can set `interval` to 1000 ms = 1 s. If your time list would be in ms, you set the parameter to 1.
comment on: http://stackoverflow.com/a/49799637

python-3.x
tags question: http://stackoverflow.com/q/49876974
tags question: http://stackoverflow.com/q/49837100
tags question: http://stackoverflow.com/q/49800487
tags question: http://stackoverflow.com/q/49761794
tags question: http://stackoverflow.com/q/49898958
tags question: http://stackoverflow.com/q/49769706
tags question: http://stackoverflow.com/q/49770419
tags question: http://stackoverflow.com/q/49844496
tags question: http://stackoverflow.com/q/49836963
tags question: http://stackoverflow.com/q/49787325
tags question: http://stackoverflow.com/q/49796382
tags question: http://stackoverflow.com/q/49849942
tags question: http://stackoverflow.com/q/49808684
tags question: http://stackoverflow.com/q/49816446
tags question: http://stackoverflow.com/q/49902788
tags question: http://stackoverflow.com/q/49834241
tags question: http://stackoverflow.com/q/49777595
tags question: http://stackoverflow.com/q/49910606
tags question: http://stackoverflow.com/q/49801435
tags question: http://stackoverflow.com/q/49829732
tags question: http://stackoverflow.com/q/49817811
tags question: http://stackoverflow.com/q/49841954
tags question: http://stackoverflow.com/q/49865313
tags question: http://stackoverflow.com/q/49839332
tags question: http://stackoverflow.com/q/49889404
tags question: http://stackoverflow.com/q/49909438
tags question: http://stackoverflow.com/q/49801931
tags question: http://stackoverflow.com/q/49796735
tags question: http://stackoverflow.com/q/49902639
tags question: http://stackoverflow.com/q/49893941
tags question: http://stackoverflow.com/q/49829789
tags question: http://stackoverflow.com/q/49785127
tags question: http://stackoverflow.com/q/49763252
tags question: http://stackoverflow.com/q/49910662
tags question: http://stackoverflow.com/q/49807747
tags question: http://stackoverflow.com/q/49834284
tags question: http://stackoverflow.com/q/49894823
tags question: http://stackoverflow.com/q/49825421
tags question: http://stackoverflow.com/q/49836480
tags question: http://stackoverflow.com/q/49861102
tags question: http://stackoverflow.com/q/49834738
tags question: http://stackoverflow.com/q/49817025
tags question: http://stackoverflow.com/q/49870254
tags question: http://stackoverflow.com/q/49889383
tags question: http://stackoverflow.com/q/49910811
tags question: http://stackoverflow.com/q/49788058
tags question: http://stackoverflow.com/q/49910608
tags question: http://stackoverflow.com/q/49808911
tags question: http://stackoverflow.com/q/49811384
tags question: http://stackoverflow.com/q/49887909
tags question: http://stackoverflow.com/q/49839680
tags question: http://stackoverflow.com/q/49916660
tags question: http://stackoverflow.com/q/49865689
tags question: http://stackoverflow.com/q/49771122
tags question: http://stackoverflow.com/q/49806171
tags question: http://stackoverflow.com/q/49892030
tags question: http://stackoverflow.com/q/49832580
tags question: http://stackoverflow.com/q/49875720
tags question: http://stackoverflow.com/q/49802811
tags question: http://stackoverflow.com/q/49777018
tags question: http://stackoverflow.com/q/49895900
tags question: http://stackoverflow.com/q/49835662
tags question: http://stackoverflow.com/q/49844117
tags question: http://stackoverflow.com/q/49848926
tags question: http://stackoverflow.com/q/49777214
tags question: http://stackoverflow.com/q/49862472
tags question: http://stackoverflow.com/q/49774993
tags question: http://stackoverflow.com/q/49835155
tags question: http://stackoverflow.com/q/49774076
tags question: http://stackoverflow.com/q/49808177
tags question: http://stackoverflow.com/q/49866887
tags question: http://stackoverflow.com/q/49896788
tags question: http://stackoverflow.com/q/49859527
tags question: http://stackoverflow.com/q/49799619
tags question: http://stackoverflow.com/q/49900087
tags question: http://stackoverflow.com/q/49907357
tags question: http://stackoverflow.com/q/49868727
tags question: http://stackoverflow.com/q/49894462
tags question: http://stackoverflow.com/q/49814881
tags question: http://stackoverflow.com/q/49880974

http://stackoverflow.com/q/49878329
has comment: http://stackoverflow.com/comment/87071165
tagged with: python
has title: PyInstaller ImportError: cannot import name 'SelectorEventLoop'
has comment: http://stackoverflow.com/comment/86817842
has comment: http://stackoverflow.com/comment/86774238
has body: Using PyInstaller to generate an .exe on a windows platform, i have an error when runnig the .exe: &gt; (venv) ...&gt;my.exe Traceback (most recent call last): File ".\my.py", &gt; line 6, in &lt;module&gt; File &gt; ".\venv\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", &gt; line 631, in exec_module exec(bytecode, module.__dict__) File &gt; "site-packages\websockets\__init__.py", line 3, in &lt;module&gt; File &gt; ".\venv\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", &gt; line 631, in exec_module exec(bytecode, module.__dict__) File &gt; "site-packages\websockets\client.py", line 6, in &lt;module&gt; File &gt; ".\venv\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", &gt; line 631, in exec_module exec(bytecode, module.__dict__) File &gt; ".\venv\Lib\site-packages\zmq\asyncio\__init__.py", line 18, in &gt; &lt;module&gt; ImportError: cannot import name 'SelectorEventLoop' [3696] &gt; Failed to execute script My I am using python 3.6.4 and pyinstaller 3.3 I just added ayncio 3.4.3 to the project (everything worked find before that) Any idea would be welcomed
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86772932
has comment: http://stackoverflow.com/comment/86773463
score: 2
upvote count: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49916040
linked to: http://stackoverflow.com/q/42180492
has comment: http://stackoverflow.com/comment/86773480
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python-asyncio
accepted answer: http://stackoverflow.com/a/49916040
tagged with: pyinstaller

http://stackoverflow.com/comment/86825312
has text: Consider also adding the code you've done so far with a data sample.
type: QuestionComment
comment on: http://stackoverflow.com/q/49904738
score: 1
type: Comment

http://stackoverflow.com/q/49908972
score: 7
upvote count: 7
tagged with: asynchronous
favorite count: 0
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/552744
tagged with: python
has comment: http://stackoverflow.com/comment/112549012
has title: Generic Python Error "MemoryError"
has body: I have a Python program that runs in several processes, and I periodically get the following error message that I can't resolve...or even really tie down to a specific section of code. Any suggestions on the cause, or a way to trap for this error and continue around it? File "/usr/lib/python3.4/multiprocessing/queues.py", line 242, in _feed obj = ForkingPickler.dumps(obj) File "/usr/lib/python3.4/multiprocessing/reduction.py", line 50, in dumps cls(buf, protocol).dump(obj) MemoryError I am running Python 3.4.2
has comment: http://stackoverflow.com/comment/86833939
downvote count: 0
answer count: 0

http://stackoverflow.com/a/49878938
score: 0
answers question: http://stackoverflow.com/q/49874921
has comment: http://stackoverflow.com/comment/86781216
type: Answer
has body: Yes, you should be able to do that. The editing and saving will just edit the original file and not the currently running code. It will just edit your running file if you have saved the file and re-run the python debugger command. It is not specific to Spyder, but to the ipdb / pdb commands, so it would be the same in other editors like PyCharm.
has comment: http://stackoverflow.com/comment/86776658

http://stackoverflow.com/comment/86682771
score: 0
has text: Looks like a combination of a re-entry flag with a timeout. You set the flag on first entrance and show the image, you don't enter if the flag is set, but you check for the timeout to reset the flag. You can use a closure to keep the local flag and timeout state.
comment on: http://stackoverflow.com/q/49833026
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49881195
type: AnsweredQuestion
score: 0
has body: os.path.isdir() is returning false even when i'm passing a directory path to the function. i'm anexing the code snippet. the code creates a folder called "arquivos" , to test, just create some files / folders inside. import os class Arquivos(): working_path = None arquivos = dict() def __init__(self, pasta = "arquivos" ): directory = os.path.dirname(os.path.abspath(__file__)) directory = os.path.join(directory,pasta) try: if not os.path.exists(directory): os.makedirs(directory) except Exception as e: print(e) self.working_path = directory def atualiza_arquivos(self): """Cria uma lista com os arquivos e pastas do diretório de trabalho""" _lista = os.listdir(self.working_path) result = dict() for arq in _lista: """ bug ,era pra retornar True só quando fossem pastas. """ caminho = os.path.join(self.working_path, arq) result['pasta'] = os.path.isdir(caminho) infos = os.stat(caminho) result['ultima_mod'] = infos[8] result['tam'] = infos[6] self.arquivos[arq] = result if __name__ == "__main__": obj = Arquivos() obj.atualiza_arquivos() print(obj.arquivos)
has answer: http://stackoverflow.com/a/49882230
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/86778442
tagged with: python-os
accepted answer: http://stackoverflow.com/a/49882230
tagged with: python
has title: os.path.isdir() is not working
has comment: http://stackoverflow.com/comment/86778585

http://stackoverflow.com/comment/86831869
score: 0
type: Comment
has text: @Anthony Yes, you can definitely remove the border pixels. In MATLAB, there is a function called `imclearborder` that removes any pixels that are connected to the border. OpenCV does not have this function, but I wrote one myself in a previous answer I provided: https://stackoverflow.com/questions/24731810/segmenting-license-plate-characters. Take note that this can get computationally intensive, because the process is to find all contours in the image, then check to see if any contours are touching any of the border pixels in the image. I then paint the area of these contours to black.
type: AnswerComment
comment on: http://stackoverflow.com/a/49907762

http://stackoverflow.com/q/49778527
possible better answer: http://stackoverflow.com/a/49824929
tagged with: oop
answer count: 3
linked to: http://stackoverflow.com/q/19629682
has answer: http://stackoverflow.com/a/49824929
tagged with: python
tagged with: dictionary
has title: Suppress key addition in collections.defaultdict
has body: When a missing key is queried in a defaultdict object, the key is automatically added to the dictionary: from collections import defaultdict d = defaultdict(int) res = d[5] print(d) # defaultdict(&lt;class 'int'&gt;, {5: 0}) # we want this dictionary to remain empty However, often we want to only add keys when they are assigned explicitly or implicitly: d[8] = 1 # we want this key added d[3] += 1 # we want this key added One use case is simple counting, to avoid the higher overhead of collections.Counter, but this feature may also be desirable generally. Counter example [pardon the pun] This is the functionality I want: from collections import Counter c = Counter() res = c[5] # 0 print(c) # Counter() c[8] = 1 # key added successfully c[3] += 1 # key added successfully But Counter is significantly slower than defaultdict(int). I find the performance hit usually ~2x slower vs defaultdict(int). In addition, obviously Counter is only comparable to int argument in defaultdict, while defaultdict can take list, set, etc. Is there a way to implement the above behaviour efficiently; for instance, by subclassing defaultdict? Benchmarking example %timeit DwD(lst) # 72 ms %timeit dd(lst) # 44 ms %timeit counter_func(lst) # 98 ms %timeit af(lst) # 72 ms Test code: import numpy as np from collections import defaultdict, Counter, UserDict class DefaultDict(defaultdict): def get_and_forget(self, key): _sentinel = object() value = self.get(key, _sentinel) if value is _sentinel: return self.default_factory() return value class DictWithDefaults(dict): __slots__ = ['_factory'] # avoid using extra memory def __init__(self, factory, *args, **kwargs): self._factory = factory super().__init__(*args, **kwargs) def __missing__(self, key): return self._factory() lst = np.random.randint(0, 10, 100000) def DwD(lst): d = DictWithDefaults(int) for i in lst: d[i] += 1 return d def dd(lst): d = defaultdict(int) for i in lst: d[i] += 1 return d def counter_func(lst): d = Counter() for i in lst: d[i]…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86656723
has comment: http://stackoverflow.com/comment/86572649
has answer: http://stackoverflow.com/a/49825074
score: 9
accepted answer: http://stackoverflow.com/a/49778990
has comment: http://stackoverflow.com/comment/86572796
has answer: http://stackoverflow.com/a/49778990
has comment: http://stackoverflow.com/comment/86663826
has comment: http://stackoverflow.com/comment/86656669
tagged with: collections
downvote count: 7
upvote count: 16
has comment: http://stackoverflow.com/comment/86664740
tagged with: defaultdict
type: AnsweredQuestion

http://stackoverflow.com/comment/86887036
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49913140
has text: @user9666493 I am working on it. I will notify you when its ready.

http://stackoverflow.com/q/49869848
type: UnansweredQuestion
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/86754935
answer count: 1
has body: I am trying to use mypy for static type checking in my python project. However, I am seeing the following errors when running mypy, utils.py:15: error: Name 'google' is not defined The annotation is something like this # type: () -&gt; google.protobuf.timestamp_pb2.Timestamp
type: Question
tagged with: mypy
has title: Issues with mypy
has answer: http://stackoverflow.com/a/49990677

http://stackoverflow.com/q/49882682
tagged with: python-2.7
linked to: http://stackoverflow.com/q/3207219
has body: This is my code : import os def get_file(): files = os.listdir('F:/Python/PAMC') print(files) for file in files: print(file) get_file() How do i list only folders in a directory in python?
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49883095
has title: How do i list folder in directory
has answer: http://stackoverflow.com/a/49884022
has comment: http://stackoverflow.com/comment/102419357
has comment: http://stackoverflow.com/comment/87899696
type: Question
linked to: http://stackoverflow.com/q/7781545
has comment: http://stackoverflow.com/comment/86781975
has answer: http://stackoverflow.com/a/49890887
tagged with: python
type: UnansweredQuestion
score: 10
upvote count: 10
favorite count: 0
duplicate of: http://stackoverflow.com/q/7781545
tagged with: python-3.x

http://stackoverflow.com/q/49796019
answer count: 1
has body: I have some trouble understanding the output of the Discrete Cosine Transform. Background: I want to achive a simple audio compression by saving only the most relevant frequencies of a DCT. In order to be somewhat general, I would cut several audio tracks into pieces of a fixed size, say 5 seconds. Then I would do a DCT on each sample and find out which are the most important frequencies among all short snippets. This however does not work, which might be due to my missunderstanding of the DCT. See for example the images below: The first image shows the DCT of the first 40 seconds of an audio track (wanted to make it long enough so that I get a good mix of frequencies). The second image shows the DCT of the first ten seconds. The thrird image shows the DCT of a reverse concatination (like abc->abccba) of the first 40 seconds I added a vertical mark at 2e5 for comparison. Samplerate of the music is the usual 44.1 khz So here are my questions: What is the frequency that corresponds to an individual value of the DCT-output-vector? Is it bin/2? Like if I have a spike at bin=10000, which frequency in the real world does this correspond to? Why does the first plot show strong amplitudes for so many more frquencies than the seond? My intuition was that the DCT would yield values for all frequencies up to 44.l khz (so bin number 88.2k if my assumption in #1 is correct), only that the scale of the spikes would be different, which would then make up the difference in the music. Why does the third plot show strong amplitudes for more frequencies than the first does? I thought that by concatenating the data, I would not get any new frequencies. As DCTand FFT/DFT are very similar, I tried to learn more about ft (this and this helped), but apparently it didn't suffice.
type: AnsweredQuestion
score: 0
tagged with: python
tagged with: dct
tagged with: scipy
has title: Understanding the output of a DCT
type: Question
linked to: http://stackoverflow.com/q/6740545
accepted answer: http://stackoverflow.com/a/49842800
has answer: http://stackoverflow.com/a/49842800

http://stackoverflow.com/comment/86831045
comment on: http://stackoverflow.com/a/49907114
score: 0
type: AnswerComment
has text: added 2 new cases to the OP
type: Comment

http://stackoverflow.com/comment/86585763
comment on: http://stackoverflow.com/q/49784828
has text: You may want to square up your code and results.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49787670
score: 0
has answer: http://stackoverflow.com/a/49787897
tagged with: dynamic-programming
answer count: 1
has body: I'm following this link to write a DP solution for Subset problem. def subsetSum(input, target): row, col = len(input)+1, target+1 db = [[False] * col] * row for i in range(row): db[i][0] = True for i in range(1, row): for j in range(1, col): db[i][j]=db[i-1][j] if db[i][j]==False and j&gt;=input[i-1]: db[i][j] = db[i-1][j-input[i-1]] return db[i][j] target = 5 input = [1,3,9,2] subsetSum(input, target) Interestingly after every iteration of "j", db[i-1] (the previous row where we are referring to the values) is also getting updated. I'm really lost whats happening here. Please suggest. Please find this link for the printed statements.
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49787897
tagged with: python
tagged with: backtracking
has title: Subset Sum in python using DP
type: AnsweredQuestion

http://stackoverflow.com/comment/86848016
score: 0
has text: But data are always available on source but sometimes i must run 2-3 times import script to import them. How to automate this process?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49916125

http://stackoverflow.com/a/49762204
answers question: http://stackoverflow.com/q/49761846
has body: This question has 2 parts: Retrieving the 2 items in a list which equate to the target Retrieving their index value def get_index_for_target(nums, target): for x in nums: for y in nums: if x + y == target: return (nums.index(x), nums.index(y))
type: Answer
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/q/49795791
score: 0
answer count: 0
has title: Loading table and saving as csv from Hive?
has body: I have a huge 440M rows and 30 columns table. I need to save it locally. I have used the SQLAlchemy package to do this but it takes a lot of time. Please advise how can I do it faster? Should I use Dask? Here is my code: import csv import pandas as pd from pyhive import hive from sqlalchemy import * from sqlalchemy.engine import create_engine from sqlalchemy.schema import * from odo import odo ################################################################################ # Using SQLAlchemy: # Creating engine: engine = create_engine('hive://er123.company.test:10000/db') # Connecting to the engine: con = engine.connect() # Read database and builds SQLAlchemy Table Objects: metadata = MetaData() tbl_name = "tbl" Table(tbl_name, metadata, autoload=True, autoload_with=engine) # Create statement: stmt = "SELECT * FROM tbl" # Fetch the data: data = pd.read_sql(stmt, con = con) # To save to a csv: # Using SQL statement: pd.read_sql(stmt, con = con).to_csv('data.csv', index=False)
tagged with: sqlalchemy
type: Question
tagged with: export-to-csv
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86692392
tagged with: database
tagged with: python
has comment: http://stackoverflow.com/comment/86626860
tagged with: hive
has comment: http://stackoverflow.com/comment/86713101

http://stackoverflow.com/a/49937227
score: 0
has body: Here is a subtle difference between printing *v and v. #printing v in the loop for s,v in ss.items(): print("s = {0}, v = {1}".format(s,v)); #printing s &amp; v s = yellow, v = [3,4,7] s = blue, v = [4,9,1] s = red, v = [1,8,2] Then we have #printing *v in the loop for s,v in ss.items(): print("s = {0}, *v = {1}".format(s,*v)); #printing s &amp; *v s = yellow, v = 3 4 7 s = blue, v = 4 9 1 s = red, v = 1 8 2 Note the subtlety here: whether we use *v in the 'for' loop, print v or *v produces the same result: #printing v in the loop for s,*v in ss.items(): print("s = {0}, v = {1}".format(s,v)); #printing s &amp; v #printing v in the loop for s,*v in ss.items(): print("s = {0}, v = {1}".format(s,*v)); #printing s &amp; v Produces the same result: s = yellow, v = [[3,4,7]] s = blue, v = [[4,9,1]] s = red, v = [[1,8,2]] Thank you, Anthony of Sydney
type: Answer
answers question: http://stackoverflow.com/q/49896007

http://stackoverflow.com/a/49867211
downvote count: 0
type: Answer
has body: The key function in your example only sorts by value, as you've noticed. If you also want to sort by key, then you can return the value and key (in that order) as a tuple: &gt;&gt;&gt; sorted(a_dict.items(), key=lambda x: (x[1], x[0])) [('aa2', 'a'), ('ba2', 'a'), ('aa1', 'n')] The confusing part is that your data looks like ('aa2', 'a'), for example, but it is being sorted as ('a', 'aa2') because of (x[1], x[0]).
accepted answer of: http://stackoverflow.com/q/49867180
upvote count: 4
answers question: http://stackoverflow.com/q/49867180
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86750258
score: 4
has comment: http://stackoverflow.com/comment/86750016

http://stackoverflow.com/q/49776618
type: Question
tagged with: graph
accepted answer: http://stackoverflow.com/a/50314496
has answer: http://stackoverflow.com/a/50314496
has body: I'm a noob in tensorflow and I start working on "Getting Started With TensorFlow" tutorial. In this tutorial there is an image of graph. In this image I don't find explanation about range and rank node. I feel that these two nodes are used to find range (0 and N-1) and data rank in sum : Is it right ? When there is such a node in graph is it good to use doc : https://www.tensorflow.org/api_docs/python/tf/range https://www.tensorflow.org/api_docs/python/tf/rank
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has title: Name use in computational graph image (TensorBoard)
score: 1
tagged with: tensorboard
answer count: 1
downvote count: 0
upvote count: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/86651436
has text: Possible duplicate of [have 3.x and 3.y anaconda version on offline mode](https://stackoverflow.com/questions/49777621/have-3-x-and-3-y-anaconda-version-on-offline-mode)
type: Comment
comment on: http://stackoverflow.com/q/49817284
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86674940
comment on: http://stackoverflow.com/a/49829802
type: Comment
type: AnswerComment
has text: Huh, just as I was writing that @JonClements provides a key function! I never considered using tuples. Will bear this in mind, thanks.
score: 0

http://stackoverflow.com/a/55235065
has body: I dont think you are right. Actually timestep number does not impact the number of parameters in LSTM. from keras.layers import LSTM from keras.models import Sequential time_step = 13 featrue = 5 hidenfeatrue = 10 model = Sequential() model.add(LSTM(hidenfeatrue, input_shape=(time_step, featrue))) model.summary() time_step=100 model2 = Sequential() model2.add(LSTM(hidenfeatrue, input_shape=(time_step, featrue))) model2.summary() the reuslt: Using TensorFlow backend. _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= lstm_1 (LSTM) (None, 10) 640 ================================================================= Total params: 640 Trainable params: 640 Non-trainable params: 0 _________________________________________________________________ _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= lstm_2 (LSTM) (None, 10) 640 ================================================================= Total params: 640 Trainable params: 640 Non-trainable params: 0 _________________________________________________________________
type: Answer
answers question: http://stackoverflow.com/q/49892528
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/114916617

numba
tags question: http://stackoverflow.com/q/49842260
tags question: http://stackoverflow.com/q/49784269
tags question: http://stackoverflow.com/q/49865334
tags question: http://stackoverflow.com/q/49900812
tags question: http://stackoverflow.com/q/49872453
tags question: http://stackoverflow.com/q/49824338
type: Tag
tags question: http://stackoverflow.com/q/49826125
tags question: http://stackoverflow.com/q/49907604
tag name: numba
tags question: http://stackoverflow.com/q/49836963

http://stackoverflow.com/comment/86767505
comment on: http://stackoverflow.com/a/49860455
type: Comment
score: 0
type: AnswerComment
has text: Yeah I see that. I am sure you didn't notice what result it produces. There is no difference between the result what my earlier script and your suggested script produces. The result both the script produces `http://www.mount-zion.biz/index.html http://www.latamcham.org/about-us-2/ http://www.innovaprint.com.sg/about.html http://www.cityscape.com.sg/?page_id=27` I EXPECTED TO HAVE THE FOLLOWING: `http://www.mount-zion.biz/contactus.html http://www.latamcham.org/contact-us/ http://www.innovaprint.com.sg/contact.html http://www.cityscape.com.sg/?page_id=37`.

http://stackoverflow.com/comment/86609336
type: AnswerComment
comment on: http://stackoverflow.com/a/49797263
type: Comment
has text: So you would suggest storing a batch of packets by extending a bytearray, then creating a numpy array and changing the array's shape to allow addressing of the packets?
score: 0

http://stackoverflow.com/comment/86685638
type: QuestionComment
has text: Why are you writing raw SQL in Django?
score: 0
comment on: http://stackoverflow.com/q/49835272
type: Comment

http://stackoverflow.com/comment/86781379
type: Comment
comment on: http://stackoverflow.com/q/49882642
type: QuestionComment
has text: i use many loss function in https://keras.io/losses/ with some of them i got wierd loss function, with some of them i got very low accuracy I changed both loss and optimizer but still i got wierd
score: 0

http://stackoverflow.com/q/49873446
has answer: http://stackoverflow.com/a/49875577
accepted answer: http://stackoverflow.com/a/49875577
tagged with: python
score: -1
tagged with: optimization
has title: Scipy minimization with multiple constraints
type: AnsweredQuestion
tagged with: constraints
upvote count: 0
answer count: 1
downvote count: 1
tagged with: scipy
favorite count: 0
type: Question
has body: I want to minimize a functional using the scipy module scipy.optimize and I'm struggling to understand how to implement my constraints. The extremal points of my solution must be exactly zero and one, so right now I'm imposing cons = ({'type': 'eq', 'fun' : lambda x: x[0]}, #the initial point is 0 {'type': 'eq', 'fun' : lambda x: x[-1]-1.}) #the final point is 1 but I also need every other point to be strictly higher than 0 and smaller than 1. How can I explicitly add this further constraint for all the other points of my array?

http://stackoverflow.com/comment/86544968
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49763994
has text: I created the file using Excel, so I'm guessing Excel encodes it in a particular way that I'm blatantly ignorant of. :)
type: Comment

elasticsearch
tags question: http://stackoverflow.com/q/49871124
tags question: http://stackoverflow.com/q/49796254
tags question: http://stackoverflow.com/q/49859528
tags question: http://stackoverflow.com/q/49891686
type: Tag
tags question: http://stackoverflow.com/q/49890878
tags question: http://stackoverflow.com/q/49770559
tag name: elasticsearch
tags question: http://stackoverflow.com/q/49866497
tags question: http://stackoverflow.com/q/49912154
tags question: http://stackoverflow.com/q/49851934
tags question: http://stackoverflow.com/q/49883563

http://stackoverflow.com/a/76365130
downvote count: 0
has body: The other answers here do forget the column names (column index) of a dataframe. The pd.util.hash_pandas_object() create a series of hash values for each row of a dataframe including it's index (the row name). But the name of columns doesn't matter as you can see here: &gt;&gt;&gt; from pandas import * &gt;&gt;&gt; from pandas import util &gt;&gt;&gt; util.hash_pandas_object(DataFrame({'A': [1,2,3], 'B': [4,5,6]})) 0 580038878669277522 1 2529894495349307502 2 4389717532997776129 dtype: uint64 &gt;&gt;&gt; util.hash_pandas_object(DataFrame({'Foo': [1,2,3], 'Bar': [4,5,6]})) 0 580038878669277522 1 2529894495349307502 2 4389717532997776129 dtype: uint64 My solution df = DataFrame({'A': [1,2,3], 'B': [4,5,6]}) hash = pandas.util.hash_pandas_object(df) # append hash of the columns hash = pandas.concat( [hash, pandas.util.hash_pandas_object(df.columns)] ) # hash the series of hashes hash = hashlib.sha1(hash.values).hexdigest() print(hash)
upvote count: 4
answers question: http://stackoverflow.com/q/49883236
type: Answer
score: 4

http://stackoverflow.com/comment/86807027
score: 0
type: QuestionComment
has text: martineau & rayryeng - Thank you for the tip. I posted the question on Codereview. Zeta - Thank you for your opinion. I also agree with you! @Aja - Thank you for the suggestion! Did not think about it this way but you are right. Thanks!
type: Comment
comment on: http://stackoverflow.com/q/49887540

http://stackoverflow.com/comment/86845996
score: 0
comment on: http://stackoverflow.com/q/49914990
type: Comment
type: QuestionComment
has text: Note that opening a file with write access will truncate the file to zero bytes destroying existing data.

http://stackoverflow.com/q/49836676
downvote count: 2
has answer: http://stackoverflow.com/a/57416371
upvote count: 507
has answer: http://stackoverflow.com/a/50062958
has answer: http://stackoverflow.com/a/58938454
has answer: http://stackoverflow.com/a/53700609
has answer: http://stackoverflow.com/a/57015258
has answer: http://stackoverflow.com/a/50205248
has answer: http://stackoverflow.com/a/55699173
score: 505
has answer: http://stackoverflow.com/a/51176952
has answer: http://stackoverflow.com/a/58020436
has answer: http://stackoverflow.com/a/51726471
answer count: 32
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/51457749
has answer: http://stackoverflow.com/a/57114773
has answer: http://stackoverflow.com/a/65169387
linked to: http://stackoverflow.com/q/49964093
has answer: http://stackoverflow.com/a/51499030
has answer: http://stackoverflow.com/a/59449631
has answer: http://stackoverflow.com/a/50675721
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51462434
possible better answer: http://stackoverflow.com/a/51462434
has answer: http://stackoverflow.com/a/52122813
has body: Whenever I am trying to install any package using pip, I am getting this import error: guru@guru-notebook:~$ pip3 install numpy Traceback (most recent call last): File "/usr/bin/pip3", line 9, in &lt;module&gt; from pip import main ImportError: cannot import name 'main' guru@guru-notebook:~$ cat `which pip3` #!/usr/bin/python3 # GENERATED BY DEBIAN import sys # Run the main entry point, similarly to how setuptools does it, but because # we didn't install the actual entry point from setup.py, don't use the # pkg_resources API. from pip import main if __name__ == '__main__': sys.exit(main()) It was working fine earlier, I am not sure why it is throwing this error. I have searched about this error, but can't find anything to fix it. Please let me know if you need any further detail, I will update my question.
has title: Error after upgrading pip: cannot import name 'main'
has answer: http://stackoverflow.com/a/54132673
has comment: http://stackoverflow.com/comment/101006017
has answer: http://stackoverflow.com/a/56162357
has comment: http://stackoverflow.com/comment/91124440
has answer: http://stackoverflow.com/a/50252101
has answer: http://stackoverflow.com/a/53205990
has answer: http://stackoverflow.com/a/51750226
has answer: http://stackoverflow.com/a/50358441
has answer: http://stackoverflow.com/a/50492636
has comment: http://stackoverflow.com/comment/90985836
has answer: http://stackoverflow.com/a/57744496
favorite count: 0
has answer: http://stackoverflow.com/a/62257385
type: Question
has answer: http://stackoverflow.com/a/49836753
has answer: http://stackoverflow.com/a/51846054
has answer: http://stackoverflow.com/a/54012930
has answer: http://stackoverflow.com/a/50010299
accepted answer: http://stackoverflow.com/a/49836753
has answer: http://stackoverflow.com/a/53942524

http://stackoverflow.com/a/49863613
has comment: http://stackoverflow.com/comment/86745678
upvote count: 4
has comment: http://stackoverflow.com/comment/86745408
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86744753
has comment: http://stackoverflow.com/comment/86744304
answers question: http://stackoverflow.com/q/49863401
score: 4
has comment: http://stackoverflow.com/comment/86746466
accepted answer of: http://stackoverflow.com/q/49863401
has comment: http://stackoverflow.com/comment/86745016
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86744632
has body: You should use: df['Duration'] = pd.to_timedelta(df.Hours*3600 + df.Mins*60 + df.Secs, unit='s') When you use apply on a DataFrame with axis=1, it's a row calculation, so typically this syntax makes sense: df['Duration'] = df.apply(lambda row: pd.Timedelta(hours=row.Hours, minutes=row.Mins, seconds=row.Secs), axis=1) Some timings import pandas as pd import numpy as np df = pd.DataFrame({'Hours': np.tile([1,2,3,4],50), 'Mins': np.tile([10,20,30,40],50), 'Secs': np.tile([11,21,31,41],50)}) %timeit pd.to_timedelta(df.Hours*3600 + df.Mins*60 + df.Secs, unit='s') #432 µs ± 5.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit df.apply(lambda row: pd.Timedelta(hours=row.Hours, minutes=row.Mins, seconds=row.Secs), axis=1) #12 ms ± 67.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) As always, apply should be a last resort.

http://stackoverflow.com/comment/86746151
comment on: http://stackoverflow.com/a/49864646
type: Comment
score: 0
type: AnswerComment
has text: Thank you @Peter for that great answer , I have one more doubt so suppose my nodes are 10,000 and i have keep_prob 0.3 now it will kept 3000 neurons right ? now my confusion is this thing happen in each iteration ? if yes then in first iteration it takes randomly 3000 and then in second it will take another randomly 3000 or it takes static 3000 for each iteration ?

http://stackoverflow.com/comment/86594612
comment on: http://stackoverflow.com/q/49789827
score: 0
type: Comment
type: QuestionComment
has text: What if you resize the `QGraphicsPixmapItem` that `scene.addPixmap(self.m)` returns?

http://stackoverflow.com/q/49805041
tagged with: telegram-bot
type: UnansweredQuestion
has body: I have a question about inline-buttons in telegram. So I have a lot of inline-buttons and I want to divide them to several pages. On each page I have forward =&gt; and back &lt;= button to move between pages. Click on each button returns document. After inline keyboard call I placed the handler that processing click on each button. First page buttons works correct except forward and back buttons. Pages don't change. I am using telebot lib. bot = telebot.TeleBot(token) @bot.message_handler(commands=['start','help']) def start(o): bot.send_message(o.chat.id,'Hi,use buttons!') def name(m): keyboard = types.InlineKeyboardMarkup() keyboard.add(*[types.InlineKeyboardButton(text=name,callback_data=name) for name in ['button1','button2']]) keyboard.add(*[types.InlineKeyboardButton(text=name,callback_data=name) for name in ['button3','button4']]) keyboard.add(*[types.InlineKeyboardButton(text=name,callback_data=name) for name in ['=&gt;']]) msg = bot.send_message(m.chat.id,'-----------Choose button----------',reply_markup=keyboard) @bot.callback_query_handler(func=lambda c:True) def inline(c): if c.data == 'button1': bot.send_document(c.message.chat.id,open('button1.pdf', 'rb')) elif c.data == 'button2': bot.send_document(c.message.chat.id,open('button2.pdf', 'rb')) elif c.data == 'button3': bot.send_document(c.message.chat.id,open('button3.pdf', 'rb')) elif c.data == 'button4' : bot.send_document(c.message.chat.id,open('button4.pdf', 'rb')) elif c.data == '=&gt;' : keyboard = types.InlineKeyboardMarkup() keyboard.add(*[types.InlineKeyboardButton(text=name,callback_data=name) for name in ['button5','button6']]) while True: try: bot.polling(none_stop=True) except Exception as e: print(e) time.sleep(15)
tagged with: python
upvote count: 2
has answer: http://stackoverflow.com/a/49816834
score: 1
downvote count: 1
answer count: 1
has title: Several pages of inline-buttons
favorite count: 0
type: Question

http://stackoverflow.com/q/49861144
score: 3
has comment: http://stackoverflow.com/comment/86737677
answer count: 2
linked to: http://stackoverflow.com/q/3247183
tagged with: sql
upvote count: 3
linked to: http://stackoverflow.com/q/19193851
downvote count: 0
duplicate of: http://stackoverflow.com/q/19193851
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49861423
tagged with: database
has comment: http://stackoverflow.com/comment/86737455
has title: SQL SELECT from table name supplied by a variable
tagged with: python
has answer: http://stackoverflow.com/a/49989916
has comment: http://stackoverflow.com/comment/86737761
accepted answer: http://stackoverflow.com/a/49989916
has answer: http://stackoverflow.com/a/49861423
has body: Whenever I try the code below, I get near "?": syntax error I tried multiple things including prepping it into a variable Is this possible in python? Or am I thinking in the wrong direction? import sqlite3 sqlite_file = 'DATABASE.db' conn = sqlite3.connect(sqlite_file) c = conn.cursor() word = () question = int(input("What would you like to see?")) if question == 1: word = ("Batchnumbers") if question == 2: word = ("Worker IDs") c.execute('SELECT * FROM ?', (word)) data = c.fetchall() for x in range(len(data)): print(data[x])
type: AnsweredQuestion

http://stackoverflow.com/a/49897558
answers question: http://stackoverflow.com/q/49895721
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49895721
type: Answer
has body: No, H2O does not require you to convert all numerical values to categorical values. If you want to view how trained H2O DRF models treat the different input columns, follow the instructions below for how to view a MOJO. http://docs.h2o.ai/h2o/latest-stable/h2o-genmodel/javadoc/overview-summary.html#viewing-a-mojo Note in the picture below that numerical columns are treated with a "less than" value comparison, and categorical columns are treated by sending some of the levels to the left child and some to the right child.

http://stackoverflow.com/comment/86622415
has text: What exactly is the error, and what Python version are you using?
comment on: http://stackoverflow.com/q/49803904
type: Comment
type: QuestionComment
score: 6

http://stackoverflow.com/comment/86828828
type: AnswerComment
score: 0
has text: np, glad it helps :)
type: Comment
comment on: http://stackoverflow.com/a/49866869

http://stackoverflow.com/comment/86541358
type: Comment
has text: What I find annoying is downvotes without explanation. :(
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/49762821

http://stackoverflow.com/a/57827295
answers question: http://stackoverflow.com/q/49764125
has body: I have been working with reticulate and R Markdown and you should specify your virtual environment. For example my R Markdown starts as follows: {r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, warning = FALSE, cache.lazy = FALSE) library(reticulate) use_condaenv('pytorch') Then you can work in either language. So, for plotting with matplotlib, I have found that you need the PyQt5 module to make it all run smoothly. The following makes a nice plot inside R Markdown. {python plot} import PyQt5 import numpy as np import pandas as pd import os import matplotlib.pyplot as plt from matplotlib.pyplot import figure data = pd.read_csv('Subscriptions.csv',index_col='Date', parse_dates=True) # make the nice plot # set the figure size fig = plt.figure(figsize = (15,10)) # the series ax1 = fig.add_subplot(211) ax1.plot(data.index.values, data.Opens, color = 'green', label = 'Opens') # plot the legend for the first plot ax1.legend(loc = 'upper right', fontsize = 14) plt.ylabel('Opens', fontsize=16) # Hide the top x axis ax1.axes.get_xaxis().set_visible(False) ####### NOW PLOT THE OTHER SERIES ON A SINGLE PLOT # plot 212 is the MI series # plot series ax2 = fig.add_subplot(212) ax2.plot(data.index.values, data.Joiners, color = 'orange', label = 'Joiners') # plot the legend for the second plot ax2.legend(loc = 'upper right', fontsize = 14) # set the fontsize for the bottom plot plt.ylabel('Joiners', fontsize=16) plt.tight_layout() plt.show()
type: Answer
score: 0

http://stackoverflow.com/q/49803188
has body: I have created an azure app service for Python 3.4 and installed pip there using this https://bootstrap.pypa.io/get-pip.py script. Everything works fine except when I try to execute pip install dlib library the exception occurs: RuntimeError: CMake must be installed to build the following extensions: dlib Is there a way to install Cmake at the machine running this app service?
has title: Run python dlib library on azure app service
upvote count: 3
tagged with: azure
has comment: http://stackoverflow.com/comment/86627925
has answer: http://stackoverflow.com/a/49904852
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86760085
favorite count: 0
type: Question
score: 3
tagged with: azure-web-app-service
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49803366
has title: Point opacity relative to depth matplotlib 3D point plot
has comment: http://stackoverflow.com/comment/86646142
tagged with: opacity
tagged with: plot
linked to: http://stackoverflow.com/q/17411940
type: AnsweredQuestion
has body: I am plotting a basic scatterplot in 3D using code from another SO post (Matplotlib scatter plot legend (top answer)) but want to have the points opacity relative to the 'depth' of the point as with ax.scatter depthshade=True. I had to use ax.plot because ax.scatter doesn't appear to work well with legends on 3D plots. I'm wondering if there is a way to get a similar aesthetic for ax.plot. Thanks!
has comment: http://stackoverflow.com/comment/86621542
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86638029
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86649413
has comment: http://stackoverflow.com/comment/86632489
accepted answer: http://stackoverflow.com/a/49819968
tagged with: 3d
has answer: http://stackoverflow.com/a/49819968
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/86714279
type: QuestionComment
score: 0
has text: @user6866797 Put a newline before each `for` to make things easier to read. The first (outer) for loop is iterating over the tuple `(I, R)` containing both lists. The second (inner) for loop is iterating over the elements from whatever list the outer loop is currently at.
type: Comment
comment on: http://stackoverflow.com/q/49849620

http://stackoverflow.com/q/49867110
type: Question
has body: I am trying to have my code find every other number from a given number within my function. For instance, my code looks like: def credit_card(number): check = float(number[1::2]) return check print(credit_card(123456789)) I want it to return 2,4,6,8.
has answer: http://stackoverflow.com/a/49867125
type: UnansweredQuestion
tagged with: python
score: -3
has title: Indexing numbers with a function?
upvote count: 0
downvote count: 3
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86750299

http://stackoverflow.com/a/49811099
type: Answer
has body: 'uidb64': b'Mw' this is a byte code, but django expects a string, so in the view from where you are sending the uid do a decode, uid.decode('utf-8') then send it to the template
answers question: http://stackoverflow.com/q/49810996
accepted answer of: http://stackoverflow.com/q/49810996
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86659072
upvote count: 1

http://stackoverflow.com/a/51311129
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49901422
type: Answer
accepted answer of: http://stackoverflow.com/q/49901422
has body: After much digging i found the problem on my machine to be a different package missing. This code from ansible/vmware.py was the culprit: try: # requests is required for exception handling of the ConnectionError import requests from pyVim import connect from pyVmomi import vim, vmodl HAS_PYVMOMI = True except ImportError: HAS_PYVMOMI = False ` You have to be able to import all of the imports in this try block to set HAS_PYVMOMI to True On my machine I was missing a package that was being imported by requests and therefore the try block was failing. uninstalling and reinstalling pyVmomi did not help and would not help. My machine is a CentOS 7.4 VM.
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/86709814
has text: thank so much for your helpful comments. I greatly appreciate your time and support!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49809569
type: AnswerComment

http://stackoverflow.com/comment/86816589
comment on: http://stackoverflow.com/q/49900511
type: Comment
score: 0
type: QuestionComment
has text: Building on what @N.Ivanov suggested: `dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'QWERTYASDFGHNBVCXZOPLKMNHY'))`. I'd also use the [str.translate](https://docs.python.org/3/library/stdtypes.html#str.translate) method

http://stackoverflow.com/q/49799356
accepted answer: http://stackoverflow.com/a/49801685
has body: I'm trying to visualize some data, but I'm not very experienced with the subject, and am having trouble finding the best bay to get what I'm looking for. I've searched around and found similar questions, but nothing that'll answer exactly what I want, so hopefully I'm not duplicating a common question. Anyway, I have a DataFrame with a column for patient_id (and others, but this is the relevant one. For example: patient_id other_stuff 0 000001 ... 1 000001 ... 2 000001 ... 3 000002 ... 4 000003 ... 5 000003 ... 6 000004 ... etc Where each row represents a specific episode that patient had. I want to plot the distribution in which the x axis is the number of episodes a patient had, and the y axis is the number of patients that have had said number of episodes. For example, based on the above, there's one patient with three episodes, one patient with two episodes, and two patients with one episode each, i.e. x = [1, 2, 3], y = [2, 1, 1]. Currently, I do the following: episode_count_distribution = ( patients.patient_id .value_counts() # the number of rows for each patient_id (i.e. episodes per patient) .value_counts() # the number of patients for each possible row count above (i.e. distribution of episodes per patient) .sort_index() ) episode_count_distribution.plot() This method does what I want, but strikes me as a bit opaque and hard to follow, so I'm wondering if there's a better way.
tagged with: visualization
tagged with: pandas
has answer: http://stackoverflow.com/a/49801685
upvote count: 5
has title: pandas - Plot distribution of column variable
favorite count: 0
type: Question
score: 5
downvote count: 0
answer count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/49758747
has body: As the error points out, you need to indent your code as required by Python language. So after typing if condition1:, hit enter, then hit tab and write your following code. def printer(data): if data&lt;5: print('data is less than 5') else: print('data is greater than 5') return And don't put a ; at the end of your function, this is not JS.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49758725

http://stackoverflow.com/comment/86605378
type: Comment
has text: Thanks Olivier that's sped things up significantly
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49795270

http://stackoverflow.com/a/49880509
accepted answer of: http://stackoverflow.com/q/49880210
has body: We can build a dictionary mapping dates to list of entries. Once we have all the data in our dictionary, we can take the averages of each value for each date from collections import defaultdict with open("Input2010_5a.txt", "r") as file: d = defaultdict(list) for line in file: date, *data = map(float, line.split()) d[date].append(data) averages = {date: [sum(values)/len(values) for values in zip(*entries)] for date, entries in d.items()} For data 1 2 3 4 2 3 4 5 1 1 1 1 this gives me print(averages) # {1.0: [1.5, 2.0, 2.5], 2.0: [3.0, 4.0, 5.0]}
answers question: http://stackoverflow.com/q/49880210
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86816768
comment on: http://stackoverflow.com/q/49899269
score: 1
type: Comment
type: QuestionComment
has text: You can install most Python libraries (Cython included) to a user directory rather than a global directory

http://stackoverflow.com/q/49801891
has comment: http://stackoverflow.com/comment/86622390
has answer: http://stackoverflow.com/a/49879576
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50466186
downvote count: 0
tagged with: keras
tagged with: tensorflow
has body: I'm trying to export a Keras model to TensorFlow. Keras Version 2.1.4 TF Version 1.3.0 Numpy Version 1.13.3 This is the model: img_width, img_height = 150, 150 batch_size = 32 samples_per_epoch = 1000 validation_steps = 300 nb_filters1 = 32 nb_filters2 = 64 conv1_size = 3 conv2_size = 2 pool_size = 2 classes_num = 3 lr = 0.0004 model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=(img_width, img_height, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) # this converts our 3D feature maps to 1D feature vectors model.add(Dense(64)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(1)) model.add(Dense(classes_num, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer=optimizers.RMSprop(lr=lr), metrics=['accuracy']) This is the export code: from tensorflow.python import keras estimator_model = keras.estimator.model_to_estimator(keras_model=model) This is the error: INFO:tensorflow:Using the Keras model provided. INFO:tensorflow:Using default config. WARNING:tensorflow:Using temporary folder as model directory: /home/dsxuser/.tmp/tmpbgYQQa INFO:tensorflow:Using config: {'_save_checkpoints_secs': 600, '_session_config': None, '_keep_checkpoint_max': 5, '_task_type': 'worker', '_global_id_in_cluster': 0, '_is_chief': True, '_cluster_spec': , '_evaluation_master': '', '_save_checkpoints_steps': None, '_keep_checkpoint_every_n_hours': 10000, '_service': None, '_num_ps_replicas': 0, '_tf_random_seed': None, '_master': '', '_num_worker_replicas': 1, '_task_id': 0, '_log_step_count_steps': 100, '_model_dir': '/home/dsxuser/.tmp/tmpbgYQQa', '_save_summary_steps': 100} AttributeErrorTraceback (most recent call last) in () 1 from tensorflow.python import keras ----> 2 estimator_m…
favorite count: 0
has title: 'Sequential' object has no attribute '_is_graph_network' when exporting Keras model to TensorFlow
upvote count: 9
tagged with: python
has comment: http://stackoverflow.com/comment/86774840
has comment: http://stackoverflow.com/comment/101094151
type: Question
score: 9
answer count: 2

http://stackoverflow.com/comment/86777881
comment on: http://stackoverflow.com/a/49880586
type: AnswerComment
has text: Tried your solution before but not worked template rendering gets no display to show,only white screen...
score: 0
type: Comment

http://stackoverflow.com/comment/86531861
type: QuestionComment
comment on: http://stackoverflow.com/q/49758227
has text: @chepner PathZero - is that path /Users/test/Downloads/File
score: 0
type: Comment

http://stackoverflow.com/comment/86634354
score: 1
type: Comment
type: QuestionComment
has text: @jezrael I'm way too tired to look closely at this today but I might tomorrow if I've got time :)
comment on: http://stackoverflow.com/q/49809438

http://stackoverflow.com/a/49843508
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86702082
accepted answer of: http://stackoverflow.com/q/49843161
type: Answer
has comment: http://stackoverflow.com/comment/86702521
has body: You can try this way: # sample data df = pd.DataFrame({'Shot#': ['001_0010','002_0020','003_0010','003_0020','003_0030','004_0010','003_0010'], 'play': ['a','b','c','d','a','b','d']}) # let's say val_to_search = '003_0010' # get row index value where match is found ix = df['Shot#'].loc[df['Shot#'].str.contains(val_to_search)].index # get rows of match value as output df.values[ix] # output array([['003_0010', 'c'], ['003_0010', 'd']], dtype=object) If you want to return a value from specfic column, there are multiple methods to do that: Method 1: df.apply(lambda row: row['Shot#'] if row['Shot#'] == val_to_search else np.nan, axis=1) Method 2: mask = df['Shot#'].str.contains(val_to_search) df['new_col'] = df.loc[mask,'Shot#'] print(df) Shot# play new_col 0 001_0010 a NaN 1 002_0020 b NaN 2 003_0010 c 003_0010 3 003_0020 d NaN 4 003_0030 a NaN 5 004_0010 b NaN 6 003_0010 d 003_0010
score: 0
answers question: http://stackoverflow.com/q/49843161

http://stackoverflow.com/comment/86788258
comment on: http://stackoverflow.com/a/49885898
type: Comment
has text: Another issue is that for it does not work with the bottom, the player just flips gravity and falls down off the screen. Can you fill this code in a bit more? Its too vague @Prune
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86574495
score: 1
type: Comment
has text: Technically, it's a builtin name. You won't find `len` in the global scope.
comment on: http://stackoverflow.com/a/49779550
type: AnswerComment

http://stackoverflow.com/q/49765266
tagged with: pandas
type: UnansweredQuestion
has body: I have what I think is an easy question but I'm missing something. I've got a data frame of values. I want to average the rows... but I only want to do so if it matches a certain number of entries -- or lacks NaN values in other words. So the following dataframe should get an 'average' column of [1.5, 1.5, np.nan], but I'm getting a "truth value of a Series is ambiguous" error. I don't know what that means. I thought it'd be something like this... df = pd.DataFrame([[1,np.nan,2], [1, 1.5, 2], [np.nan, np.nan, 1]]) df['mean'] = df[0:3].mean(axis=1) if df['nullsum'] &lt; 2 else np.nan ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
has answer: http://stackoverflow.com/a/49765280
type: Question
has answer: http://stackoverflow.com/a/49765403
has title: How to apply function to row of a dataframe only if it contains less than a certain number of NaNs?
tagged with: dataframe
tagged with: python
score: 0
answer count: 2

http://stackoverflow.com/q/49784989
has comment: http://stackoverflow.com/comment/86585570
linked to: http://stackoverflow.com/q/49732826
linked to: http://stackoverflow.com/q/4710067
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86585439
has body: I want to delete a specific line in a text file in python. for example, say in my text file I have: Ben Walsh - 768 James Cook - 659 Jamie Walsh - 4359 Owen Perkins - 699 Dylan Thomas - 1574 Adam Ward - 987 Allen Woodhouse - 599 I want to delete any line that contains the number 699. How do I do this? I have tried using this to solve it,Deleting a specific line in a file (python) however, using Tkinter I am asking the user to enter the number of the person they want to delete. So the number decides what is deleted because there are other items on the line it does not delete it.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/11968998
has title: Deleting a line from text file in python
has comment: http://stackoverflow.com/comment/86585828
has comment: http://stackoverflow.com/comment/86585652
tagged with: python
has comment: http://stackoverflow.com/comment/86585483
has comment: http://stackoverflow.com/comment/86585789
has answer: http://stackoverflow.com/a/57355472
score: -3
has comment: http://stackoverflow.com/comment/86585558
has answer: http://stackoverflow.com/a/49785115
linked to: http://stackoverflow.com/q/6996603
has comment: http://stackoverflow.com/comment/86585513
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/86585638
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/86840054
type: QuestionComment
has text: did you try another option, e.g. register for an account at https://pypi.org/ and then choose option 1 when prompted?
type: Comment
comment on: http://stackoverflow.com/q/49787860
score: 0

graphics
tag name: graphics
type: Tag
tags question: http://stackoverflow.com/q/49888538
tags question: http://stackoverflow.com/q/49829783
tags question: http://stackoverflow.com/q/49868646
tags question: http://stackoverflow.com/q/49787167

http://stackoverflow.com/comment/86588851
comment on: http://stackoverflow.com/q/49786743
type: Comment
score: 0
has text: I think the first, you are redefining the module as a whole. The second, you are reassigning the reference within the `sys` module
type: QuestionComment

http://stackoverflow.com/comment/100132703
has text: It is a nice answer. Based on this, I'd take 2 independent distributions with support on a bound interval. scale them accordingly to have the above intervals. Chose the shape factors such that the means add up to the required mean.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49856676
type: AnswerComment

http://stackoverflow.com/a/49848565
answers question: http://stackoverflow.com/q/49848375
score: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/86745651
upvote count: 1
has body: The format of the GET is incorrect. And you need to connect to the socket: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) request = "GET /r/AccidentalRenaissance/comments/8ciibe/mr_fluffies_betrayal/ HTTP/1.1\r\nHost: www.reddit.com\r\n\r\n" s.connect(("www.reddit.com", 80)) s.sendall(request.encode()) contest = s.recv(1024).decode() s.close() print(contest)

http://stackoverflow.com/comment/86572748
comment on: http://stackoverflow.com/q/49778642
type: Comment
score: 2
has text: @chrisz yep. it uses "9900" as base 16 - converts to int - so this question does not really makes sense to me
type: QuestionComment

http://stackoverflow.com/q/49772590
accepted answer: http://stackoverflow.com/a/49772960
score: 0
tagged with: list
has body: I've written a script in python to scrape some contents from a webpage. The scraper is doing good when it comes to parse the data. There are two fields to scrape name and data each of which contains lists of items. However, when I print it, the result becomes messy because I'm unable at this point to print them properly. This is what I have tried so far: import requests, csv from bs4 import BeautifulSoup LINK = 'http://active.boeing.com/doingbiz/d14426/geoprocess.cfm?ProcessCode=000&amp;pageID=m20487&amp;Country=AllLocations&amp;State=' def get_item(url): res = requests.get(url).text soup = BeautifulSoup(res,"lxml") name = [item.find_next_sibling().text for item in soup.select("strong")] table = soup.select('table[cellspacing="1"]')[0] for items in table.select("tr")[1:]: data = [item.get_text(strip=True) for item in items.select("td")] print(name,data) #this is where I need to twitch the code to get them printed like how it should be with open("itemresults.csv","a",newline="") as infile: writer = csv.writer(infile) writer.writerow(name,data) #I can't write them like so but if I try like [name,data] this the results are messy if __name__ == '__main__': get_item(LINK) For the clarity: the list within name variable should be printed once but they are being printed keeping pace with lists within data variable. As they are big enough to show how the expected result look like, I'm trying with a demo: "1,2,3" are within "name". I wish to get them printed like below: 1 2 3 q w e a s d c x r They are printed like the following instead: 1 2 3 q w e 1 2 3 a s d 1 2 3 c x r The bottom line is: 1. I wish to get them printed accordingly and 2. Write in a csv file in the right way
answer count: 2
has answer: http://stackoverflow.com/a/49774365
possible better answer: http://stackoverflow.com/a/49774365
has comment: http://stackoverflow.com/comment/86561485
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/86560257
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86560731
has comment: http://stackoverflow.com/comment/86561119
has comment: http://stackoverflow.com/comment/86560608
has comment: http://stackoverflow.com/comment/86561780
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/86562937
has title: Can't make my scraper print and write results accordingly
has comment: http://stackoverflow.com/comment/86561244
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49772960

http://stackoverflow.com/comment/86650922
score: 0
type: AnswerComment
has text: Thanks! I think this is the way to go
comment on: http://stackoverflow.com/a/49817401
type: Comment

http://stackoverflow.com/a/49840739
answers question: http://stackoverflow.com/q/49840675
has body: Try the conda install, such like conda install package_name==version
type: Answer
score: 0

http://stackoverflow.com/comment/138162928
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/61243904
type: Comment
has text: I don't think this is a sound solution... If you don't know what is initializing the other thread then you could have some serious problems that you will never know you even have

http://stackoverflow.com/a/49924911
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49909224
score: 5
type: AcceptedAnswer
downvote count: 0
has body: TL;DR — if you want something to show up in META, make it a kwarg. The client.get method is a different signature from requests.get. This is because the kwargs of self.client.get map directly to HTTP attributes. Take a look at the source. You'll notice the stack is: get generic request _base_environ In that process, the kwargs are carried to _base_environ with very few alterations. They're then merged into a dictionary that includes all of the basic headers you'd expect: # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See http://www.python.org/dev/peps/pep-3333/#environ-variables environ = { 'HTTP_COOKIE': self.cookies.output(header='', sep='; '), 'PATH_INFO': '/', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.input': FakePayload(b''), 'wsgi.errors': self.errors, 'wsgi.multiprocess': True, 'wsgi.multithread': False, 'wsgi.run_once': False, } environ.update(self.defaults) environ.update(request) return environ The above is then passed into a WSGIRequest object in the request method. That class then takes the provided environ dict and assigns it to the META property: class WSGIRequest(HttpRequest): def __init__(self, environ): script_name = get_script_name(environ) # If PATH_INFO is empty (e.g. accessing the SCRIPT_NAME URL without a # trailing slash), operate as if '/' was requested. path_info = get_path_info(environ) or '/' ############################## ## ## ## This is the line you're ## ## looking for. ## ## ## ############################## self.environ = environ self.path_info = path_info
accepted answer of: http://stackoverflow.com/q/49909224

http://stackoverflow.com/q/49861456
answer count: 1
has body: I have been going through django by example book.I have made the necessary changes for google login. below image shows https://console.developers.google.com/apis setting. Changes for keys in settings.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'account.authentication.EmailAuthBackend', 'social.backends.facebook.Facebook2OAuth2',#for face book authentication 'social.backends.google.GoogleOAuth2', ) #Creating a facebook authentication for django auth framework SOCIAL_AUTH_FACEBOOK_KEY = '356920068048038' # Facebook App ID SOCIAL_AUTH_FACEBOOK_SECRET = 'f57792e060753abb7f15ed183512ee4a' # Facebook App Secret #Asking additional permissions for facebook users SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_REDIRECT_IS_HTTPS = True #google authentication SOCIAL_AUTH_GOOGLE_OAUTH2_KEY ='419087081878-rt976l4dovnujv6lhjnfgtkc8sejpjlf.apps.googleusercontent.com' # Google Consumer Key SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'ItMLE4-nSID-UG73xm7tiL2f' # Google Consumer Secret I have enabled the google+API as mentioned in the book,below is my html link. Login with Google When I click on login with google ,iam getting the error **Error: redirect_uri_mismatch.**Below is the screenshot. I have gone through various online resources to resolve this but not successful as of now,please let me know how can i resolve this.
tagged with: django
upvote count: 1
tagged with: python
score: 1
has title: Error: redirect_uri_mismatch error while creating google login through django
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49861538
downvote count: 0

http://stackoverflow.com/comment/137998676
type: Comment
comment on: http://stackoverflow.com/a/69620212
score: 0
type: AnswerComment
has text: This solution is legit. Works like a charm for me. Thank you.

http://stackoverflow.com/q/49845169
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49845872
tagged with: image
has body: My Question is how to destroy a image with a Button Click. This is the image-upload. img1 = PhotoImage(file="C:/Users/Stavr/Desktop/giphy.gif") w1 = Label(root, image=img1) w1.place(x = 360, y = 380) This is the button delete_image_Button=Button(root, text="delete image", command=delete_image_function) And here the function def delete_image_function(): ??????????? Ok i thing the question is clear. Can someone help me to fill this code? Thanks ahead of time!!
score: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86705564
has comment: http://stackoverflow.com/comment/86705193
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Destroy Image in Python Tkinter
has comment: http://stackoverflow.com/comment/86706309

http://stackoverflow.com/a/49869406
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49869373
answers question: http://stackoverflow.com/q/49869373
has body: Get the return out of the for loop. Also date_count isn't an array so you should be using .append() not addition: def dates_with_intensity(vehicle_records, intensity): """Returns number of days with the given traffic intensity level""" new_list = [] for number in vehicle_records: date_count = number[0] number_count = number[1] traffic = traffic_intensity(number_count) if traffic == intensity: new_list.append(date_count) return new_list
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86871799
type: AnswerComment
has text: Hi Raja, my folder structure is exactly as you show it. This also becomes clear from my imports. Note that I already proposed a solution, which works for me. The client calls a route in lambda, and only return statements from that route go back to the client. So I captured returns from `utils.py` in that route (or def) in `app.py` et voila...
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49913445

http://stackoverflow.com/a/49922880
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49828755
answers question: http://stackoverflow.com/q/49828755
score: 1
has body: The problem was in fact trivial, as clarified with JetBrains support: I needed to set the parent folder of my_project as content root (/Users/my_user/dev/github/), instead of using /Users/my_user/dev/github/my_project/ directly. This was needed because the source code contained imports from module my_project which could not be resolved, as there was no subfolder my_project inside of my main project folder. I implemented this change in Project settings -&gt; Modules view, Project settings -&gt; Facets view and also in the run configuration.
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86783063
type: QuestionComment
has text: @RebeccaNelson Your solution is correct! I couldn't find any SSL setting on graphenedb but I guess that is set up by default.
comment on: http://stackoverflow.com/q/49883223
type: Comment
score: 0

http://stackoverflow.com/a/52606205
has comment: http://stackoverflow.com/comment/97587237
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92152988
score: 4
has body: You can set the parameters of Parameterized objects (models, kernels, likelihoods etc) using assign(): k1.assign(k1.read_trainables()) (or some other dict of path-value pairs). You might as well create a new kernel object, though! Note that each time you create new parameterized objects - this applies both to kernels and models, as in your fit() method - you add operations to the tensorflow graph, which can slow down graph computation significantly if it grows a lot. You probably want to look into manually handling tf.Graph() and tf.Session() to keep them distinct for each model. (See the notebooks on session handling and further tips and tricks in the new GPflow documentation.)
answers question: http://stackoverflow.com/q/49817410
type: Answer
accepted answer of: http://stackoverflow.com/q/49817410
upvote count: 4

http://stackoverflow.com/comment/86686786
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49835849
score: 0
has text: Possible duplicate of [How do I install pip on macOS or OS X?](https://stackoverflow.com/questions/17271319/how-do-i-install-pip-on-macos-or-os-x)

http://stackoverflow.com/comment/86616661
has text: `{i: j for i, *j in zip(*[x[i::4] for i in range(4)])}` might be a bit cleaner.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49800687
score: 1

http://stackoverflow.com/comment/101094138
type: AnswerComment
has text: I get AttributeError: module 'tensorflow' has no attribute 'python'
comment on: http://stackoverflow.com/a/50466186
score: 0
type: Comment

http://stackoverflow.com/q/49807797
answer count: 0
tagged with: h5py
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86630736
tagged with: python
has comment: http://stackoverflow.com/comment/86630677
tagged with: data-science
tagged with: matlab
has body: I am writing h5 file as follows in matlab for loop // Let's assume 4 for now fileN = imread(filename); im = cat(4, im, fileN); h5create('data.h5', '/Image', [64 64 3 3], 'Datatype', 'uint8'); h5write('data.h5', '/Image', im); Here, fileN have dimension 64 x 64 x 3 Hence im have dimensions 64 x 64 x 3 x 4 I am reading data.h5 as follows in python hf = h5py.File('./data.h5', 'r') syn1 = hf['/Image'] doing syn1.shape returns 4 x 3 x 64 x 64 Why so? Reading data.h5 in matlab returns correct axes i.e. 64 x 64 x 3 x 4 I have a work-around of using np.moveaxis but was curious if how hd5 file in stored and is there a way in h5py to read dimensions differently (i.e. change the order to the original one while reading itself) Note that, this reverse ordering rotates image by 90 degree as we are reading in reverse order and that's why I need move axis to make it right.
score: 0
has comment: http://stackoverflow.com/comment/86630968
has comment: http://stackoverflow.com/comment/86630994
has comment: http://stackoverflow.com/comment/86631020
has title: moving axes while reading h5 file in python(h5py) written in matlab
has comment: http://stackoverflow.com/comment/86695734
type: Question

http://stackoverflow.com/comment/86768497
type: Comment
type: AnswerComment
has text: OK, I've tried the same code on 3 different computers running last version of Win10, and all three showed the right White King icon. Have no idea about what is different on your system. Sorry.
comment on: http://stackoverflow.com/a/49875348
score: 0

http://stackoverflow.com/comment/86778229
has text: Also, storing the result of `limit(integrate(α*x*exp(-α*x), (x, 0, t), conds='none'), t, oo)` in variable `result` and then calling `limit(result, t, oo)` does not raise this error.
comment on: http://stackoverflow.com/q/49880817
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49769796
has title: Comparing elements within list of lists
score: 1
has comment: http://stackoverflow.com/comment/86554608
answer count: 1
tagged with: loops
has answer: http://stackoverflow.com/a/49771213
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/zip
tagged with: python
has body: I have following list of lists taken from .csv file: [['1002', '27', 'K', '1100004224', '2688.40'],['1002', '50', 'S', '1100004224', 2688.40']] The idea is to iterate through list of lists, compare index 3 ('1100004224') and if they are equal, add index 4 to each other and append into new list. So result of above (index 1 and 2 disregarded) [['1002', '1100004224', '5376.8']] Edit: If element is not equal, take following list: [['1002', '27', 'K', '1100004224', '2688.40'],['1002', '50', 'S', '1100004224', 2688.40'],['1002', '50, 'S', '1100004225', '1000']] Result should be: [['1002', '1100004224', '5376.8'],['1002','1100004225','1000']] How could I achieve that? Was looking into zip, trying numerous loops but I am blocked.
accepted answer: http://stackoverflow.com/a/49771213
type: AnsweredQuestion
tagged with: list
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49833016
has body: You can shorten your code by using zip: import csv d = {'09-04-2018' : {1: 11, 2: 5, 3: 1, 4: 1, 5: 0} , '10-04-2018' : {1: 5, 2: 1, 3: 1, 4: 1, 5: 0}} with open('filename.csv', 'w') as f: write = csv.writer(f) full_rows = [i for h in [zip(*b.items()) for _, b in sorted(d.items(), key=lambda x:map(int, x[0].split('-')))] for i in h] write.writerows([['counts']+[a for a, _ in sorted(d.items(), key=lambda x:map(int, x[0].split('-')))]]+list(zip(*[full_rows[0]]+full_rows[1::2]))) Output: counts,09-04-2018,10-04-2018 1,11,5 2,5,1 3,1,1 4,1,1 5,0,0
type: Answer
answers question: http://stackoverflow.com/q/49830757
score: 0

http://stackoverflow.com/q/49868528
answer count: 1
has answer: http://stackoverflow.com/a/49868575
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/86752764
type: Question
tagged with: python-3.x
upvote count: 2
accepted answer: http://stackoverflow.com/a/49868575
downvote count: 1
has body: This is my module storing my account information for easy-access in further project. #universal.py def fb_acc(): usr = XXXX pwd = XXXX def bank_acc(): accno = XXXX ssc = XXX pwd = XXXX However, when I tried to use to put these variables in the local variable, it reported like this: &gt;&gt; from universal import fb_acc &gt;&gt; usr = fb_acc.usr Traceback (most recent call last): File "&lt;pyshell#7&gt;", line 1, in &lt;module&gt; usr = fb_acc.usr AttributeError: 'function' object has no attribute 'usr' Can anyone help my point my syntax errors in 2 scripts?
has title: (Python 3.6) Can't not use variable in module
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/86719163
has text: Possible duplicate of [Matplotlib: How to make the background transparent?](https://stackoverflow.com/questions/36332349/matplotlib-how-to-make-the-background-transparent)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49852306
score: 2

http://stackoverflow.com/comment/86587661
comment on: http://stackoverflow.com/q/49785239
has text: It sounds like you need a non-trainable variable rather than a constant, like `tf.Variable(r, trainable=False)`. Do I understand this correctly?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88664018
type: AnswerComment
has text: i need some additional help... i am applying this regex on the Email message which is downloaded as string in text/plain format into a variable... the regex is not working on it... but if i copy the email message completely and paste it in my code as a string in a variable, then the regex is working. I am not able to understand this issue..
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49817969

http://stackoverflow.com/comment/86836058
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49909918
has text: Thanks so much! I really appreciate the help.
score: 0

http://stackoverflow.com/comment/86753390
score: 0
has text: Sorry, but it's going to happen again! >>> import universal as uni >>> foo = uni.facebook() >>> usr = foo.usr Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> usr = foo.usr AttributeError: 'facebook' object has no attribute 'usr'
type: AnswerComment
comment on: http://stackoverflow.com/a/49868575
type: Comment

http://stackoverflow.com/comment/86557135
type: Comment
type: QuestionComment
has text: tried to google ? what about `geoip` ?
comment on: http://stackoverflow.com/q/49771067
score: 0

http://stackoverflow.com/a/49911361
has body: One way is to use operator.itemgetter. import operator def most_oscars(d): return max(d.items(), key=operator.itemgetter(1)) nominees = {'Meryl Streep': 20, 'Robert De Niro': 7, 'Michael Caine': 6, 'Maggie Smith': 6} print(most_oscars(nominees)) # ('Meryl Streep', 20)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49911314

http://stackoverflow.com/comment/86581504
type: Comment
has text: Have you considered looking at the next chunk for the next newline character?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49782992

http://stackoverflow.com/a/49833949
has comment: http://stackoverflow.com/comment/86702519
has body: Where is the row added from ? If from Flask app you can use Signals in Model to send notification when the new row is added
type: Answer
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86791510
upvote count: 1
has comment: http://stackoverflow.com/comment/86702364
answers question: http://stackoverflow.com/q/49833921

http://stackoverflow.com/comment/86688466
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49836522
has text: @EduardoAndrade fixed

http://stackoverflow.com/q/49780991
has comment: http://stackoverflow.com/comment/86577439
favorite count: 0
has answer: http://stackoverflow.com/a/49781044
type: Question
accepted answer: http://stackoverflow.com/a/49781072
has body: My text file is like below. [0, "we break dance not hearts by Short Stack is my ringtone.... i LOVE that !!!.....\n"] [1, "I want to write a . I think I will.\n"] [2, "@va_stress broke my twitter..\n"] [3, "\" &amp;quot;Y must people insist on talking about stupid politics on the comments of a bubblegum pop . Sorry\n"] [4, "aww great &amp;quot;Picture to burn&amp;quot;\n"] [5, "@jessdelight I just played ur joint two s ago. Everyone in studio was feeling it!\n"] [6, "http://img207.imageshack.us/my.php?image=wpcl10670s.jpg her s are so perfect.\n"] [7, "cannot hear the new due to geographic location. i am geographically undesirable. and tune-less\n"] [8, "\" couples in public\n"] [9, "damn wendy's commerical got that damn in my head.\n"] [10, "i swear to cheese &amp;amp; crackers @zyuuup is in Detroit like every 2 months &amp;amp; i NEVER get to see him! i swear this blows monkeyballs!\n"] [11, "\" getting ready for school. after i print out this\n"] I want to read every second element from the list mean all the text tweets into array. I wrote tweets = [] for line in open('tweets.txt').readlines(): print line[1] tweets.append(line) but when I see the output, It just takes 2nd character of every line.
tagged with: python
has comment: http://stackoverflow.com/comment/86577366
possible better answer: http://stackoverflow.com/a/49781133
has comment: http://stackoverflow.com/comment/86577408
linked to: http://stackoverflow.com/q/49778665
has comment: http://stackoverflow.com/comment/86577392
has answer: http://stackoverflow.com/a/49781133
has answer: http://stackoverflow.com/a/49781348
answer count: 4
has title: How to read list element in Python from a text file?
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49781072

http://stackoverflow.com/comment/86636162
type: QuestionComment
has text: Possible duplicate of [python time format check](https://stackoverflow.com/questions/1322464/python-time-format-check)
score: 0
comment on: http://stackoverflow.com/q/49809512
type: Comment

http://stackoverflow.com/a/49841495
score: 0
answers question: http://stackoverflow.com/q/49841155
type: Answer
has body: This is an interpretation of what I understood from your question: https://pyfiddle.io/fiddle/0893e2af-726d-4fb3-9155-d83ecc5bbd55/ import random diceboard = [1,2,0,4,5,0] #for example def roll(): return list(map( lambda x: random.randint(1,6), range(len(diceboard)) )) n=0 #this basically means that per each element #that does not have a value of zero(pls correct my code) non_zero_diceboard = [d for d in diceboard if d &gt; 0] for i in range(len(non_zero_diceboard)): n=n+1 newroll=roll() newroll=newroll[:n] #this limits the size of the list print(newroll)

http://stackoverflow.com/q/49797295
has title: Running a python script on a linux machine after every few minutes, only if its not already running
tagged with: python
has answer: http://stackoverflow.com/a/49797716
has body: I have a python script which has to run once every 3 minutes. The script runs a process can run for more than 10 minutes though. And hence I need to make sure that if it's already running it shouldn't run. I need to do this without any database interference. The approach I have used it is having a cron via the following command in the crontab. */3 * * * * sudo ps aux|grep -v grep|grep "python XMLProcessor.py" || cd /home/ubuntu/git/perpule-python-subscriber; sudo python XMLProcessor.py It runs smoothly. But the problem here is, once in a while, even after the process ends, the command sudo ps aux|grep -v grep|grep "python XMLProcessor.py" still gives an output because of which the python script doesn't run. Please suggest me a better approach or rectify the one I'm using. All the suggestions are appreciated.
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: ubuntu
answer count: 1
favorite count: 0
tagged with: linux
type: Question
tagged with: cron

http://stackoverflow.com/a/49926516
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49913228
has body: The answer is trivially simple (hint from a colleague). You evaluate the returned value from some_def in the caller function (myRoute). If it's non-empty you return that one. Using the example from the question, app.py looks like so: from chalice import Chalice, Response from chalicelib.utils import some_class app = Chalice(app_name='myApp') app.debug = True @app.route('/myRoute', methods=['POST'], content_types=['application/octet-stream']) def myRoute(): some_class_instance = some_class() r = some_class_instance.some_def() if r: return r else: return Response( body={'hello': 'world'}, headers={'Content-Type': 'application/json'})
accepted answer of: http://stackoverflow.com/q/49913228

http://stackoverflow.com/a/49795208
upvote count: 0
downvote count: 1
has comment: http://stackoverflow.com/comment/86605138
has body: There are multiple ways to solve this : could you try : from unidecode import unidecode new_string = unidecode(string) then use the new string for your processing You can also look at this link if unidecode didnt work : https://stackoverflow.com/questions/3704731/replace-non-ascii-chars-from-a-unicode-string-in-python
answers question: http://stackoverflow.com/q/49795137
has comment: http://stackoverflow.com/comment/86608055
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/86604899

http://stackoverflow.com/a/49789715
upvote count: 1
has body: Try to change the URL to, say, http://www.google.com and update Python to the latest version.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49787794
downvote count: 0

iframe
tags question: http://stackoverflow.com/q/49778017
tag name: iframe
type: Tag

http://stackoverflow.com/comment/86652299
has text: I have been coming across this `package_data` but I have not found any complete example
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49818553

http://stackoverflow.com/q/49878789
has comment: http://stackoverflow.com/comment/86773383
answer count: 0
tagged with: python
type: UnansweredQuestion
tagged with: flask
duplicate of: http://stackoverflow.com/q/12269537
linked to: http://stackoverflow.com/q/38982807
downvote count: 0
score: 1
upvote count: 1
has body: I am looking to control my raspberry pi using alexa voice commands and need to open up flask to accept incoming requests from outside my network. My setup would have alexa using amazons AWS lambda to process the request and send a vocal response back to alexa. An aditional request would be made from the code hosted on AWS to my raspberry pi running flask. My question is how safe would it be to publicly expose the flask server through port forwarding and what could I do to make this safe or safer? I have read that changing the debug to False on flask would be advisable. Would it also be possible to set a rule in flask to only accept connections from specific domains?
duplicate of: http://stackoverflow.com/q/38982807
favorite count: 0
has title: Is it safe to port forward to Flask development server?
tagged with: raspberry-pi
tagged with: server
tagged with: alexa-skills-kit
type: Question

http://stackoverflow.com/comment/86819895
comment on: http://stackoverflow.com/a/49901914
type: Comment
type: AnswerComment
has text: Hm, I don't get any errors. Post your updated code and example function call.
score: 0

http://stackoverflow.com/comment/86703869
score: 1
comment on: http://stackoverflow.com/q/49844564
type: QuestionComment
has text: `len` / `raw_input`, etc. are builtins. `import builtins; dir(builtins)` (python3) will give you a list of them
type: Comment

http://stackoverflow.com/a/49768988
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49768600
has body: The class in question has __call__ method that allows to treat it's instances as functions. To see exactly what happens in your specific case, you can have a look on official github of Keras (Layer class, TimeDistributed). Your class in question is ingerited like that: TimeDistributed &lt;- Wrapper &lt;- Layer. In Layer.__call__ we see that it's a wrapper around .call method, so here you go.

http://stackoverflow.com/q/49776040
has title: Longest Palindromic Subsequence
has comment: http://stackoverflow.com/comment/86575268
tagged with: computer-science
type: Question
accepted answer: http://stackoverflow.com/a/49776790
tagged with: algorithm
has answer: http://stackoverflow.com/a/49776790
tagged with: python
has comment: http://stackoverflow.com/comment/86575794
type: AnsweredQuestion
score: 0
has body: I tried to solve it using recursion. Here's my code. It is failing for "ABDA" (returning 3 instead of 1). The reasoning for this is clear to me but I'm not sure how to fix that. def lps(s): print(s) n = len(s) if n &lt;= 1: return n if s[0] == s[n-1]: return 2 + lps(s[1:-1]) return max(lps(s[:-1]), lps(s[1:]))
has comment: http://stackoverflow.com/comment/86575330
answer count: 1

http://stackoverflow.com/comment/86574409
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49779076
type: QuestionComment
has text: related: https://stackoverflow.com/questions/43777551/python-saving-an-eval-function

http://stackoverflow.com/comment/86630955
type: Comment
has text: I place the geckodriver in the same directory where my code is. That way there is no confusion about the version.
type: QuestionComment
comment on: http://stackoverflow.com/q/49806074
score: 0

http://stackoverflow.com/q/49824630
tagged with: admin
has comment: http://stackoverflow.com/comment/86665422
linked to: http://stackoverflow.com/q/1339845
favorite count: 0
type: Question
has body: I'm working on a Django/Wagtail project. I have a very customized feature in the admin view what will delete an object when hitting Save if certain conditions are met. I have this in my class (that is a snippet): def save(self, *args, **kwargs): if condition: self.delete() else: return super(MyModel, self).save(*args, **kwargs) This works as expected. The object gets deleted, but after this I get an error page because the browser remains in the same URL /snippets/myapp/mymodel/1234/ but the object doesn't exist anymore. I thought of two possible solutions for this. Possible solution 1: def save(self, *args, **kwargs): if condition: self.delete() #### ===== &gt; Redirect to objects list view else: return super(MyModel, self).save(*args, **kwargs) Possible solution 2: def save(self, *args, **kwargs): if condition: #### ===== &gt; Don't delete and redirect to delete view (.../mymodel/1234/delete/) else: return super(MyModel, self).save(*args, **kwargs) These are the two possible solutions I thought, but I don't know how to do any of them, even after reading docs here and there. How can I do what I'm trying to achieve?
tagged with: sql-delete
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/86666852
tagged with: python
has comment: http://stackoverflow.com/comment/86668749
has comment: http://stackoverflow.com/comment/86665286
has title: Redirect to delete view in Django admin
answer count: 0
tagged with: wagtail
downvote count: 0
tagged with: django
upvote count: 1

http://stackoverflow.com/q/49779551
accepted answer: http://stackoverflow.com/a/49782220
answer count: 1
has answer: http://stackoverflow.com/a/49782220
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86574895
has title: Chaining custom querysets inside the Queryset Object to obtain a different custom queryset
tagged with: django-queryset
type: Question
score: 0
tagged with: django
has body: I have the following code: class MQuerySet(models.query.QuerySet): def active(self): return self.filter(is_active=True) def type_a(self): return self.filter(type=AB) def active_type_a(self): return self.active().self.type_a() The issues is in chaining in active_type_a method, because my example will fail. Off course the above example is simple, and I can add the filter, but I have also more complex querysets, where I want to do this.
tagged with: python

http://stackoverflow.com/a/49761534
score: 0
has body: As the docs and previous answers already state the command you want to execute via subprocess.Popen() needs to be passed as a list. From the docs: Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces) are single list elements. Another useful tip you can get from the docs is to use shlex.split() to help you to properly split your command into a list. Beware though that the use of special shell parameters (e.g. $USER) might not work well with subprocess.Popen() unless you would set the shell=True option, which you shouldn't do without reading the doc's Security Considerations.
type: Answer
answers question: http://stackoverflow.com/q/49761056

http://stackoverflow.com/comment/86852251
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49908158
has text: You could have used scrapy shell

http://stackoverflow.com/a/49834228
has comment: http://stackoverflow.com/comment/86684614
score: 2
has comment: http://stackoverflow.com/comment/86685961
has body: If you look at the documentation for append you can see that it returns the resulting DataFrame, and doesn't alter the DataFrame on which append is called nor the DataFrame which is the argument. In the body of your loop, you probably meant something like df1 = df1.append(wsClient.start()) As DJK correctly notes below, for a more efficient alternative, you can first create a list of all DataFrames, then append: dfs = [] for i in wsClient.start(): dfs.append(wsClient.start()) df1 = pd.concat(dfs)
has comment: http://stackoverflow.com/comment/86686348
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49834173
downvote count: 0
has comment: http://stackoverflow.com/comment/86685781
has comment: http://stackoverflow.com/comment/86685801
accepted answer of: http://stackoverflow.com/q/49834173
type: Answer

http://stackoverflow.com/comment/86723753
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49854626
has text: Welcome to SO. Please provide a **[mcve]**.
type: Comment

http://stackoverflow.com/comment/86585564
comment on: http://stackoverflow.com/a/49783648
has text: You are welcome. I'm glad you got your problem solved.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49881398
score: 1
answer count: 1
downvote count: 0
has title: Splitting pandas df into groups using column value being consecutively higher than x
upvote count: 1
accepted answer: http://stackoverflow.com/a/49881786
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49881786
tagged with: datetime
has body: I have a dataframe with datetimes as an index, and 2 columns. What I want to do is split the df up into days, split those days up into blocks where the value of column 2 is equal/higher than 70, and calculate the both the duration (index) and the average from column 1 for that period. I can think of ways of doing it, but those include dictionaries and ugly loops or groupby from itertools, so I prefer a more pandanic solution. I'm already splitting up my bigger dataframe using: for x in df.groupby(pd.Grouper(freq='24H', base=12)), which splits them into chuncks posted below 2018-04-13 12:00:00 11.4 70.0 2018-04-13 13:00:00 11.3 73.0 2018-04-13 14:00:00 10.6 70.0 2018-04-13 15:00:00 11.2 67.0 2018-04-13 16:00:00 10.4 67.0 2018-04-13 17:00:00 10.8 66.0 2018-04-13 18:00:00 10.8 67.0 2018-04-13 19:00:00 10.8 67.0 2018-04-13 20:00:00 10.7 69.0 2018-04-13 21:00:00 10.3 70.0 2018-04-13 22:00:00 10.1 71.0 2018-04-13 23:00:00 9.8 73.0 2018-04-14 00:00:00 9.4 75.0 2018-04-14 01:00:00 9.1 77.0 2018-04-14 02:00:00 8.6 80.0 2018-04-14 03:00:00 7.8 84.0 2018-04-14 04:00:00 7.3 87.0 2018-04-14 05:00:00 8.3 87.0 2018-04-14 06:00:00 8.3 88.0 2018-04-14 07:00:00 8.6 88.0 2018-04-14 08:00:00 9.0 87.0 2018-04-14 09:00:00 11.3 83.0 2018-04-14 10:00:00 12.2 81.0 2018-04-14 11:00:00 12.4 82.0 I need: (not in this formatting, just example) 2018-04-13 12:00:00 - 3 hours - 71.0 2018-04-13 21:00:00 - 14 hours - 80.86 Any clean suggestions for this problem? It's kind of related to this, but I couldn't transform it to my example. I also though about filtering out where column 2 &lt; 70, but than I'd have trouble getting the consecutiveness again EDIT: my final solution df['Time'] = df.index for day, daydf in df.groupby(pd.Grouper(freq='24H', base=12)): df_filtered = daydf[daydf['v2'] &gt;= 70] grouping_key = df_filtered.Time.diff().dt.total_seconds().ne(3600).cumsum() grouper = df_filtered.groupby(grouping_key) aggregated_data = grouper.agg({'Time': 'first', 'v1': 'mean', 'v2': len}) print(aggre…
tagged with: python
has comment: http://stackoverflow.com/comment/86779591
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/29632784

http://stackoverflow.com/comment/86786698
type: QuestionComment
has text: That seem to perfectly do the job. Submit it as an answer please
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49885266

http://stackoverflow.com/comment/86772153
has text: @jpp Vote to close?
comment on: http://stackoverflow.com/a/49878002
score: 0
type: Comment
type: AnswerComment

python-requests
tags question: http://stackoverflow.com/q/49835062
tags question: http://stackoverflow.com/q/49913002
tags question: http://stackoverflow.com/q/49896860
tags question: http://stackoverflow.com/q/49832988
tags question: http://stackoverflow.com/q/49890227
tags question: http://stackoverflow.com/q/49818842
tags question: http://stackoverflow.com/q/49876442
tags question: http://stackoverflow.com/q/49896464
tags question: http://stackoverflow.com/q/49904801
tags question: http://stackoverflow.com/q/49880150
type: Tag
tags question: http://stackoverflow.com/q/49764218
tags question: http://stackoverflow.com/q/49909381
tags question: http://stackoverflow.com/q/49804906
tags question: http://stackoverflow.com/q/49825421
tags question: http://stackoverflow.com/q/49820173
tags question: http://stackoverflow.com/q/49869769
tags question: http://stackoverflow.com/q/49896788
tags question: http://stackoverflow.com/q/49813056
tags question: http://stackoverflow.com/q/49833207
tags question: http://stackoverflow.com/q/49802305
tags question: http://stackoverflow.com/q/49868937
tags question: http://stackoverflow.com/q/49855419
tags question: http://stackoverflow.com/q/49806786
tags question: http://stackoverflow.com/q/49787022
tags question: http://stackoverflow.com/q/49910982
tags question: http://stackoverflow.com/q/49879996
tags question: http://stackoverflow.com/q/49834066
tag name: python-requests
tags question: http://stackoverflow.com/q/49850036
tags question: http://stackoverflow.com/q/49887395
tags question: http://stackoverflow.com/q/49813265
tags question: http://stackoverflow.com/q/49848395
tags question: http://stackoverflow.com/q/49847376
tags question: http://stackoverflow.com/q/49831540
tags question: http://stackoverflow.com/q/49879471
tags question: http://stackoverflow.com/q/49871455
tags question: http://stackoverflow.com/q/49861597
tags question: http://stackoverflow.com/q/49908132
tags question: http://stackoverflow.com/q/49848175
tags question: http://stackoverflow.com/q/49803518
tags question: http://stackoverflow.com/q/49845712
tags question: http://stackoverflow.com/q/49892870
tags question: http://stackoverflow.com/q/49832076
tags question: http://stackoverflow.com/q/49808367
tags question: http://stackoverflow.com/q/49805545

http://stackoverflow.com/q/49882131
tagged with: django
has body: I am currently creating a python application using the Django web framework. In the app users can login and create personal goals. These goals are stored in a database and users are able to view them. I am having trouble linking the webpages within the app. When i try to click onto another webpage I am getting an AttributeError telling me that their is know Reverse for 'goal_create' not found. 'goal_create' is not a valid view function or pattern name This is how I am trying to implement the app: Models //The information that i am storing in the DB class Goal(models.Model): title = models.CharField(max_length=1000) body = models.TextField() created_data = models.DateTimeField(auto_now_add=True, auto_now=False) updated_data = models.DateTimeField(auto_now_add=False, auto_now=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.title Views //the list of goals that the User will see on the webpage. def goal_list(request): goals = Goal.objects.all().order_by('created_data') return render(request, 'goals/goal_list.html', { 'goals': goals }) @login_required def goal_create(request, *args): if request.method == 'POST': form = forms.CreateGoal(request.POST, request.FILES) if form.is_valid(): goal_create = Post(CreateGoal.title.data, CreateGoal.text.data) # save article to db //Returns the list of goals after it has been created. return redirect('goals:goal_list') else: form = forms.CreateGoal() return render(request, 'goals/goal_create.html', {'form': form}) Urls app_name = 'goals' urlpatterns = [ url(r'^$', views.goal_list, name='list'), url(r'^create/$', views.goal_create, name='create'), url(r'^details/$', views.goal_detail, name="goal_detail"), Base.html //My navbar that I'm using to link Webpages. RecoverRight {% if user.is_authenticated %} Profile Edit Profile Add Goal View Goals Nutrition Exercise {# Workout #} Log out
accepted answer: http://stackoverflow.com/a/49882175
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49882175
has title: Linking Django wepages
answer count: 1

http://stackoverflow.com/comment/86841345
score: 2
has text: have you considered regex?
type: QuestionComment
comment on: http://stackoverflow.com/q/49912875
type: Comment

http://stackoverflow.com/comment/86732998
type: QuestionComment
has text: You need to convert the string to an int or double, using those functions: `double("0.002")` and `int("20")`, for example.
score: 0
comment on: http://stackoverflow.com/q/49858967
type: Comment

http://stackoverflow.com/comment/86609939
comment on: http://stackoverflow.com/a/49791402
type: Comment
type: AnswerComment
has text: Thank you very much for your answer. Trying your solution, I noticed, that there are also "real" empty cells. Therefore I added `df = df.loc[:, df.isnull().mean() < .6]`. Is there a way to combine it with your code (`df = df.loc[:, df.isin([' ','NULL',0]).mean() < .6]`)?
score: 0

http://stackoverflow.com/a/49801154
upvote count: 37
type: Answer
accepted answer of: http://stackoverflow.com/q/49801060
answers question: http://stackoverflow.com/q/49801060
has comment: http://stackoverflow.com/comment/96316505
score: 37
type: AcceptedAnswer
downvote count: 0
has body: As per the documentation for pandas.read_excel, skiprows must be list-like. Try this instead to exclude rows 1 to 336 inclusive: df = pd.read_excel("file.xlsx", sheet_name = "Sheet1", skiprows = range(1, 337), usecols = "H:BD") Note: range constructor is considered list-like for this purpose, so no explicit list conversion is necessary.

http://stackoverflow.com/comment/86827565
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49866916
has text: If I don't know that inside those numbers there's a wall, how could I tell it? Extra-info is needed. For example 3D viewing the data and selecting the desired triangle/edge/etc with the mouse. Or analize normals and their change between adyacent triangles.

http://stackoverflow.com/comment/86532748
score: 1
has text: This could be a possible solution: https://stackoverflow.com/questions/49158246/unable-to-start-selenium-safari-webdriver-via-python3
type: QuestionComment
comment on: http://stackoverflow.com/q/49758692
type: Comment

paramiko
tags question: http://stackoverflow.com/q/49890374
tags question: http://stackoverflow.com/q/49777888
tags question: http://stackoverflow.com/q/49896802
tags question: http://stackoverflow.com/q/49831800
type: Tag
tag name: paramiko
tags question: http://stackoverflow.com/q/49879862
tags question: http://stackoverflow.com/q/49859822
tags question: http://stackoverflow.com/q/49860350
tags question: http://stackoverflow.com/q/49882737

http://stackoverflow.com/comment/86817503
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49900913
type: AnswerComment
has text: @bphi yes, I don't think OP is considering such cases. I just added an edit where I explained that the question is rather underspecified about what can and can't be in `a`.

http://stackoverflow.com/q/49845715
answer count: 2
accepted answer: http://stackoverflow.com/a/49846109
upvote count: 0
has comment: http://stackoverflow.com/comment/86706376
has answer: http://stackoverflow.com/a/49846109
has body: I am developing a program that will check the user's hard drives for games and display a list of all the games installed on the computer with the relative names and paths. I achieved this by creating a database in JSON that contains for each game the name and the paths(The program runs on linux and windows so there are 4 values in database: name, windows_path, windows_steam_path, linux_path, linux_steam_path) *Steam paths are to check if the game uses steam cloud "name", "Windows_path", "Windows_steam_path", "Linux_path", "Linux_sync_path" I also needed a "Template" for each game so I created a class for them class Game(): def __init__(self, game_name, game_path, sync_path): self.name = game_name self.path = game_path self.sync_path = sync_path def to_dict(self): self.name self.path self.sync_path return {"name": self.name, "path": self.path, "sync_path": self.sync_path} And I also needed an user interface Eel - https://github.com/ChrisKnott/Eel Eel hosts a local webserver so I'll use HTML files to display content Home User Guide Now I get the data from the database like so save_database = json.load(open("database.json")) def load_game(db_item): current_os = platform.system() path = "" sync_path = "" [name, win_path, win_sync, lin_path, lin_sync] = db_item if current_os == "Windows": sync_path = win_sync path = win_path print(path, sync_path) else: sync_path = lin_sync path = lin_path print(path, sync_path) print(Game(name, os.path.expanduser(path), os.path.expanduser(sync_path))) return Game(name, os.path.expanduser(path), os.path.expanduser(sync_path)) save_database = map(load_game, save_database) And pass the data into a dictionary def get_all_in_database(): for game in save_database: game_dict = game.to_dict() yield game_dict And then I used lodash to create a template and javascript and jquery to modify the html and call the python functions (I am not posting that code here since this is already pretty big question) When I go to my desired page it calls the jav…
has title: Storing the values produced by a generator for multiple uses
possible better answer: http://stackoverflow.com/a/49845764
downvote count: 1
favorite count: 0
tagged with: yield
has comment: http://stackoverflow.com/comment/86706754
has comment: http://stackoverflow.com/comment/86706772
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49845764
tagged with: python
score: -1
tagged with: dictionary
type: Question

http://stackoverflow.com/a/49908482
upvote count: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49908385
answers question: http://stackoverflow.com/q/49908385
has body: Use merge to fitler records: foo.merge(foo_multi.to_frame(), left_on=['bar','baz'], right_index=True).drop(0, axis=1) Output: bar baz qux 0 1 a z 1 2 b x 2 3 c c
type: Answer
score: 2

http://stackoverflow.com/comment/86554444
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49769623
has text: it run and give me the result of the script

http://stackoverflow.com/comment/86731468
type: AnswerComment
has text: Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49857991

http://stackoverflow.com/a/49793393
downvote count: 0
has comment: http://stackoverflow.com/comment/86601263
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49793255
type: Answer
score: 4
has body: You're sending a return to the ajax query which is then going to try and do something with it. Instead of using the ajax call, try something like: window.location = '/getSearchQuesions/'+ques_id
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49793255

global
type: Tag
tags question: http://stackoverflow.com/q/49781573
tags question: http://stackoverflow.com/q/49837453
tags question: http://stackoverflow.com/q/49800802
tags question: http://stackoverflow.com/q/49871107
tags question: http://stackoverflow.com/q/49847809
tag name: global
tags question: http://stackoverflow.com/q/49777905
tags question: http://stackoverflow.com/q/49766508

http://stackoverflow.com/a/49779271
score: 0
has comment: http://stackoverflow.com/comment/86573998
has comment: http://stackoverflow.com/comment/86574206
has body: Try running the makemigration command along with the app name. This is needed if you have models in the default app. Eg - python manage.py makemigrations parser. Then run the migrate command.
type: Answer
answers question: http://stackoverflow.com/q/49778816
has comment: http://stackoverflow.com/comment/86574129

http://stackoverflow.com/comment/86777908
type: Comment
type: QuestionComment
score: 0
has text: Its a HTML page Chrisz.
comment on: http://stackoverflow.com/q/49880846

http://stackoverflow.com/q/49795988
tagged with: django-model-field
has title: django-models - a non-string type is stored into CharField
upvote count: 1
answer count: 1
downvote count: 1
tagged with: django
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49796460
accepted answer: http://stackoverflow.com/a/49796460
type: AnsweredQuestion
score: 0
has body: I am using Django 1.11 on Python 3, and MySQL 5.7. Suppose I have a model with a CharField, like so: class ModelA(models.Model): ID = models.AutoField(primary_key=True) a = models.CharField() And in the shell, I tried doing this: &gt;&gt;&gt; instance = ModelA(a={'1' : 1}) &gt;&gt;&gt; instance which gives me a TypeError: __str__ returned non-string (type dict) But when I do this: &gt;&gt;&gt; instance.save() I don't get any error. If I try: &gt;&gt;&gt; instance.a {'1': 1} But when I try: &gt;&gt;&gt; ModelA.objects.get(ID=&lt;the ID of the above instance&gt;).a "{'1': 1}" Which means that it got stored in the database table as a string. My question is why does this implicit conversion happen, and why doesn't save() raise an error like __str__() did? Thanks for your help!
tagged with: django-models
tagged with: python

http://stackoverflow.com/comment/86531435
type: QuestionComment
type: Comment
has text: You need to learn how return values work...
comment on: http://stackoverflow.com/q/49758228
score: 0

http://stackoverflow.com/q/49837676
has comment: http://stackoverflow.com/comment/86691002
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/75356869
tagged with: python
has body: I have been working on a terminal GUI using python and Curses for the past few days and feel I am not making any progress. Right now what I need to do is create two panels that both take up half the screen minus 1 - 2 characters as a margin. I want these windows to be able to handle resizing so if the user decides to make their screen larger or smaller my panels resize to adjust to the user's needs. +---------------------------+ +---------------------------+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | +---------------------------+ +---------------------------+ At This time I can draw the windows and have them resize. The issue is that if I resize smaller then what my boxes are currently set I get an error. _curses_panel.error: move_panel() returned ERR I am not sure if this is due to how I am checking and resizing the window or a limitation of Curses. Can you please take a look at my code and let me know if I am losing my mind or not? import curses import curses.panel screen = curses.initscr() curses.start_color() curses.noecho() curses.curs_set(1) screen.keypad(1) curses.cbreak() height,width = screen.getmaxyx() window = curses.newwin(1,1,1,1) window2 = curses.newwin(height -2 ,(width/2)-10, 1,width/2+1) left_panel = curses.panel.new_panel(window) right_panel = curses.panel.new_panel(window2) window.border('|', '|', '-', '-', '+', '+', '+', '+') window2.border('|', '|', '-', '-', '+', '+', '+', '+') curses.panel.update_panels() curses.doupdate() running = True x = 0 while ( running ): height,width = screen.getmaxyx() k = window.getch() if k == curses.KEY_RESIZE: window2.erase() window.erase() h, w = screen.getmaxyx() window2.resize(height - 2 ,(width/2)-10) window.resize(height - 2,(width/2) - 10) left_panel.replace(window) right_panel.replace(window2) left_panel.move(0,0) right_panel.move(0,width/2) window2.border('|', '|', '-', '-', '+', '+', '+', '+') window.border('|', '|', '-', '-', '+', '+', '+', '+') if k == ord('q') or x …
tagged with: ncurses
score: 0
has comment: http://stackoverflow.com/comment/86690749
answer count: 1
tagged with: curses
has title: Pythons Curses Library and Resizing
type: Question

http://stackoverflow.com/comment/86777745
comment on: http://stackoverflow.com/a/49880880
type: AnswerComment
has text: Actually, it should be like that~
type: Comment
score: 0

http://stackoverflow.com/comment/86731008
has text: @Rachitkapadia yes, I want to loop over the form data and perform updates in mysql.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49858032

http://stackoverflow.com/a/49869919
type: AcceptedAnswer
has body: The package is most likely broken, and if you look at one of the more recent changes they added an invalid line here in the setup file. install_requires=[ + 'flask&gt;=0.12.2, &lt;0.12.99' 'future&gt;=0.15, &lt;0.16.99', See the missing comma ^. This causes the two lines to get concatenated into flask>=0.12.2, &lt;0.12.99future>=0.15, &lt;0.16.99 Update I reported the issue to the library author here and they fixed it.
type: Answer
accepted answer of: http://stackoverflow.com/q/49869827
score: 0
answers question: http://stackoverflow.com/q/49869827

http://stackoverflow.com/q/49890492
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49890593
answer count: 1
has answer: http://stackoverflow.com/a/49890593
score: 1
tagged with: latitude-longitude
favorite count: 0
downvote count: 0
upvote count: 1
tagged with: python
has title: Convert utm to lat long in csv using pandas
tagged with: utm
has body: import pandas import utm df = pd.read_csv("0006.csv") this is the output of the imported csv file Description PositionDateTime X Y Z \ 0 DT0006 2018-01-01 00:00:08 668471.51 7473216.92 43.60 1 DT0006 2018-01-01 00:00:09 668471.51 7473216.90 43.62 2 DT0006 2018-01-01 00:00:39 668471.63 7473216.49 44.00 3 DT0006 2018-01-01 00:01:02 668471.66 7473216.41 44.07 4 DT0006 2018-01-01 00:01:14 668471.66 7473216.39 44.09 5 DT0006 2018-01-01 00:01:48 668471.67 7473216.37 44.11 6 DT0006 2018-01-01 00:01:54 668471.67 7473216.37 44.11 7 DT0006 2018-01-01 00:02:36 668471.67 7473216.37 44.11 8 DT0006 2018-01-01 00:02:39 668471.67 7473216.37 44.11 9 DT0006 2018-01-01 00:03:18 668451.81 7473220.04 52.36 Assuming the Zone is 45K, I would like to use utm to convert X, Y into latitude and longitude. So far I know how to convert like this utm.to_latlon(???, ???, ??, '?') How do I convert each numbers of lat and long into separate columns? What I did was this df['lat'], df['long'] = utm.to_latlon(df.X, df.Y, 45, 'K') This is wrong, still looking how to do that. many thanks
type: Question
tagged with: pandas

http://stackoverflow.com/q/49902322
tagged with: python
has comment: http://stackoverflow.com/comment/86821947
accepted answer: http://stackoverflow.com/a/49903306
linked to: http://stackoverflow.com/q/7587490
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49903306
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86821148
downvote count: 0
answer count: 1
has title: convert rgb image from numpy array to HSV (opencv)
has comment: http://stackoverflow.com/comment/86821010
favorite count: 0
type: Question
tagged with: opencv
has body: When I'm converting an image from RGB to HSV, if the image come straight from opencv, everything is alright: img = cv2.imread(path) img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) However, if this image come from a numpy array of shape (nb_of_images, 224, 224, 3) there is some complications. Here is my import function: def import_images(path_list): path_len = len(path_list) images = numpy.zeros((path_len, 224, 224, 3), dtype = numpy.float64) for pos in range(path_len): testimg = cv2.imread(path_list[pos]) if(testimg is not None): testimg = cv2.cvtColor(testimg, cv2.COLOR_BGR2RGB) testimg = cv2.resize(testimg, (224, 224)) images[pos, :, :, :] = testimg return images And now, here is my trouble: images = import_images(["./test/dog.jpg"]) img = images[0, :, :, :] img = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) The console give the following error: cv2.error: /io/opencv/modules/imgproc/src/color.cpp:11073: error: (-215) depth == 0 || depth == 2 || depth == 5 in function cvtColor I tried to change the image type: img.astype(numpy.float32) but the console give the same error What am I missing ? --edit-- I'm using python 3.5 numpy (1.14.2) opencv-python (3.4.0.12)
has comment: http://stackoverflow.com/comment/86821104
has comment: http://stackoverflow.com/comment/86821658
has comment: http://stackoverflow.com/comment/86822115
has comment: http://stackoverflow.com/comment/86821673
has comment: http://stackoverflow.com/comment/86821405

http://stackoverflow.com/a/49850248
answers question: http://stackoverflow.com/q/49848978
score: 2
downvote count: 0
has body: Using AmiTavory's sample data df = pd.DataFrame(dict(options=[ '[Bean status:Whole][Type of Roast:Medium]', '[Type of Roast:Espresso][Coffee Type:Blend]' ])) Combination of re.findall and str.split import re import pandas as pd pd.DataFrame([ dict( x.split(':') for x in re.findall('\[(.*?)\]', v) ) for v in df.options ]) Bean status Coffee Type Type of Roast 0 Whole NaN Medium 1 NaN Blend Espresso
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86726478
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49848978
type: Answer
has comment: http://stackoverflow.com/comment/86715004

http://stackoverflow.com/comment/86749058
has text: @bnoos Can you clarify what should taking place when "populating"?
comment on: http://stackoverflow.com/a/49864558
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/49913962
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49912739
has body: To make pip work for the install, you need to install pip using curl: curl https://bootstrap.pypa.io/get-pip.py | python The reason is that Python.org sites have stopped supporting older versions of TLS, so you need a later version of pip now. See this answer for more details.
has comment: http://stackoverflow.com/comment/86845325

http://stackoverflow.com/comment/86708392
comment on: http://stackoverflow.com/q/49846516
score: 0
type: Comment
has text: As it is, the question is "too broad". I'd advice you to check whether basic Naive Bayes for text classification, with multinomial model does what you want, take this as baseline, then take a look at more complex models, then eventually come back with more concrete questions.
type: QuestionComment

http://stackoverflow.com/comment/89280155
type: AnswerComment
score: 0
has text: Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Thanks
comment on: http://stackoverflow.com/a/51147820
type: Comment

http://stackoverflow.com/comment/86648052
comment on: http://stackoverflow.com/q/49799080
score: 0
has text: Possible duplicate of [PyQt5 does now show icons?](https://stackoverflow.com/questions/44080247/pyqt5-does-now-show-icons)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86580777
score: 0
type: Comment
has text: The histogram actually is *already* normalized, but in terms of it's density. Essentially, `sum(bin_heights*bin_widths) == 1.0`
type: QuestionComment
comment on: http://stackoverflow.com/q/49781927

http://stackoverflow.com/comment/86536119
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49760485
has text: I think you forgot to cose a few brackets (in both the first and second code sample).

http://stackoverflow.com/q/49810315
tagged with: python
has answer: http://stackoverflow.com/a/49811645
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/86636190
answer count: 4
has answer: http://stackoverflow.com/a/49837532
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49811645
downvote count: 0
has title: Storing the first word in each line of a string into a list
has comment: http://stackoverflow.com/comment/86635290
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49810400
has answer: http://stackoverflow.com/a/49811328
has body: I have a string containing multiple lines. Each line is broken by '\n' and contains commas after each word. I want to store the first word in each line into a list. Here is the string output: AIG,10,,,,Yes,,,Jr,,,MS,, Baylor College of Medicine,19,Yes,Yes,,,,,,,,,,Recent CGG,17,Yes,Yes,,,,,,,,MS,PhD,Recent Citi,27/28,Yes,,,Yes,,,Jr,Sr,,,, My list should be ['AIG', 'Baylor College of Medicine', 'CGG', 'Citi'] I thought about using split after the first comma and then go to the next line, but I do not know how I can achieve this. My Solution was to go back in my code and search for a list of "companies" I previously made. companies = ['AIG,10,,,,Yes,,,Jr,,,MS,,\n', 'Baylor\xa0College\xa0of\xa0Medicine,19,Yes,Yes,,,,,,,,,,Recent\n', 'CGG,17,Yes,Yes,,,,,,,,MS,PhD,Recent\n', 'Citi,27/28,Yes,,,Yes,,,Jr,Sr,,,,\n', 'ExxonMobil,11,Yes,,,Yes,Fr,Soph,Jr,Sr,PB,,,\n', 'Flow-Cal\xa0Inc.,16,Yes,,,Yes,,,Jr,Sr,,,,All\n', 'Global\xa0Shop\xa0Solutions,18,Yes,,,Yes,,,,Sr,PB,,,All\n'] cmpny_name = [] for i in companies: cmpny_name.append(i.split(',', 1)[0]) cmpny_name = [c.replace('\xa0', ' ') for c in cmpny_name] print(cmpny_name) OUTPUT:['AIG', 'Baylor College of Medicine', 'CGG', 'Citi', 'ExxonMobil', 'Flow-Cal Inc.', 'Global Shop Solutions', 'Harris County CTS', 'HCSS', 'Hitachi Consulting', 'HP Inc.', 'INT Inc.']
type: Question
has answer: http://stackoverflow.com/a/49810400

http://stackoverflow.com/comment/86676421
type: Comment
has text: @maya, no it's not, are you using python3?
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49830615

http://stackoverflow.com/comment/86581119
has text: This is quite an interesting idea, thanks for suggestion!
comment on: http://stackoverflow.com/a/49782929
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/49832681
answers question: http://stackoverflow.com/q/49832623
score: 0
type: Answer
has body: you are doing it right . But you need to escape the double quotes like i have shown below line from your code : file.write(" if command == "quit":\n") Fixed Line file.write(" if command == \"quit\":\n") hope this helps

http://stackoverflow.com/q/49866370
has comment: http://stackoverflow.com/comment/86748705
has title: SyntaxError when trying to handle errors with except
tagged with: try-catch
has comment: http://stackoverflow.com/comment/86748192
score: -2
has comment: http://stackoverflow.com/comment/86748512
has comment: http://stackoverflow.com/comment/86748866
tagged with: python
has answer: http://stackoverflow.com/a/49866390
has comment: http://stackoverflow.com/comment/86748203
type: AnsweredQuestion
upvote count: 0
tagged with: syntax-error
downvote count: 2
has body: I'm trying to program a personal assistant for my ICT class. I'm a beginner in python and I tried following a tutorial but I get a SyntaxError when using except. This is the script: try: command = r.recognize_google(audio) print ('Your command was: ' + command + '/n' #loop back ca sa asculte pentru comenzi daca nu gaseI'ste recon speech except sr.UnknownValueError: assistant(myCommand()) And here's the error: File "/Users/dumitruvictor/Desktop/Assistant.py", line 31 except (sr.UnknownValueError: ^ SyntaxError: invalid syntax Operating System: Mac OS X
answer count: 1
tagged with: error-handling
has comment: http://stackoverflow.com/comment/86748246
accepted answer: http://stackoverflow.com/a/49866390
tagged with: except
favorite count: 0
type: Question

http://stackoverflow.com/comment/86600024
type: QuestionComment
comment on: http://stackoverflow.com/q/49791885
score: 0
has text: @Alasdair pip version is 1.3.1, I'll try with mysqlclient then, maybe it is outdated
type: Comment

http://stackoverflow.com/comment/86562951
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49773722
score: 0
has text: It's hard to know what's going wrong with `mail_addresses` without some more information. Can you please either post the code you used to create `customers_df`, or the output from `print(mail_addresses)`? If the output is very long, just post a sample of it

keras
tags question: http://stackoverflow.com/q/49882424
tags question: http://stackoverflow.com/q/49772573
tags question: http://stackoverflow.com/q/49847312
tags question: http://stackoverflow.com/q/49892136
tags question: http://stackoverflow.com/q/49845706
tags question: http://stackoverflow.com/q/49801891
tags question: http://stackoverflow.com/q/49801135
tags question: http://stackoverflow.com/q/49811350
tags question: http://stackoverflow.com/q/49813577
tags question: http://stackoverflow.com/q/49812619
tags question: http://stackoverflow.com/q/49905274
tags question: http://stackoverflow.com/q/49804102
tags question: http://stackoverflow.com/q/49893201
tags question: http://stackoverflow.com/q/49855404
tags question: http://stackoverflow.com/q/49852241
tags question: http://stackoverflow.com/q/49857979
tags question: http://stackoverflow.com/q/49799539
tags question: http://stackoverflow.com/q/49886416
tags question: http://stackoverflow.com/q/49870386
tags question: http://stackoverflow.com/q/49831917
tags question: http://stackoverflow.com/q/49857842
tags question: http://stackoverflow.com/q/49861106
tags question: http://stackoverflow.com/q/49836058
tags question: http://stackoverflow.com/q/49832227
tags question: http://stackoverflow.com/q/49843113
tags question: http://stackoverflow.com/q/49913007
tags question: http://stackoverflow.com/q/49806437
tags question: http://stackoverflow.com/q/49911206
tags question: http://stackoverflow.com/q/49819438
tags question: http://stackoverflow.com/q/49897638
tags question: http://stackoverflow.com/q/49809052
tags question: http://stackoverflow.com/q/49810175
tags question: http://stackoverflow.com/q/49861009
tags question: http://stackoverflow.com/q/49861842
tags question: http://stackoverflow.com/q/49788549
tags question: http://stackoverflow.com/q/49856097
tags question: http://stackoverflow.com/q/49844416
tags question: http://stackoverflow.com/q/49899509
tags question: http://stackoverflow.com/q/49830584
tags question: http://stackoverflow.com/q/49843345
tags question: http://stackoverflow.com/q/49873676
tags question: http://stackoverflow.com/q/49890135
tags question: http://stackoverflow.com/q/49901661
tags question: http://stackoverflow.com/q/49889385
tags question: http://stackoverflow.com/q/49765265
tags question: http://stackoverflow.com/q/49842865
tags question: http://stackoverflow.com/q/49765144
tags question: http://stackoverflow.com/q/49863333
tags question: http://stackoverflow.com/q/49846359
tags question: http://stackoverflow.com/q/49915600
tags question: http://stackoverflow.com/q/49857812
tags question: http://stackoverflow.com/q/49797291
tags question: http://stackoverflow.com/q/49799979
tags question: http://stackoverflow.com/q/49800295
tags question: http://stackoverflow.com/q/49862326
tags question: http://stackoverflow.com/q/49902780
tags question: http://stackoverflow.com/q/49852061
tags question: http://stackoverflow.com/q/49775515
tags question: http://stackoverflow.com/q/49892528
tags question: http://stackoverflow.com/q/49803266
tags question: http://stackoverflow.com/q/49803503
tags question: http://stackoverflow.com/q/49886574
tags question: http://stackoverflow.com/q/49827328
tags question: http://stackoverflow.com/q/49846240
tags question: http://stackoverflow.com/q/49785536
tags question: http://stackoverflow.com/q/49866343
tags question: http://stackoverflow.com/q/49853718
tags question: http://stackoverflow.com/q/49873078
tags question: http://stackoverflow.com/q/49905849
tags question: http://stackoverflow.com/q/49834532
tags question: http://stackoverflow.com/q/49849680
tags question: http://stackoverflow.com/q/49782579
tags question: http://stackoverflow.com/q/49758199
tags question: http://stackoverflow.com/q/49824967
tags question: http://stackoverflow.com/q/49910419
tags question: http://stackoverflow.com/q/49861594
tags question: http://stackoverflow.com/q/49785133
tag name: keras
tags question: http://stackoverflow.com/q/49858233
tags question: http://stackoverflow.com/q/49834632

http://stackoverflow.com/comment/86816977
type: Comment
comment on: http://stackoverflow.com/q/49900714
has text: The question you referred to explains the 3rd parameter (step). Above the example prior to the one you shared.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86590226
comment on: http://stackoverflow.com/a/49787503
score: 0
has text: I can have the same name in the indexes, but I still need the result to have the same number of columns as the expected result I stated in the question
type: Comment
type: AnswerComment

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

http://stackoverflow.com/q/49838315
tagged with: pandas
has title: Python pandas: apply a function to dataframe.rolling()
has body: I have this dataframe: In[1]df = pd.DataFrame([[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]]) In[2]df Out[2]: 0 1 2 3 4 0 1 2 3 4 5 1 6 7 8 9 10 2 11 12 13 14 15 3 16 17 18 19 20 4 21 22 23 24 25 I need to achieve this: for every rows in my dataframe, if 2 or more values within any 3 consecutive cells is greater than 10, then the last of that 3 cells should be marked as True. The resulting dataframe df1 should be same size with True of False in it based on the above stated criteria: In[3]df1 Out[3]: 0 1 2 3 4 0 NaN NaN False False False 1 NaN NaN False False False 2 NaN NaN True True True 3 NaN NaN True True True 4 NaN NaN True True True df1.iloc[0,1] is NaN bacause in that cell, only two numbers were given but needed atleast 3 numbers to do the test. df1.iloc[1,3] is False since none in [7,8,9] is greater than 10 df1.iloc[3,4] is True since 2 or more in [18,19,20] is greater than 10 I figured dataframe.rolling.apply() with a function might be the solution, but how exactly?
has comment: http://stackoverflow.com/comment/86692790
tagged with: rolling-computation
tagged with: python
has comment: http://stackoverflow.com/comment/86692651
has answer: http://stackoverflow.com/a/49839362
has comment: http://stackoverflow.com/comment/86692367
linked to: http://stackoverflow.com/q/12182744
score: 2
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/49839033
linked to: http://stackoverflow.com/q/20109391
upvote count: 2
has comment: http://stackoverflow.com/comment/86692331
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49839893
possible better answer: http://stackoverflow.com/a/49839893
has comment: http://stackoverflow.com/comment/86693169
has answer: http://stackoverflow.com/a/49839033

http://stackoverflow.com/a/49813028
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49812724
has comment: http://stackoverflow.com/comment/86640543
has body: You can use pandas: import pandas as pd df = pd.DataFrame(date_wise_data).transpose() print(df.head()) # user1 user2 user3 user4 # 2018-04-03 8 0 5 1 # 2018-04-04 0 0 5 1 # 2018-04-05 2 0 2 8 # 2018-04-06 2 0 1 1 # 2018-04-07 6 5 1 2 Convert the dataframe to a dictionary: print(df.to_dict()) # {'user1': {'2018-04-03': 8, '2018-04-04': 0, '2018-04-05': 2, '2018-04-06': 2, '2018-04-07': 6, '2018-04-08': 2, '2018-04-09': 3}, 'user2': {'2018-04-03': 0, '2018-04-04': 0, '2018-04-05': 0, '2018-04-06': 0, '2018-04-07': 5, '2018-04-08': 0, '2018-04-09': 1}, 'user3': {'2018-04-03': 5, '2018-04-04': 5, '2018-04-05': 2, '2018-04-06': 1, '2018-04-07': 1, '2018-04-08': 1, '2018-04-09': 1}, 'user4': {'2018-04-03': 1, '2018-04-04': 1, '2018-04-05': 8, '2018-04-06': 1, '2018-04-07': 2, '2018-04-08': 1, '2018-04-09': 1}}
upvote count: 2

http://stackoverflow.com/q/49912484
type: Question
tagged with: ajax
type: UnansweredQuestion
has title: django render template variables and tags via ajax
tagged with: django
tagged with: python
score: 0
tagged with: django-templates
has body: I want to use Django+jquery-ajax to refresh my blog's new comments. The code is as follows: views.py: @require_POST def wirte_comment(request): """ajax new article comment""" if request.user.is_anonymous: login_url = reverse('login') return JsonResponse({'status': 'redirect', 'login_url': login_url}) # logined article_id = int(request.POST.get('article_id')) comment_form = ArticleCommentForm(request.POST) article = get_object_or_404(Article, id=article_id) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.author = request.user new_comment.article = article new_comment.save() create_action(request.user, article, verb=f"{request.user.username} commentted《{article.title}》") # comment html with open('blog/templates/blog/add_comment.html') as f: html = f.read() return JsonResponse({'status': 'ok', 'html': html}) else: return JsonResponse({'status': 'ko'}) I sent the HTML of the new comment as a string to the front end: add_comment.html: {% avatar article.author 25 class="circle-avatar" %} {{ article.author }} {{ comment }} article.html And then there's a problem: When I submit a new comment,it's rendered like this: {% avatar article.author 25 class="circle-avatar" %} {{ article.author }} {{ comment }} How can i solve this problem? Thanks very much.
answer count: 1
has answer: http://stackoverflow.com/a/49912671
tagged with: variables

http://stackoverflow.com/q/49827411
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: http://stackoverflow.com/tag/csv
score: 3
tagged with: reader
tagged with: python
has comment: http://stackoverflow.com/comment/86670561
accepted answer: http://stackoverflow.com/a/49827487
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/49827487
possible better answer: http://stackoverflow.com/a/49827690
has body: I'm trying to create a program that splits large CSV files into smaller ones. I've got the function working great, except it doesn't ever close the last file, which means it never finishes writing to that file. Here's what I've got: import csv length of original file = 1000 rows length_of_new_file = 100 # rows def file_splitter(file_name, desired_length): with open("{}".format(file_name), 'r') as original_file: header = original_file.readline() file_reader = csv.reader(original_file,dialect='excel') file_count = 0 new_name = 'split_file_test' loop = 0 while file_reader: with open("{}{}.csv".format(new_name, file_count), 'w', newline='') as new_file: new_file.write(header) csv_writer = csv.writer(new_file, delimiter=',') for line in file_reader: if loop == (desired_length-1): csv_writer.writerow(line) new_file.close() file_count += 1 loop = 0 break else: csv_writer.writerow(line) loop += 1 test_file = 'zlotsacontacts.csv' file_splitter(test_file, length_of_new_file) I have tried adding new_file.close(), but no matter where I put it the last file never seems to get closed. I've also tried different logic in the outermost while loop, like: while file_reader != '': and while file_reader not None: but from what I can find, the CSV module can't recognize None values. I'm not sure what I can do to close this loop!
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49827690
has title: Python 3 - CSV writer loop won't close after CSV reader reaches end of file
tagged with: writer

http://stackoverflow.com/q/49884154
has body: I am trying to split a user:pass:host:port proxy into user:pass and host:port, I know how to get the user:pass using proxytest = proxy.split("@")[0] when the proxy is user:pass@localhost:8080, it returns user:pass but how can I get the localhost:8080? Preferably a very easy way if possible. The proxy is opened in a .txt file and may be changed so I do not know the exact string.
has comment: http://stackoverflow.com/comment/86784448
has comment: http://stackoverflow.com/comment/86784642
has comment: http://stackoverflow.com/comment/86784627
downvote count: 6
has comment: http://stackoverflow.com/comment/86784385
has comment: http://stackoverflow.com/comment/86784897
answer count: 2
has comment: http://stackoverflow.com/comment/86784771
has comment: http://stackoverflow.com/comment/86784621
upvote count: 0
has answer: http://stackoverflow.com/a/49884447
has answer: http://stackoverflow.com/a/49884409
has title: How to get the text after a split when using a function?
has comment: http://stackoverflow.com/comment/86784607
score: -6
favorite count: 0
has comment: http://stackoverflow.com/comment/86784559
type: Question
tagged with: proxies
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86784411
has comment: http://stackoverflow.com/comment/86784469

http://stackoverflow.com/comment/86783009
type: AnswerComment
comment on: http://stackoverflow.com/a/49883468
has text: I guess this will work. I have implemented some kind of similar solution that I will post later.
score: 0
type: Comment

http://stackoverflow.com/comment/86568628
type: Comment
has text: Since answer will probably get flagged. Putting this here. https://networkx.github.io/documentation/stable/index.html
type: QuestionComment
comment on: http://stackoverflow.com/q/49775355
score: 0

http://stackoverflow.com/q/49768600
has title: Back to back parentheses in Python
accepted answer: http://stackoverflow.com/a/49768909
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49768909
upvote count: 2
downvote count: 2
has body: I am watching a video and saw the following line of code: encoded_frames = tf.keras.layers.TimeDistributed(cnn)(video) Can someone please tell me what the "(cnn)(video)" part is doing? Is the (video) part an anonymous function being called? Thanks
tagged with: python
possible better answer: http://stackoverflow.com/a/49768988
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49768988
tagged with: syntax

http://stackoverflow.com/comment/86723216
has text: POSCodeModifier max will be 50 and CSP will be 500 @Val
comment on: http://stackoverflow.com/q/49851934
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86825574
comment on: http://stackoverflow.com/a/49904741
type: Comment
score: 0
type: AnswerComment
has text: I will definitely do those too. Best. :)

http://stackoverflow.com/comment/86590927
type: Comment
type: AnswerComment
score: 1
has text: @LunchBox No, you've got that backward. You _don't_ want escape if you want to interpret the input as a regex. You _do_ want escape if you want to interpret it as a plain string (even if it happens to look like a regex). For example, if the user wants to strip off `'.'`, you want to escape that, so it only strips literal periods, not every character.
comment on: http://stackoverflow.com/a/49787880

http://stackoverflow.com/comment/86618982
has text: Also how do i prevent 'Nan' from being stored in a list while using apply?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49802038
score: 0

http://stackoverflow.com/a/49830027
downvote count: 0
has comment: http://stackoverflow.com/comment/86696728
upvote count: 1
has comment: http://stackoverflow.com/comment/87026556
score: 1
has comment: http://stackoverflow.com/comment/87020139
has comment: http://stackoverflow.com/comment/86966781
has comment: http://stackoverflow.com/comment/87019795
has comment: http://stackoverflow.com/comment/87018888
accepted answer of: http://stackoverflow.com/q/49829322
has comment: http://stackoverflow.com/comment/86695880
has comment: http://stackoverflow.com/comment/86874277
type: Answer
has comment: http://stackoverflow.com/comment/86695940
answers question: http://stackoverflow.com/q/49829322
has comment: http://stackoverflow.com/comment/86695719
has comment: http://stackoverflow.com/comment/86695698
has comment: http://stackoverflow.com/comment/86696229
has body: Issue with your code is that you have s and s+k inside the quotes and the interpreter treats it like a normal string not a variable. if you want to append 2 strings you need to use + operation. strA = "this is string A" strB = "this is a string B + String A i,e " +strA print(strB) output 'this is a string B + String A i,e this is string A' Here is how to append string to another string in your case: s = "some summary" #Assumed some Values k = "something else" payload = "{\r\n\t\"fields\":{\r\n\"project\":{\"key\":\"SSETOPS\"},\r\n\"summary\":" +'\"'+ s +'\"'+ ",\r\n\"description\":" +'\"'+ k+" "+s +'\"'+ ",\r\n\"issuetype\":{\"name\":\"Task\"},\r\n\"customfield_12610\":{\"value\":\"High\"},\r\n\"components\":[{\"name\":\"Other\"}],\r\n\"assignee\":{\"name\":\"rahsingh\"}\r\n}}" print(payload) This is what i got as an output : { "fields":{ "project":{"key":"SSETOPS"}, "summary":"some summary", "description":"something else some summary", "issuetype":{"name":"Task"}, "customfield_12610":{"value":"High"}, "components":[{"name":"Other"}], "assignee":{"name":"rahsingh"} }}
has comment: http://stackoverflow.com/comment/87018619
has comment: http://stackoverflow.com/comment/86695822
type: AcceptedAnswer

http://stackoverflow.com/a/49882372
has comment: http://stackoverflow.com/comment/86782199
score: 0
type: Answer
downvote count: 1
has body: Use a cartesian product to get all possible pairs import itertools as it all_pairs = it.product(tx, ty) And then use map to loop over all pairs and compute the cross product: map(lambda x: np.cross(x[0], x[1]), all_pairs)
answers question: http://stackoverflow.com/q/49881468
upvote count: 1

http://stackoverflow.com/comment/86543020
comment on: http://stackoverflow.com/q/49762985
type: QuestionComment
type: Comment
has text: I'm not really sure. It might be some other packages (failed to install correctly?) jammed pip. Or there are some [conflicts](https://github.com/rholder/retrying/issues/34#issuecomment-268013088) in your packages? Just a suggestion, check out the list of installed packages for potential problems, like multiple versions? If you remember you installed something unsuccessfully recently, try remove and clean up?
score: 0

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

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

http://stackoverflow.com/q/49881468
possible better answer: http://stackoverflow.com/a/49883489
has comment: http://stackoverflow.com/comment/86781841
tagged with: python
has answer: http://stackoverflow.com/a/49882305
score: 4
has answer: http://stackoverflow.com/a/49883489
has comment: http://stackoverflow.com/comment/86783510
has answer: http://stackoverflow.com/a/49882372
upvote count: 4
tagged with: numpy
has answer: http://stackoverflow.com/a/49884385
downvote count: 0
has title: Efficient way of computing the cross products between two sets of vectors numpy
has answer: http://stackoverflow.com/a/49883074
has comment: http://stackoverflow.com/comment/86780362
favorite count: 0
type: Question
has body: I have two sets of 2000 3D vectors each, and I need to compute the cross product between each possible pair. I currently do it like this for tx in tangents_x: for ty in tangents_y: cross = np.cross(tx, ty) (... do something with the cross variable...) This works, but it's pretty slow. Is there a way to make it faster? If I was interested in the element-wise product, I could just do the following # Define initial vectors tx = np.array([np.random.randn(3) for i in range(2000)]) ty = np.array([np.random.randn(3) for i in range(2000)]) # Store them into matrices X = np.array([tx for i in range(2000)]) Y = np.array([ty for i in range(2000)]).T # Compute the element-wise product ew = X * Y # Use the element_wise product as usual for i,tx in enumerate(tangents_x): for j,ty in enumerate(tangents_y): (... use the element wise product of tx and ty as ew[i,j]) How can I apply this to the cross product instead of the element-wise one? Or, do you see another alternative? Thanks much :)
accepted answer: http://stackoverflow.com/a/49884385
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86782883
has comment: http://stackoverflow.com/comment/86783694
answer count: 5
has comment: http://stackoverflow.com/comment/86782116

http://stackoverflow.com/q/49859957
tagged with: genfromtxt
score: 1
answer count: 1
favorite count: 0
type: Question
tagged with: numpy
has body: I have a CSV containing special characters. Some cells are arithmetic operations (like "(10/2)"). I would like to import these cells as string in numpy by using np.genfromtxt. What I notice is that it actually import them in UTF8 (if I understood). For instance everytime I have a division symbol I get this code in the numpy array :\xc3\xb7 How could I import these arithmetic operations as readable string? Thank you!
has answer: http://stackoverflow.com/a/49861251
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: special-characters
has title: Importing csv embedding special character with numpy genfromtxt
has comment: http://stackoverflow.com/comment/86735237
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86762373
has text: HEAD /listusers [status:404 request:0.254s] PUT /listusers [status:406 request:0.006s] Traceback (most recent call last): res = es.indices.create(index = INDEX_NAME, body = request_body) File "C:\Users\home\AppData\Local\Programs\Python\Python35- elasticsearch.exceptions.TransportError: TransportError(406, 'Content-Type header [] is not supported') i am getting the error at creating the indexes @ Lupanoide
score: 0
comment on: http://stackoverflow.com/q/49871124
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87814582
has text: The link are not working
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49809148

http://stackoverflow.com/comment/86683242
type: Comment
type: AnswerComment
has text: Requiring a parameter is not the difference. If you used a class that required a parameter, the class wouldn't receive the parameter.
score: 1
comment on: http://stackoverflow.com/a/49833974

http://stackoverflow.com/q/49827686
tagged with: nested-loops
answer count: 1
downvote count: 3
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49827701
type: UnansweredQuestion
score: -2
has body: print "\tdog \tbun \ketchup" count=1 for dog in [0,1]: for bun in [0,1]: for ketchup in [0,1]: print "#",count, "\t", print dog, "\t", bun, "\t", ketchup count=count+1 I'm having trouble in fixing this nested loop problem. Please help me to fix this in a simple way. Thanks
upvote count: 1
tagged with: python
has title: How does nested loop works in python?
tagged with: python-2.7

aiohttp
tags question: http://stackoverflow.com/q/49901840
tags question: http://stackoverflow.com/q/49869769
type: Tag
tag name: aiohttp
tags question: http://stackoverflow.com/q/49858711

http://stackoverflow.com/comment/86690319
comment on: http://stackoverflow.com/q/49837521
type: Comment
type: QuestionComment
score: 0
has text: You may want to have a look at Boyer-Moore algorithm.

http://stackoverflow.com/comment/86630976
type: Comment
has text: @tdelaney Presumably the intention is that it knows because of that assignment line—he wrote `b.x = a.x`, and he didn't write `b.x = a2.x`. This would make sense in a language with variables that were lvalues rather than names, it just doesn't make sense in Python.
comment on: http://stackoverflow.com/q/49807747
score: 1
type: QuestionComment

http://stackoverflow.com/q/49826635
has comment: http://stackoverflow.com/comment/86744610
accepted answer: http://stackoverflow.com/a/49827699
tagged with: google-api-explorer
has title: Google API Explorer for Spreadsheet returns properties - How do I get properties (filename) in Python Quickstart?
tagged with: google-sheets
answer count: 1
has comment: http://stackoverflow.com/comment/86677127
tagged with: google-sheets-api
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49827699
has comment: http://stackoverflow.com/comment/86827641
has comment: http://stackoverflow.com/comment/86829720
upvote count: 1
downvote count: 1
has body: When I use the Google API Explorer for SpreadSheet to Try this API and fill in the spreadsheetId, the information it returns includes a properties key that has the spreadsheet name in it: { "spreadsheetId": "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms", "properties": { "title": "Example Spreadsheet", "locale": "en_US", } } How do I get this information using Python? I want to get the filename from : result['properties']['title'] The Python quickstart code is: """ Shows basic usage of the Sheets API. Prints values from a Google Spreadsheet. """ from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # Setup the Sheets API 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())) # Call the Sheets API SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' RANGE_NAME = 'Class Data!A2:E' result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute() The result here is a hash of the data from the RANGE_NAME that was requested: { u'range': u "'Class Data'!A2:E101", u'values': [ [u 'Alexandra', u 'Female', u '4. Senior', u 'CA', u 'English'], [u 'Andrew', u 'Male', u '1. Freshman', u 'SD', u 'Math'], [u 'Anna', u 'Female', u '1. Freshman', u 'NC', u 'English'], [u 'Becky', u 'Female', u '2. Sophomore', u 'SD', u 'Art'], [u 'Benjamin', u 'Male', u '4. Senior', u 'WI', u 'English'], [u 'Carl', u 'Male', u '3. Junior', u 'MD', u 'Art'], [u 'Carrie', u 'Female', u '3. Junior', u 'NE', u 'English'], [u 'Dorothy', u 'Female', u '4. Senior', u 'MD', u 'Math'], [u 'Dylan', u 'Male', u '1. Freshman', u 'MA', u 'Math'], [u 'Edward', u 'Male', u '3. Junior', u 'FL', u 'English'], [u 'E…
tagged with: python
favorite count: 0
type: Question

http://stackoverflow.com/comment/86540702
type: QuestionComment
has text: anyway i can convince you to *not* store sequences in elements of the data frame?
score: 1
comment on: http://stackoverflow.com/q/49762555
type: Comment

http://stackoverflow.com/comment/86732375
type: QuestionComment
comment on: http://stackoverflow.com/q/49853772
has text: is age the same for every brain? So your vector has the same element in very entry
score: 0
type: Comment

http://stackoverflow.com/q/49820587
has comment: http://stackoverflow.com/comment/86657168
has comment: http://stackoverflow.com/comment/86656558
tagged with: python
has comment: http://stackoverflow.com/comment/86664757
has comment: http://stackoverflow.com/comment/86657057
has comment: http://stackoverflow.com/comment/86656398
has body: The following code will take the contents of 'out.txt' and append it to the end of 'fixed_inv.txt' in the form of a new file, 'concat.txt' based on a shared path. Sample lines of all files: 1) fixed_inv.txt 70 abc.def.com HRShared$ \vol\cor_q_share1\HRShared 34 NULL 3 4479242 Share 1 1 CifsPerm: 0, CifsType: 0, Remark:Up-level share detected. 0 CIFS NULL ntap 70 abc.def.com HRTraining$ \vol\cor_q_share1\HRTraining 35 NULL 4 4479243 Share 1 1 CifsPerm: 0, CifsType: 0, Remark:Up-level share detected. 0 CIFS NULL ntap 70 abc.def.com psoft_prd$ \vol\cor_q_share1\psoft_prd 36 NULL 6 4479245 Share 1 1 CifsPerm: 0, CifsType: 0, Remark:Up-level share detected. 0 CIFS NULL ntap 2) out.txt abcdef.ghi.com: \fs\FS11\cifs15\cifs-userhome-corp-prd_01: The inherited access control list (ACL) or access control entry (ACE) could not be built. (125), Access to file was denied (1) abcdef.ghi.com: \fs\FS11\cifs17\cifs-userhome-corp-prd_03: The inherited access control list (ACL) or access control entry (ACE) could not be built. (45) abcdef.ghi.com: \fs\FS11\cifs17\cifs-userhome-corp-prd_05: The inherited access control list (ACL) or access control entry (ACE) could not be built. (17) 3) concat.txt --> goal In the 'concat.txt' file, I am getting a few rows (out of thousands) that seem to have a random new line in the middle of said line. For instance, a line is supposed to look like: 122 abc.def.com Failed to get CIFS shares with error code -2147024891. None Non-supported share access type. 0 Unkonwn NULL bluearc Different Security Type (1), Access is denied. (1354), Pruned. Different security type (21), The inherited access control list (ACL) or access control entry (ACE) could not be built. (3713), Could not convert the name of inner file or directory (27) But instead, I have a few looking like: 122 abc.def.com Failed to get CIFS shares with error code -2147024891. None Non-supported share access type. 0 Unkonwn NULL bluearc Different Security Type (1), Access is denied. (1354), Prune…
has comment: http://stackoverflow.com/comment/86656978
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86656844
has comment: http://stackoverflow.com/comment/86656912
has comment: http://stackoverflow.com/comment/86657383
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86661679
answer count: 1
has title: How do I remove a random new line in the middle of a line in a text file using Python?
has comment: http://stackoverflow.com/comment/86656811
has comment: http://stackoverflow.com/comment/86656950
has comment: http://stackoverflow.com/comment/86657213
score: 0
has comment: http://stackoverflow.com/comment/86657177
has answer: http://stackoverflow.com/a/49820881
has comment: http://stackoverflow.com/comment/86657134

http://stackoverflow.com/comment/86827321
has text: Ah I was seeing both the page and the dropdown with models in Chrome 65, but just upgraded to Chrome 66, now getting `NET::ERR_CERT_SYMANTEC_LEGACY` error. Could it be certificate-related?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49905530
score: 0

http://stackoverflow.com/comment/86752764
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49868528
has text: Use Python Classes to access its attributes. What you are accessing are just local variables.
type: Comment

http://stackoverflow.com/a/49768471
has comment: http://stackoverflow.com/comment/86552282
type: Answer
has comment: http://stackoverflow.com/comment/86552181
has comment: http://stackoverflow.com/comment/86552270
has comment: http://stackoverflow.com/comment/86552355
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: What you do to get up and running from a git project: locate the git URL (ends with .git usually) Clone or download it install requirements, for python this would be: pip install -r requirements.txt run the app with given parameters Now step 4 is presumably where you run into trouble, the app seems to require 1 parameter (the image directory). This image directory is a folder on your computer. So point to a directory on your machine. For example: python app.py /home/mastermindzh/Pictures Edit After looking at the git repo my suspicions are confirmed.
accepted answer of: http://stackoverflow.com/q/49768334
answers question: http://stackoverflow.com/q/49768334

http://stackoverflow.com/a/49800114
score: 2
upvote count: 2
type: AcceptedAnswer
has body: **Here is a better solution to your question.** df['count'] = 0 df.loc[df['16/17']['Apps']&gt;9.0, 'count'] += 1 df.loc[df['15/16']['Apps']&gt;9.0, 'count'] += 1 df.loc[df['14/15']['Apps']&gt;9.0, 'count'] += 1 df.loc[df['13/14']['Apps']&gt;9.0, 'count'] += 1 df.loc[df['12/13']['Apps']&gt;9.0, 'count'] += 1 df[df['count']&gt;3]
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49795287
type: Answer
answers question: http://stackoverflow.com/q/49795287

http://stackoverflow.com/comment/95945924
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49938988
has text: Need to activate the virtual environment by `activate path/to/your/virtualenv`. For more information https://virtualenv.pypa.io/en/stable/userguide/#activate-script

http://stackoverflow.com/q/49849023
has title: Filter data through multiple columns and print rows?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49849483
has answer: http://stackoverflow.com/a/49849154
tagged with: python
has comment: http://stackoverflow.com/comment/86712706
score: 0
answer count: 2
tagged with: pandas
has body: Kind of a follow up on my last question. So I got this data in .csv file that looks like: id,first_name,last_name,email,gender,ip_address,birthday 1,Ced,Begwell,cbegwell0@google.ca,Male,134.107.135.233,17/10/1978 2,Nataline,Cheatle,ncheatle1@msn.com,Female,189.106.181.194,26/06/1989 3,Laverna,Hamlen,lhamlen2@dot.gov,Female,52.165.62.174,24/04/1990 4,Gawen,Gillfillan,ggillfillan3@hp.com,Male,83.249.190.232,31/10/1984 5,Syd,Gilfether,sgilfether4@china.com.cn,Male,180.153.199.106,11/07/1995 What I want is that when the python program runs it asks the user what keywords to search for. It then takes all keywords entered ( maybe they are stored in a list???), then prints out all rows that contain all keywords no matter what column that keyword is in. I've been playing around with csv and pandas, and have been googling for hours but just can't seem to get it to work like I want it to. I'm still kinda new to python3. Please help. **Edit to show what I've got so far: import csv # Asks for search criteria from user search_parts = input("Enter search criteria:\n").split(",") # Opens csv data file file = csv.reader(open("MOCK_DATA.csv")) # Go over each row and print it if it contains user input. for row in file: if all([x in row for x in search_parts]): print(row) Works great if only searching by one keyword. But I want the choice of filtering by one or mutiple keywords.
type: Question
has comment: http://stackoverflow.com/comment/86712936

http://stackoverflow.com/q/49858009
has comment: http://stackoverflow.com/comment/86730859
has comment: http://stackoverflow.com/comment/86731063
upvote count: 1
linked to: http://stackoverflow.com/q/36405994
favorite count: 0
tagged with: python-3.x
has body: I have the following error builtins.AssertionError: 12 columns passed, passed data had 6 columns The last 6 Columns datawise will vary so Im happy to have None in the areas the data is missing. However I cant seem to find a simple way to do this, im pretty sure there must be an option for it but I cant see it in the docs or any google searches. Any help would be apprecaited. I would like to reiterate that I know what is causing the problem and I know data is missing from coloumns. I would like to ignore missing data and am ahppy to have None or NaN in the output csv.
has title: Is there a way to allow NaN values to be writen to CSV from panadas?
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86735708
has answer: http://stackoverflow.com/a/49858441
answer count: 1
score: -1
has comment: http://stackoverflow.com/comment/86730988
has comment: http://stackoverflow.com/comment/86730700
has comment: http://stackoverflow.com/comment/86731162
tagged with: pandas
has comment: http://stackoverflow.com/comment/86730592
downvote count: 2
has comment: http://stackoverflow.com/comment/86730931

http://stackoverflow.com/q/49832781
has title: How to tell interaction window which y value to display with twin axes?
tagged with: matplotlib-widget
tagged with: matplotlib
has body: I'm working on a Python script to display the results of musical pitch analysis. I have twinned the first axis and supplied a custom ticker so I can view the results in both Hz and Pitch. The relevant code, based on the example at https://matplotlib.org/2.1.0/gallery/api/two_scales.html is: fig, ax1 = plt.subplots(1,1) ax1.set_xlabel('time') ax1.set_ylabel('f0/Hz') # read and process data, draw green rectangle on ax1... then ax1.plot(t, f0) # Make a second y axis with note names on it. ax2 = ax1.twinx() ax2.set_ylabel('Pitch') ax2.set_ylim(ax1.get_ylim()) ax2.yaxis.set_major_locator(PitchTicker(19,numticks=30)) ax2.yaxis.set_major_formatter(ticker.FuncFormatter(lambda f, pos: hz_to_tuning19(f)[0])) # All other code refers to ax1, then... plt.title('[{}:{}] {}'.format(first,last,title)) fig.tight_layout() plt.show() This working as desired except in one respect, which is unfortunately a major issue for the end user. When the window is displayed and the pointer is moved over the axes, the Y value shown is that from the twinned axis, ax2, not from the first one. Interaction window with twinned axes: The Y value given in the bottom right hand corner is the value given by ax2's ticker.FuncFormatter, and I can't find a way to make it display ax1's value instead so that the value of f0 in Hz gets displayed. I have found that one possible solution is to draw the line and triangle on ax1, then create ax2 and say ax1.yaxis.tick_right() ax2.yaxis.tick_left() ax1.yaxis.set_label_position('right') ax2.yaxis.set_label_position('left') but this seems rather counter-intuitive and feels like it might break in future. I have tried calling plt.sca(ax1) and even ax2.set_axisbelow(True) before plt.show() but this doesn't change anything. Is there an official way to tell the interaction window which X and Y values to display when reporting mouse position?
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/91347868
linked to: http://stackoverflow.com/q/21583965
has comment: http://stackoverflow.com/comment/91325831
score: 0

http://stackoverflow.com/comment/86556803
type: AnswerComment
comment on: http://stackoverflow.com/a/49770870
has text: Yeah, with `remove(x)` only one occurrence of `x` is removed.
type: Comment
score: 0

http://stackoverflow.com/q/49804514
upvote count: 2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49903502
tagged with: gpio
accepted answer: http://stackoverflow.com/a/49903502
answer count: 1
favorite count: 0
has title: Python how to read an anonymous linux file for a GPIO event
score: 2
type: AnsweredQuestion
tagged with: embedded-linux
downvote count: 0
tagged with: events
tagged with: python
has body: Working on a python 3 implementation of the new linux gpio implementation. The initial setup works great: class gpioevent_request(ctypes.Structure): _pack_ = 1 _fields_ = [ ('lineoffset', ctypes.c_ulong), ('handleflags', ctypes.c_ulong), ('eventflags', ctypes.c_ulong), ('consumer_label', ctypes.c_char * 32), ('fd', ctypes.c_int), ] class gpioevent_data(ctypes.Structure): _pack_ = 1 _fields_ = [ ('timestamp', ctypes.c_ulonglong), ('id', ctypes.c_ulong), ] self.event = gpioevent_request() self.eventData = gpioevent_data() ... # Open /dev/gpiochipx with os.open and set up the event structure ... fcntl.ioctl(self._fd, GPIO_GET_LINEEVENT_IOCTL, self.event) My challenge comes when I try to read the event information that is stored in the anonymous linux file created by the GPIO_GET_LINEEVENT_IOCTL call. If I try os.read I get an invalid argument response: os.read(self.event.fd, bytesToRead) If I try libc read then it will read the file but I get all zeros for my data (timestamp and id): import ctypes.util libc = ctypes.CDLL(ctypes.util.find_library('c')) self.f_read = libc.read self.f_read(self.event.fd, ctypes.byref(self.eventData), ctypes.sizeof(self.eventData)) using epoll does seem to trigger the file on the rising or falling edge on my input pin but it works intermittently: p = select.epoll() p.register(self.event.fd, select.EPOLLIN | select.EPOLLET | select.EPOLLPRI) Any insight is appreciated greatly.
type: Question

http://stackoverflow.com/q/49883361
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/86782943
answer count: 2
has comment: http://stackoverflow.com/comment/86782689
downvote count: 3
has body: How can I extract 249.30 251.50 252.55 246.80 248.20 from below code using python (assuming that the number of digits are variable i.e in place of 249.30 I can have say 2.4 or 2490.30)? &lt;html&gt; &lt;body&gt; &lt;p&gt; BSE##B#As on 17 Apr 18 | 16:00@C#7@P#@HL#249.30,251.50,252.55,246.80,248.20,Listed &lt;/p&gt; &lt;/body&gt; &lt;/html&gt;
has comment: http://stackoverflow.com/comment/86782999
has answer: http://stackoverflow.com/a/49883482
possible better answer: http://stackoverflow.com/a/49883482
has answer: http://stackoverflow.com/a/49883806
favorite count: 0
has title: Extracting variable data from p tag
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
score: -3
tagged with: python
accepted answer: http://stackoverflow.com/a/49883806

http://stackoverflow.com/a/49837064
score: 1
answers question: http://stackoverflow.com/q/49835742
has comment: http://stackoverflow.com/comment/86693712
type: Answer
has comment: http://stackoverflow.com/comment/86709352
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86700434
has body: For responsive behaviour, you have two options: you can write a on_message event handler, or use the discord.ext.commands module. I recommend using commands, as it's more powerful and doesn't keep everything in a single coroutine. from discord.ext.commands import Bot bot = Bot(command_prefix='!') @bot.event async def on_ready(): print("I'm ready.") global target_channel target_channel = bot.get_channel("412678093006831617") @bot.command() async def send(*, message): global target_channel await bot.send_message(channel, message) This would be called with !send Some message. The *, message syntax just tells the bot not to try and parse the message contents further.
has comment: http://stackoverflow.com/comment/86699900

http://stackoverflow.com/comment/86705766
score: 2
type: Comment
type: QuestionComment
has text: @R2RT, the reason to test is ensure the options has been used will not get changed without a warning. The purpose is not to test `argparse`.
comment on: http://stackoverflow.com/q/49838007

http://stackoverflow.com/a/49887903
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86801661
has body: Aside from reading &amp; writing to file, maybe this will point you in the right direction: import yaml document = """ --- '001': name: Ben email: ben@test.com '002': name: Lisa email: lisa@test.com '003': name: Alex email: alex@test.com """ phones = {'001': '000-111-2222', '002': '000-111-2223', '003': '000-111-2224'} doc = yaml.safe_load(document) for k, v in phones.items(): # Might want to check that 'doc[k]' exists doc[k]['phone'] = v print(yaml.safe_dump(doc, default_flow_style=False, explicit_start=True)) Output: '001': email: ben@test.com name: Ben phone: 000-111-2222 '002': email: lisa@test.com name: Lisa phone: 000-111-2223 '003': email: alex@test.com name: Alex phone: 000-111-2224
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86792698
has comment: http://stackoverflow.com/comment/86841384
answers question: http://stackoverflow.com/q/49887681
has comment: http://stackoverflow.com/comment/86793423
has comment: http://stackoverflow.com/comment/86832913

http://stackoverflow.com/q/49841577
has answer: http://stackoverflow.com/a/49841659
downvote count: 1
favorite count: 0
type: Question
tagged with: ctypes
score: 8
upvote count: 9
type: UnansweredQuestion
has title: Updating a variable by its id within python
tagged with: python
tagged with: pointers
has answer: http://stackoverflow.com/a/78953191
answer count: 3
has body: I know how to get the value of a variable by its id in Python like: a = "hello world!" ctypes.cast(id(a), ctypes.py_object).value I wonder if it possible to overwrite the variables value by id? The simplest way, this one: ctypes.cast(id(a), ctypes.py_object).value = "new value" does not work.
has answer: http://stackoverflow.com/a/49845506

tensorflow-transform
tags question: http://stackoverflow.com/q/49911534
type: Tag
tag name: tensorflow-transform

http://stackoverflow.com/comment/86775719
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49879862
type: QuestionComment
has text: Use `==` to compare strings for equality ;-)

http://stackoverflow.com/comment/86818854
has text: Oh that would have worked too. Just put that working code back into the class and it should work. The problem was the way you were binding the event handler, not the class. I just decided to make the code simpler at the same time.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49885303

http://stackoverflow.com/a/49871206
score: 0
has comment: http://stackoverflow.com/comment/126355588
answers question: http://stackoverflow.com/q/49849475
has body: Add below code to the initial file for tests. Then it should work in either Pycharm or terminal. import sys import os curPath = os.path.abspath(os.path.dirname(__file__)) rootPath = os.path.split(curPath)[0] sys.path.append(rootPath)
type: Answer

http://stackoverflow.com/q/49903165
has answer: http://stackoverflow.com/a/49903324
linked to: http://stackoverflow.com/q/56860
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86821943
tagged with: oop
has comment: http://stackoverflow.com/comment/86822342
has comment: http://stackoverflow.com/comment/86822481
tagged with: python
upvote count: 6
linked to: http://stackoverflow.com/q/4382945
has comment: http://stackoverflow.com/comment/86822099
tagged with: class
has comment: http://stackoverflow.com/comment/86822262
accepted answer: http://stackoverflow.com/a/49903575
has title: Check if a function raises NotImplementedError before calling it in Python
type: AnsweredQuestion
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/49903575
has body: I have the following simplified scheme: class NetworkAnalyzer(object): def __init__(self): print('is _score_funct implemented?') @staticmethod def _score_funct(network): raise NotImplementedError class LS(NetworkAnalyzer): @staticmethod def _score_funct(network): return network and I am looking for what I should use instead of print('is _score_funct implemented?') in order to figure out if a subclass has already implemented _score_funct(network) or not. Note: If there is a more pythonic/conventional way of structuring the code, I would also appreciate its mention. The reason I defined it this way is, some NetworkAnalyzer subclasses have _score_funct in their definition, and the ones that dont have it will have different initialization of variables although they will have the same structure
has comment: http://stackoverflow.com/comment/86822356
has comment: http://stackoverflow.com/comment/86822261
possible better answer: http://stackoverflow.com/a/49903324
downvote count: 0
score: 6

http://stackoverflow.com/a/49903694
type: Answer
accepted answer of: http://stackoverflow.com/q/49903319
upvote count: 6
answers question: http://stackoverflow.com/q/49903319
downvote count: 1
score: 5
type: AcceptedAnswer
has body: The modulus of negative L will do it. pad = -L % N

http://stackoverflow.com/comment/135471735
has text: Couldn't edit (too many pending edits). The request needs to be a POST request: r = requests.post(url + "/sendMessage", params=params)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/67152755
type: Comment

http://stackoverflow.com/q/49779890
linked to: http://stackoverflow.com/q/2823315
has body: So Lets say I have a dictionary it contains: {'h': 2, 'e': 1, 'l': 4, 'o': 4, ',': 1, ' ': 3, 'w': 2, 'r': 1, 'd': 1, '!': 1, 'n': 1, 'g': 1, '.': 3, '\n': 1} and I want to swap my keys and values so that way the frequency is in the front. What would be the best way to do this. I tried this. my_dict2 = {y: x for x, y in letter_frequency.items()} and got {2: 'w', 1: '\n', 4: 'o', 3: '.'} so it's clearly not working. Here is my full code to read in the letter frequency. If there is a way to do it without swamping the keys and values that might be best. word_list = [] file = open(file_name, 'rU') for line in file: for word in line: word_list.append(word); letter_frequency = {} for word in word_list: for letter in word: keys = letter_frequency.keys() if letter in keys: letter_frequency[letter] += 1 else: letter_frequency[letter] = 1 print(letter_frequency) my_dict2 = {y: x for x, y in letter_frequency.items()} print(my_dict2) return letter_frequency
answer count: 1
has comment: http://stackoverflow.com/comment/86575148
has comment: http://stackoverflow.com/comment/86575336
duplicate of: http://stackoverflow.com/q/2823315
type: Question
has answer: http://stackoverflow.com/a/49779999
type: UnansweredQuestion
has title: swaping keys and values in python
tagged with: python
tagged with: dictionary
score: 0
has comment: http://stackoverflow.com/comment/86575410

http://stackoverflow.com/comment/86809964
type: QuestionComment
type: Comment
has text: i am using window 10. and when i run the server then this error is occure help me anyone please... Thank you in advance
score: 0
comment on: http://stackoverflow.com/q/49897357

http://stackoverflow.com/comment/86803752
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49877645
has text: Yes, I agree with you Koustav, this is also exactly the output from the model.summary() in my case. My problem is that I do not know how to create the target batches with this shape in this case, because I use from Keras's documentation specifically for images&masks, which produce an output of dimension 4(for the target shape)(the generator produces such output). This is what I do not know, how to modify in(see image [4]) to correctly fit it in (see image[5]), the import of the dataset in order to fit it correctly to my architecture. If you know how to do that, I would be very grateful.
type: AnswerComment

http://stackoverflow.com/comment/86766245
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49874482
has text: [Here](https://stackoverflow.com/questions/43463431/custom-logarithmic-axis-scaling-in-matplotlib) or [here](https://stackoverflow.com/questions/45306099/how-to-put-different-in-magnitude-values-at-same-distance-on-x-axis) is how you create a custom scale. This will not align your ticks. For that you would in addition need a custom locator (in this case probably a `FixedLocator`). This seems a bit overkill, so maybe you don't need a proper scale at all? Still not too clear from the question.
score: 0

http://stackoverflow.com/comment/86849005
has text: I did that. thanks Rick..
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49914888

http://stackoverflow.com/q/49795525
favorite count: 0
type: Question
tagged with: ajax
score: 14
accepted answer: http://stackoverflow.com/a/49797251
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49795599
has answer: http://stackoverflow.com/a/56767987
possible better answer: http://stackoverflow.com/a/56767987
type: AnsweredQuestion
has title: TypeError: Object of type 'int32' is not JSON serializable
tagged with: django-views
upvote count: 14
answer count: 3
has answer: http://stackoverflow.com/a/49797251
downvote count: 0
has body: I have to select those symptoms which is in the dictionary with the symptoms already posted.It works fine.But for some symptoms typeError is showing in command prompt and also all are getting printed in command prompt but not in html page. Here is my code views.py def predict(request): sym=request.POST.getlist('symptoms[]') sym=list(map(int,sym)) diseaseArray=[] diseaseArray=np.array(diseaseArray,dtype=int) dictArray=[] for dicti in dictionary: if (set(sym)&lt;= set(dicti['symptoms']) and len(sym)!= 0) or [x for x in sym if x in dicti['primary']]: diseaseArray=np.append(diseaseArray,dicti['primary']) diseaseArray=np.append(diseaseArray,dicti['symptoms']) diseaseArray=list(set(diseaseArray)) print(diseaseArray) for i in diseaseArray: if i not in sym: dict={'id':i} dictArray.append(dict) print(dictArray) for j in dictArray: symptoms=Symptom.objects.get(syd=j['id']) j['name']=symptoms.symptoms print(j['name']) print(len(dictArray)) return JsonResponse(dictArray,safe=False) template $('.js-example-basic-multiple').change(function(){ $('#suggestion-list').html(''); $('#suggestion').removeClass('invisible'); $.ajax({ url:"/predict", method:"post", data:{ symptoms: $('.js-example-basic-multiple').val(), }, success: function(data){ data.forEach(function(disease){ console.log(disease.name) $('#suggestion-list').append('&lt;li&gt;'+disease.name+'&lt;li&gt;') $('#suggestion-list').removeClass('invisible'); }); } });

http://stackoverflow.com/q/49884400
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/86784881
favorite count: 0
has answer: http://stackoverflow.com/a/49884496
type: Question
has title: How do I find the maximum value in an array within a dataframe column?
has answer: http://stackoverflow.com/a/49885073
possible better answer: http://stackoverflow.com/a/49885073
has comment: http://stackoverflow.com/comment/86784835
has answer: http://stackoverflow.com/a/49884435
accepted answer: http://stackoverflow.com/a/49884435
has body: I have a dataframe (df) that looks like this: a b loc.1 [1, 2, 3, 4, 7, 5, 6] loc.2 [3, 4, 3, 7, 7, 8, 6] loc.3 [1, 4, 3, 1, 7, 8, 6] ... I want to find the maximum of the array in column b and append this to the original data frame. My thought was something like this: for line in df: split = map(float,b.split(',')) count_max = max(split) print count Ideal output should be: a b max_val loc.1 [1, 2, 3, 4, 7, 5, 6] 7 loc.2 [3, 4, 3, 7, 7, 8, 6] 8 loc.3 [1, 4, 3, 1, 7, 8, 6] 8 ... But this does not work, as I cannot use b.split as it is not defined...
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/comment/86547475
comment on: http://stackoverflow.com/q/49765898
type: Comment
type: QuestionComment
score: 0
has text: which library are you using ? can you please provide more code you have tried ?

http://stackoverflow.com/q/49888875
has comment: http://stackoverflow.com/comment/86793955
has body: Apologies if this is a silly question. I have a list of potential dictionary keys here: form_fields = ['sex', 'birth', 'location', 'politics'] I am currently manually adding values to these keys like so: self.participant.vars["sex"] = [Constants.fields_dict["sex"][0], Constants.fields_dict["sex"][1], self.player.name] self.participant.vars["birth"] = [Constants.fields_dict["birth"][0], Constants.fields_dict["birth"][1],self.player.age] self.participant.vars["location"] = [Constants.fields_dict["location"][0], Constants.fields_dict["location"][1],self.player.politics] I'd like to be able to do a use a for loop to do this all at once like so: for i in form_fields: self.participant.vars[i] = [Constants.fields_dict[i][0], Constants.fields_dict[i][1], self.player.`i`] Obviously, however, I can't reference the object self.player.i like that. Is there a way to reference that object dynamically?
type: AnsweredQuestion
score: 0
tagged with: python
type: Question
has title: Python: Refer to objects dynamically
answer count: 1
accepted answer: http://stackoverflow.com/a/49888953
has answer: http://stackoverflow.com/a/49888953
has comment: http://stackoverflow.com/comment/86793980

http://stackoverflow.com/q/49829466
has body: From a Jupyter Notebook running Python 3, I'm running the following code to try and insert the text "a search term" into the Google search box with Selenium [1]: import os from selenium import webdriver from selenium.webdriver.common.keys import Keys # get the path of ChromeDriverServer chrome_driver_path = os.getcwd() + "/chromedriver 2" # create a new Chrome session driver = webdriver.Chrome(chrome_driver_path) # navigate to the application home page driver.get("https://www.google.com") # get the search textbox search_field = driver.find_element_by_name("q") # enter search keyword and submit search_field.send_keys("a search term") However, when I run the code, I just get a new browser with the Google homepage open but the text isn't inserted into the search bar. What am I missing here? [1] Make sure to have the right webdriver installed -- I initially installed the 32-bit version but then had to install the 64-bit version, since the "2".
type: UnansweredQuestion
tagged with: python
tagged with: jupyter-notebook
score: 0
answer count: 1
tagged with: selenium
has title: Selenium from Jupyter Notebook not sending keys
type: Question
has answer: http://stackoverflow.com/a/49829526

http://stackoverflow.com/q/49829023
accepted answer: http://stackoverflow.com/a/49830789
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I'm currently trying to train a data set with a decision tree classifier but I couldn't get the train_test_split to work. From the code below CS is the target output and EN SN JT FT PW YR LO LA are features input. All variables that went through OHL are in sparse matrix format whereas the other are in array taken straight from the dataframe. def OHL(x, column): #OneHotEncoder le = LabelEncoder() enc = OneHotEncoder() Labeled = le.fit_transform(x[column].astype(str)) return enc.fit_transform(Labeled.reshape(-1,1)) ###------------------------------------------------------------------------ df = pd.read_csv('h1b_kaggle.csv') df = df.drop(['Unnamed: 0','WORKSITE'],1) ###------------------------------------------------------------------------ CS = OHL(df, 'CASE_STATUS') EN = OHL(df, 'EMPLOYER_NAME') SN = OHL(df, 'SOC_NAME') JT = OHL(df, 'JOB_TITLE') FT = OHL(df, 'FULL_TIME_POSITION') PW = np.array(df['PREVAILING_WAGE']) YR = OHL(df, 'YEAR') LO = np.array(df['lon']) LA = np.array(df['lat'])
score: 10
tagged with: dataframe
tagged with: python
upvote count: 11
has comment: http://stackoverflow.com/comment/86691904
has title: train_test_split with multiple features
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86678156
tagged with: pandas
answer count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/49830789

http://stackoverflow.com/comment/86714435
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49849936
has text: Operator `*` is _greedy_. Use `*?` instead. Or, better yet, insert a `\s` in the regex before the number.
score: 2

http://stackoverflow.com/comment/86835515
has text: Create a smaller image and post that one's base64 code. You can also try to upload one of the damaged PNGs on a public server and provide a link (I don't think you can attached a 'damaged' file to an SO post).
comment on: http://stackoverflow.com/q/49906127
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86828887
type: Comment
comment on: http://stackoverflow.com/q/49906366
score: 0
type: QuestionComment
has text: Hah thank you!! I cant believe I missed this, I spent some time looking before asking for help too.

http://stackoverflow.com/q/49799931
has answer: http://stackoverflow.com/a/49800594
accepted answer: http://stackoverflow.com/a/49800538
linked to: http://stackoverflow.com/q/26332238
score: -2
upvote count: 5
has answer: http://stackoverflow.com/a/49800538
tagged with: python
tagged with: regex
has title: Python regular expression to remove all text between <> symbols
duplicate of: http://stackoverflow.com/q/26332238
type: AnsweredQuestion
has body: I have a set of sentences of the form "Today is a <unk> sunny day and <num> children are playing outside " I would like to remove all text between <> symbols, so that the output sentence is "Today is a sunny day and children are playing outside" How can I do this using a regular expression in Python?
possible better answer: http://stackoverflow.com/a/49800185
answer count: 3
has answer: http://stackoverflow.com/a/49800185
tagged with: string
downvote count: 7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86614986

http://stackoverflow.com/comment/86845100
comment on: http://stackoverflow.com/a/49914623
score: 0
type: AnswerComment
has text: I do agree. Some foor for thoughts: https://stackoverflow.com/questions/14431118/how-to-fix-this-iterative-python-code-and-reduce-repetition
type: Comment

http://stackoverflow.com/q/49777172
downvote count: 4
has answer: http://stackoverflow.com/a/49778313
has title: Inserting value in dictionaries
upvote count: 0
answer count: 2
score: -4
favorite count: 0
has comment: http://stackoverflow.com/comment/86569574
type: Question
has comment: http://stackoverflow.com/comment/86571530
tagged with: python
type: UnansweredQuestion
has body: lloyd = {"name":"Lloyd", "homework":[], "quizzes":[], "tests":[]} alice = {"name":"Alice", "homework":[], "quizzes":[], "tests":[]} tyler = {"name":"Tyler", "homework":[], "quizzes":[], "tests":[]} I am new to programming, at the moment I am learning python programming from codeacademy and udemy.com. Here I have question, since every dictionary above have key name "homework" I want to insert "homework" value as Homework: 90.0, 97.0, 75.0, 92.0. Is it possible to insert 3 dictionary homework value with a same value in a single code ?
has comment: http://stackoverflow.com/comment/86572494
has answer: http://stackoverflow.com/a/49777212

http://stackoverflow.com/comment/86588532
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49786276
score: 0
has text: @Sraw check the edit, and top of the page.

http://stackoverflow.com/comment/86663256
score: 0
type: Comment
type: QuestionComment
has text: Thanks for providing a complete question with a reproducible example. It's rare to see that from a new user, and a real pleasure. I'll write you a complete answer momentarily.
comment on: http://stackoverflow.com/q/49823699

http://stackoverflow.com/q/49827976
tagged with: pyqt
tagged with: pyqt4
answer count: 1
tagged with: python
has body: I created a QGraphicsPathItem by passing the constructor a QPainterPath with about 10 QPoint's in it. Now how can I move the points in the path around? For example: This to create a box: path = QtGui.QPainterPath() path.moveTo(0, 0) path.lineTo(10, 0) path.lineTo(10, 10) path.lineTo(0, 10) line = QtGui.QGraphicsPathItem() line.setPath(path) Now after some time goes by I want to make this box wider by grabbing the top &amp; bottom right points and moving them right. How can I access the points? The Qt documentation for QPainterPath indicates that path.elementAt(i) is the way to access data within the path, but that returns a QElementObject and I could not find much documentation for an "element object", and it is definitely not a QPointF (which is what I would expect to get...right?). So how can I get a QPointF out of this element? And once I do get the points, is it fine to just call their QPointF.setX() and QPointF.setY() and the line will re-draw, or do I need to re-set it to the QGraphicsPathItem with a new call to line.setPath()? As a note this is PyQt4, python 2.7. However I'll take a C++ answer if you have it, though I don't know C++ at all it seems pretty easy to translate.
type: AnsweredQuestion
tagged with: qpainterpath
upvote count: 1
score: 1
has title: how can I move the points in a Qt QPainterPath after creation?
has answer: http://stackoverflow.com/a/49828070
accepted answer: http://stackoverflow.com/a/49828070
favorite count: 0
type: Question
downvote count: 0
tagged with: qgraphicspathitem

http://stackoverflow.com/comment/116007534
type: AnswerComment
comment on: http://stackoverflow.com/a/49896477
has text: @martineau I've updated the answer to include this option too.
type: Comment
score: 0

http://stackoverflow.com/q/49762808
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: python
has body: Suppose I have 100,000 users. I want to create a csv file with 100,000 rows and K columns. K is expected to be around a few hundred. Each row contains one user's data, and each column is one variable. I create such csv data with a for loop, of which each iteration constructs a dictionary whose keys are the variable names. If I knew the K variables names, I can use csv.DictWriter to append new row. The problem is that I don't know the variables' names or the number K. One way is to use pandas.DataFrame.append function. I don't like this one, because pandas' documentation says append is slow for iterative appending. I cannot use loc as suggested somewhere, because the number of columns varies. My current strategy is to create three list. list1 is to store variable names; list2 is to save values; and list3 is to save row index. Append list in python within loop is easy. From list3, I crate a list of unique row indexes, which will be used as the field names of the csv. For each variable, I create a dictionary whose keys are row indexes, and the corresponding value is the value of the variable in that row. Then I use csv.DictWriter to create the csv file. The last step is to transpose the created csv file. I am glad to hear improvement suggestions. # Example: three rows (r1, r2, r3) and four variables (n1, n2, n3, n4) list1 = ['n1', 'n2', 'n3', 'n2', 'n3', 'n3', 'n4'] # n* is variable name list2 = ['v11', 'v12', 'v13', 'v22', 'v23', 'v33', 'v34'] # v* is value list3 = ['r1', 'r1', 'r1', 'r2', 'r2', 'r3', 'r3'] # v* is row id # Convert to data of the following format # n1 n2 n3 n4 # v11 v12 v13 NA # NA v22 v23 NA # NA NA v33 v34 # MY CURRENT WORKFLOW: # 1. create a list of unique row id from collections import OrderedDict rowIds = list(OrderedDict.fromkeys(list3)) # this preserve row id order # 2. create a list of unique variable names names = list(OrderedDict.fromkeys(list1)) # 3. For each variable n*, create a dictionary whose keys are row id, and # whose values are val…
has comment: http://stackoverflow.com/comment/86541596
has answer: http://stackoverflow.com/a/49926201
score: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86541502
has comment: http://stackoverflow.com/comment/86541266
has title: Efficient way to create csv iteratively in python

http://stackoverflow.com/comment/86800189
score: 0
has text: @pissall there is no loop to break out of. Easiest fix is to just import sys and call sys.exit(0)
comment on: http://stackoverflow.com/q/49892030
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50365036
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49802164
score: 0
type: Answer
has body: Apparently the answer is super simple(!), there is nothing special we need to do - SQLAlchemy support it by itself. Meaning - you can set the specific column to be INT in the DB, but enum in the model, and when querying the DB SQLAlchemy will convert it by itself. same goes when inserting to the DB :) I used it with declarative enum, it means it's values are strings (and it has a function - from_string()). So once I used VARCHAR columns, it worked like a charm!
accepted answer of: http://stackoverflow.com/q/49802164

http://stackoverflow.com/comment/86606313
score: 0
has text: How looks lookup Series? What is value for `6` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/49795683
type: Comment

http://stackoverflow.com/a/49909127
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/49909039
type: Answer
has body: You could simplify your code by using advanced slicing on strings s = input().strip() print(s[::2], s[1::2]) For s[i:j:k] i is the start index, if omitted, it just uses 0 j is the end index, if omitted, it just uses len(s) k is the step value, so it will iterate though the sequence by that amount. So for even indexed characters, we start at the 0 index and step through every other character. For odd indexed characters, we just start at the 1 index and get every other character.
downvote count: 0

http://stackoverflow.com/comment/86817357
type: QuestionComment
comment on: http://stackoverflow.com/q/49900892
score: 0
has text: Please post a [mcve]. We can't debug your code if we can only see 6 lines of it.
type: Comment

http://stackoverflow.com/comment/133904387
has text: The `justify=` parameter justifies *column labels* (see [docs](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html)).
score: 0
comment on: http://stackoverflow.com/a/75880231
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49898271
type: UnansweredQuestion
tagged with: amazon-rds
has comment: http://stackoverflow.com/comment/86812440
downvote count: 0
score: 6
has title: Behind a proxy: Flask SQLAlchemy connect to Postgres
tagged with: flask-sqlalchemy
favorite count: 0
tagged with: postgresql
has body: I have a postgres instance running on a remote (AWS). I am on a corporate network using a proxy. I can use the tsocks package to connect to the postgres instance through a SOCKS5 proxy. Is there anyway for me to force FlaskSql to do the interactions through the proxy? Notes I have tried setting the proxy on the requests module and can get that to work. I have tried some things with the PySocks module, e.g this without any good results. Can you set which socket SQLAlchemy uses? I have set http_proxy and https_proxy as well, but it is not enough for tcp connections.
linked to: http://stackoverflow.com/q/11019179
tagged with: python
upvote count: 6
type: Question
has comment: http://stackoverflow.com/comment/86815203
answer count: 0

http://stackoverflow.com/comment/86705524
comment on: http://stackoverflow.com/q/49845285
type: QuestionComment
has text: In that case, you might have to show us some of the json. Not all 20 keys and all rows, maybe 4 keys for 4 rows is enough. Then we can suggest a better way for you to build your dataframe.
type: Comment
score: 0

http://stackoverflow.com/q/49810470
has comment: http://stackoverflow.com/comment/86941625
downvote count: 0
tagged with: bokeh
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86934629
type: Question
has body: Is it possible to build an API which can call bokeh's 'components' function to serve the and tags to be served at the front end ? For ex the following code is output of the components function: Bokeh Scatter Plots Given that only the docs_json and render_items are the only changing values, would it be possible to pass them to front end using an API ? Furthermore build the bokeh plots at the front end itself ?
has comment: http://stackoverflow.com/comment/86931731
has comment: http://stackoverflow.com/comment/86929329
type: UnansweredQuestion
has title: Bokeh Components function, embed through an API
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/86927799
has comment: http://stackoverflow.com/comment/86936179
has comment: http://stackoverflow.com/comment/86935885
tagged with: pandas
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/86903008

amazon-web-services
tags question: http://stackoverflow.com/q/49881550
tags question: http://stackoverflow.com/q/49807460
tags question: http://stackoverflow.com/q/49761497
tags question: http://stackoverflow.com/q/49880760
tags question: http://stackoverflow.com/q/49820453
tags question: http://stackoverflow.com/q/49894758
tags question: http://stackoverflow.com/q/49784028
tags question: http://stackoverflow.com/q/49832133
tags question: http://stackoverflow.com/q/49868725
tags question: http://stackoverflow.com/q/49870002
tags question: http://stackoverflow.com/q/49762291
tags question: http://stackoverflow.com/q/49825638
tags question: http://stackoverflow.com/q/49792499
tags question: http://stackoverflow.com/q/49864209
tags question: http://stackoverflow.com/q/49896513
tags question: http://stackoverflow.com/q/49797674
tags question: http://stackoverflow.com/q/49759940
tags question: http://stackoverflow.com/q/49799318
tags question: http://stackoverflow.com/q/49807795
tags question: http://stackoverflow.com/q/49885463
tags question: http://stackoverflow.com/q/49772151
tags question: http://stackoverflow.com/q/49908912
tags question: http://stackoverflow.com/q/49784340
tags question: http://stackoverflow.com/q/49878521
tags question: http://stackoverflow.com/q/49870228
tags question: http://stackoverflow.com/q/49800725
tags question: http://stackoverflow.com/q/49868348
tags question: http://stackoverflow.com/q/49809138
type: Tag
tags question: http://stackoverflow.com/q/49827177
tags question: http://stackoverflow.com/q/49782230
tags question: http://stackoverflow.com/q/49768961
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/49868678
tags question: http://stackoverflow.com/q/49867759
tags question: http://stackoverflow.com/q/49855087

http://stackoverflow.com/comment/86545640
type: QuestionComment
has text: Python 2 or Python 3?
comment on: http://stackoverflow.com/q/49765019
score: 1
type: Comment

http://stackoverflow.com/comment/86590894
comment on: http://stackoverflow.com/a/49787880
type: Comment
type: AnswerComment
score: 0
has text: The users aren't going to give me regex to strip off, they will give actual values . . . so I don't need escape at all.

join
tags question: http://stackoverflow.com/q/49868822
type: Tag
tag name: join
tags question: http://stackoverflow.com/q/49802004
tags question: http://stackoverflow.com/q/49826378
tags question: http://stackoverflow.com/q/49886199
tags question: http://stackoverflow.com/q/49873535
tags question: http://stackoverflow.com/q/49759397

http://stackoverflow.com/comment/86616822
type: AnswerComment
comment on: http://stackoverflow.com/a/49800632
has text: ok I did what you said sir and the output is "/root" . But why? I have the py file in specific subfolders in my Desktop, I will try putting the csv file in the root folder or using the relative path (even tho I've already tried that)
type: Comment
score: 0

flask-sqlalchemy
tags question: http://stackoverflow.com/q/49811492
tags question: http://stackoverflow.com/q/49763571
tags question: http://stackoverflow.com/q/49887484
tags question: http://stackoverflow.com/q/49784883
tags question: http://stackoverflow.com/q/49844449
tags question: http://stackoverflow.com/q/49868005
tags question: http://stackoverflow.com/q/49905006
tags question: http://stackoverflow.com/q/49783442
tags question: http://stackoverflow.com/q/49776619
tags question: http://stackoverflow.com/q/49794899
type: Tag
tags question: http://stackoverflow.com/q/49861846
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/49820972
tags question: http://stackoverflow.com/q/49893974
tags question: http://stackoverflow.com/q/49802142
tags question: http://stackoverflow.com/q/49845987
tags question: http://stackoverflow.com/q/49797786
tags question: http://stackoverflow.com/q/49898271

http://stackoverflow.com/comment/129313985
type: Comment
score: 2
has text: Restrictions: returns some or all (up to 1,000) of the objects in a bucket with each request https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
type: AnswerComment
comment on: http://stackoverflow.com/a/56540890

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

http://stackoverflow.com/q/49913804
possible better answer: http://stackoverflow.com/a/49913950
has title: NameError after show some data
type: AnsweredQuestion
tagged with: nameerror
score: 0
accepted answer: http://stackoverflow.com/a/49913910
tagged with: pandas
type: Question
has answer: http://stackoverflow.com/a/49913950
answer count: 2
has body: X_train, X_test, y_train, y_test = train_test_split(x1, x2, test_size=0.2) d=len(X_train) for i in range(d): print(x2[i]) I am using a dataset with 2500 data when i run this code this error is happen what is wrong with my code can you help me with that?? This show some data than the error 7.9 7.82 7.67 7.7 8.65 9.49 9.4 9.23 8.87 9.7 9.87 9.2 8.85 8.9 8.9 8.95 8.93 8.89 9.15 9.44 9.65 11.0 11.12 11.3 11.29 11.19 11.1 11.15 11.6 1160.0 11.77 12.05 12.04 13.25 KeyError Traceback (most recent call last) in () 6 7 for i in range(d): ----> 8 print(x2[i]) 9 ~\Anaconda3\lib\site-packages\pandas\core\series.py in getitem(self, key) 599 key = com._apply_if_callable(key, self) 600 try: --> 601 result = self.index.get_value(self, key) 602 603 if not is_scalar(result): ~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key) 2475 try: 2476 return self._engine.get_value(s, k, -> 2477 tz=getattr(series.dtype, 'tz', None)) 2478 except KeyError as e1: 2479 if len(self) > 0 and self.inferred_type in ['integer', 'boolean']: pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_value() pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_value() pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() KeyError: 504
has answer: http://stackoverflow.com/a/49913910
tagged with: python

http://stackoverflow.com/q/49889404
has answer: http://stackoverflow.com/a/49890344
tagged with: facebook-prophet
has answer: http://stackoverflow.com/a/72327598
type: Question
has answer: http://stackoverflow.com/a/70516709
linked to: http://stackoverflow.com/q/61353951
has answer: http://stackoverflow.com/a/72322915
has answer: http://stackoverflow.com/a/59388981
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/58784658
has body: I am trying to install fbprophet for Python using Pip install, but failing. I have already installed Pystan. Can I import it using Anaconda Navigator? Can someone please help. Failed building wheel for fbprophet Running setup.py clean for fbprophet Failed to build fbprophet Installing collected packages: fbprophet Running setup.py install for fbprophet ... error Complete output from command C:\ProgramData\Anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\SJ-Admin\\AppData\\Local\\Temp\\pip-build-bsm4sxla\\fbprophet\\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\SJ-Admin\AppData\Local\Temp\pip-kvck8fw1-record\install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build\lib creating build\lib\fbprophet creating build\lib\fbprophet\stan_models Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\SJ-Admin\AppData\Local\Temp\pip-build-bsm4sxla\fbprophet\setup.py", line 126, in &lt;module&gt; """ File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\__init__.py", line 129, in setup return distutils.core.setup(**attrs) File "C:\ProgramData\Anaconda3\lib\distutils\core.py", line 148, in setup dist.run_commands() File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 955, in run_commands self.run_command(cmd) File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools\command\install.py", line 61, in run return orig.install.run(self) File "C:\ProgramData\Anaconda3\lib\distutils\command\install.py", line 545, in run self.run_command('build') File "C:\ProgramData\Anaconda3\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\ProgramData\Anaconda3\lib\distutils\di…
has answer: http://stackoverflow.com/a/71964422
downvote count: 1
upvote count: 16
has answer: http://stackoverflow.com/a/67863792
has answer: http://stackoverflow.com/a/71373563
has answer: http://stackoverflow.com/a/74501857
has answer: http://stackoverflow.com/a/70104617
tagged with: anaconda
has answer: http://stackoverflow.com/a/61882344
has comment: http://stackoverflow.com/comment/86794884
has answer: http://stackoverflow.com/a/73132307
answer count: 14
tagged with: python
has title: Fbprophet installation error - failed building wheel for fbprophet
favorite count: 0
has answer: http://stackoverflow.com/a/76723004
tagged with: python-3.x
score: 15

http://stackoverflow.com/q/49894103
has comment: http://stackoverflow.com/comment/86803823
has title: Trying to read dictionary from text file
type: Question
score: 0
has answer: http://stackoverflow.com/a/49894466
answer count: 2
has comment: http://stackoverflow.com/comment/86803807
type: UnansweredQuestion
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86803634
has answer: http://stackoverflow.com/a/49894679
has body: I have a text file having dictionaries like this - account1 = {'email':'abc@test1', 'password':'abc321', 'securitycode':546987, 'name':'tester1', 'phone':236945744 } account2 = {'email':'abc@test2.com', 'password':'abc123', 'securitycode':699999, 'name':'tester2', 'phone':666666666666 } and I'm trying to read these dictionaries value with this code - dicts_from_file = [] with open('account.txt','r') as inf: dict_from_file = eval(inf.read()) print (dicts_from_file) but i get this traceback- Traceback (most recent call last): File "C:\Python\Dell_test.py", line 15, in &lt;module&gt; dict_from_file = eval(inf.read()) File "&lt;string&gt;", line 2 {'email':'abc@test2.com', 'password':'abc123', 'securitycode':699999, 'name':'tester2', 'phone':666666666666 } ^ SyntaxError: invalid syntax Can anybody please help and guide whats wrong with this snippet?
has comment: http://stackoverflow.com/comment/86803676
has comment: http://stackoverflow.com/comment/86803599
tagged with: python
has comment: http://stackoverflow.com/comment/86803796

http://stackoverflow.com/comment/86600270
score: 0
type: AnswerComment
has text: when i giving input "ve" it shows correct output.But when i give input as "va" shows error..means it not handing vowel "a".can you help me
comment on: http://stackoverflow.com/a/49792827
type: Comment

http://stackoverflow.com/a/49878869
has comment: http://stackoverflow.com/comment/86797071
answers question: http://stackoverflow.com/q/49878112
has comment: http://stackoverflow.com/comment/86804289
type: Answer
has body: Typically, a parser for expressions is implemented using recursive functions, so instead of a loop (as in your or Patrick's example) a function will call itself or other functions recursively to parse the subexpressions, take their results and build a compound expression of the subexpressions. Then the stack isn't handled explicitly by your code but the normal execution stack is used to achieve this. Have a look at this implementation: class Named_List(list): def __repr__(self): return '%s(%s)' % (type(self).__name__, ', '.join(repr(x) for x in self)) class Parens(Named_List): pass class Brackets(Named_List): pass class Braces(Named_List): pass def parse(text): if not text: raise Exception("empty input") result = [] if text[0] == '(': text = text[1:] while text[0] != ')': element, text = parse(text) result.append(element) return Parens(result), text[1:] elif text[0] == '[': text = text[1:] while text[0] != ']': element, text = parse(text) result.append(element) return Brackets(result), text[1:] elif text[0] == '{': text = text[1:] while text[0] != '}': element, text = parse(text) result.append(element) return Braces(result), text[1:] else: raise Exception("bad input", text) This function returns an abstract syntax tree (AST) of the given parenthesis expression and the part it could not parse. For an input like '(((()[]{})))' it will return Parens(Parens(Parens(Parens(), Brackets(), Braces()))) (and the empty string because it could parse everything). For a faulty input like '(((()[]{)))' it will raise an exception complaining about the bad rest ')))' which wasn't parsable anymore.
score: 0
has comment: http://stackoverflow.com/comment/86797219

http://stackoverflow.com/comment/86841268
comment on: http://stackoverflow.com/a/49912765
has text: Cool, yes you can use an iterator, but it will work the same way. List comprehension is also an iterator just written in one line in a simple way.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/86662886
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49823462
type: Comment
has text: i have no idea.. im a beginner can you guide me?

http://stackoverflow.com/comment/86791004
score: 0
has text: Updated. I would greatly appreciate your help
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49882758

http://stackoverflow.com/q/49864156
has comment: http://stackoverflow.com/comment/102272190
type: Question
type: UnansweredQuestion
tagged with: python
has body: I'm trying to create a trigger in my database by executing a raw SQL string in alembic's upgrade function. However I get a sqlalchemy.exc.ProgrammingError when running upgrade: Running this in my migration script: def upgrade(): connection = op.get_bind() connection.execute('DELIMITER #') Produces this traceback: app/migrate.py:10: ExtDeprecationWarning: Importing flask.ext.script is deprecated, use flask_script instead. from flask.ext.script import Manager app/migrate.py:11: ExtDeprecationWarning: Importing flask.ext.migrate is deprecated, use flask_migrate instead. from flask.ext.migrate import Migrate, MigrateCommand /home/my_project/app/database/models.py:2: ExtDeprecationWarning: Importing flask.ext.whooshalchemy is deprecated, use flask_whooshalchemy instead. import flask.ext.whooshalchemy /home/my_project/venv/local/lib/python2.7/site-packages/flask_whooshalchemy.py:18: ExtDeprecationWarning: Importing flask.ext.sqlalchemy is deprecated, use flask_sqlalchemy instead. import flask.ext.sqlalchemy as flask_sqlalchemy /home/my_project/venv/local/lib/python2.7/site-packages/sqlalchemy/dialects/mysql/base.py:1518: Warning: '@@tx_isolation' is deprecated and will be removed in a future release. Please use '@@transaction_isolation' instead cursor.execute('SELECT @@tx_isolation') INFO [alembic.runtime.migration] Context impl MySQLImpl. INFO [alembic.runtime.migration] Will assume non-transactional DDL. INFO [alembic.runtime.migration] Running upgrade 60f73629ea28 -&gt; 48dd7624f294, add trigger for adding to history table Traceback (most recent call last): File "app/migrate.py", line 25, in &lt;module&gt; manager.run() File "/home/my_project/venv/local/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in run result = self.handle(sys.argv[0], sys.argv[1:]) File "/home/my_project/venv/local/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handle res = handle(*args, **config) File "/home/my_project/venv/local/lib/python2.7/site-packages/…
upvote count: 2
has title: alembic won't execute raw sql that sets delimiter
score: 2
tagged with: alembic
answer count: 0
downvote count: 0
tagged with: mysql
tagged with: sqlalchemy
favorite count: 0

http://stackoverflow.com/comment/86535937
type: AnswerComment
has text: then can use yield with for line in fisier: yield line , it gonna work, am right?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49760279

http://stackoverflow.com/comment/86607078
comment on: http://stackoverflow.com/q/49796294
score: 0
type: Comment
type: QuestionComment
has text: Is the _"exists more than one"_ criteria only applicable to the first tuple element?

hid
tag name: hid
tags question: http://stackoverflow.com/q/49887540
type: Tag

http://stackoverflow.com/comment/86558953
comment on: http://stackoverflow.com/q/49769284
has text: @ducminh thanks for help, I just look over that similar question and find out my solution
type: Comment
type: QuestionComment
score: 0

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

loops
tags question: http://stackoverflow.com/q/49763716
tags question: http://stackoverflow.com/q/49792148
tags question: http://stackoverflow.com/q/49867711
tags question: http://stackoverflow.com/q/49821663
tags question: http://stackoverflow.com/q/49879874
tag name: loops
tags question: http://stackoverflow.com/q/49840020
tags question: http://stackoverflow.com/q/49879369
tags question: http://stackoverflow.com/q/49777774
tags question: http://stackoverflow.com/q/49894880
tags question: http://stackoverflow.com/q/49844960
tags question: http://stackoverflow.com/q/49848360
tags question: http://stackoverflow.com/q/49798244
tags question: http://stackoverflow.com/q/49774174
tags question: http://stackoverflow.com/q/49806962
tags question: http://stackoverflow.com/q/49909524
tags question: http://stackoverflow.com/q/49863191
tags question: http://stackoverflow.com/q/49841954
tags question: http://stackoverflow.com/q/49798451
tags question: http://stackoverflow.com/q/49903741
tags question: http://stackoverflow.com/q/49886839
tags question: http://stackoverflow.com/q/49786510
tags question: http://stackoverflow.com/q/49798329
tags question: http://stackoverflow.com/q/49846916
type: Tag
tags question: http://stackoverflow.com/q/49837899
tags question: http://stackoverflow.com/q/49846461
tags question: http://stackoverflow.com/q/49842652
tags question: http://stackoverflow.com/q/49848261
tags question: http://stackoverflow.com/q/49758858
tags question: http://stackoverflow.com/q/49909039
tags question: http://stackoverflow.com/q/49885478
tags question: http://stackoverflow.com/q/49912743
tags question: http://stackoverflow.com/q/49862853
tags question: http://stackoverflow.com/q/49848563
tags question: http://stackoverflow.com/q/49790366
tags question: http://stackoverflow.com/q/49769796
tags question: http://stackoverflow.com/q/49876947
tags question: http://stackoverflow.com/q/49814554
tags question: http://stackoverflow.com/q/49770315
tags question: http://stackoverflow.com/q/49812981
tags question: http://stackoverflow.com/q/49798741
tags question: http://stackoverflow.com/q/49908787

http://stackoverflow.com/comment/86719315
type: AnswerComment
score: 1
has text: With the help of the points you provided, I could solve the issue. I was not aware of celery worker thread to start to process the messages in the queue. So, none of celery workers is started in my setup. So, issue is not acctually related to celery broker configuration but none of celery worker was started. Could you please edit your answer to emphasize that point. If so, I can mark your answer as correct.
type: Comment
comment on: http://stackoverflow.com/a/49767106

http://stackoverflow.com/a/49800814
answers question: http://stackoverflow.com/q/49800701
score: 0
has body: Not remembering python syntax very well because I don't use it since years, but consider the logic: If you don't want to use polymorphism, you can create a dictionary map(key,value). For example: map[Europa]=(1560.8,3203.52) map[default]=(0.0,0.0) and when user insert orbiting_body you assign variables by doing: (primary_body_radius,gravitational_paramter)=map[orbiting_body]
type: Answer

http://stackoverflow.com/a/49808296
upvote count: 1
has body: Let me try and re-state your problem: You have a dictionary with letters as keys and integers as values. You want to produce a bar graph where the dictionary keys are the labels and the dictionary values are the heights of the bars. If that's right, the following will do what you want: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt d = {'g': 3, 'c': 1, 'f': 1} s = pd.Series(d) sns.barplot(s.index, s.values).set_title('Word count by letter') plt.show()
accepted answer of: http://stackoverflow.com/q/49807856
type: Answer
answers question: http://stackoverflow.com/q/49807856
score: 1
has comment: http://stackoverflow.com/comment/86631671
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49823951
accepted answer: http://stackoverflow.com/a/49823974
tagged with: python
has answer: http://stackoverflow.com/a/49823974
type: Question
answer count: 2
upvote count: 3
possible better answer: http://stackoverflow.com/a/49824036
tagged with: set
downvote count: 0
linked to: http://stackoverflow.com/q/3438140
favorite count: 0
tagged with: set-comprehension
type: AnsweredQuestion
score: 3
has title: Union of multiple sets in a list
duplicate of: http://stackoverflow.com/q/3438140
has body: This is my code. s = set() for x in [ {1,2}, {3,4}, {5,1} ]: s |= x It returns set([1, 2, 3, 4, 5]). Is it possible to use set comprehension in such a case? How can I write it shorter?
has answer: http://stackoverflow.com/a/49824036

http://stackoverflow.com/comment/86778033
score: 0
type: AnswerComment
has text: I wrote this: `import pandas` `df=pandas.read_csv("/Users/Desktop/IMDB.csv")` `df['year'] = df['title'].str.extract('\((\d{4})\)', expand=False).astype(int)` `print (df)`
comment on: http://stackoverflow.com/a/49855057
type: Comment

http://stackoverflow.com/comment/86618382
comment on: http://stackoverflow.com/a/49786912
score: 0
type: AnswerComment
has text: Perhaps, but you need to include the code that you're using to run your program in order for us to help with that!
type: Comment

http://stackoverflow.com/q/49799318
type: Question
has comment: http://stackoverflow.com/comment/86613873
has title: how to handle internet not avaialble while uploading the file to s3?
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/86613335
has answer: http://stackoverflow.com/a/49849999
accepted answer: http://stackoverflow.com/a/49849999
type: AnsweredQuestion
score: 2
upvote count: 3
tagged with: amazon-s3
has body: I have written scheduler program in python to uploading file to AWS S3 at a particular time(using scheduler). if internet connection is not available at that time , I'm getting socket.gaierror: [Errno -3] Temporary failure in name resolution exception. This breaks the total flow, so that i need to restart the program. How to handle this situation in a graceful way, so that when internet resumes my file get upload process starts. Below is my scheduler job code: def job(): serialNo = getserial() print('schedule working.......') yesterday_date=date.today() - timedelta(1) # one day file path file_path="/home/pi/Desktop/bme280_elf_new/reading/"+str(yesterday_date)+".csv" # file move are upload file from cloud here AWS_ACCESS_KEY_ID = 'AWS_ACCESS_KEY_ID' AWS_SECRET_ACCESS_KEY = 'AWS_SECRET_ACCESS_KEY' Bucketname = 'Bucketname' conn = boto.s3.connect_to_region('us-east-1', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, is_secure=True, # uncomment if you are not using ssl calling_format = boto.s3.connection.OrdinaryCallingFormat(), ) bucket = conn.get_bucket(Bucketname) print ('Uploading %s to Amazon S3 bucket %s' % (file_path, Bucketname)) def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() k = Key(bucket) k.key = str(serialNo)+'-'+str(yesterday_date)+'.csv' k.set_contents_from_filename(file_path, cb=percent_cb, num_cb=10) Initiating scheduler by , schedule.every().day.at("00:10").do(job) # run at midnight 00:10 Thanks in advance.
answer count: 1
downvote count: 1
tagged with: iot
favorite count: 0

http://stackoverflow.com/a/49801269
score: 1
type: Answer
has body: Try Below: import pandas as pd datestr = '12:17 AM - 8 Apr 2018' utcDate = pd.to_datetime(datestr, format='%H:%M %p - %d %b %Y', utc=True)
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49800475

http://stackoverflow.com/a/58217239
type: Answer
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/49823996
downvote count: 1
has body: Before use searching string in sql command search_string= f"%{search_string}%" and then apply it in sql command cur.execute("SELECT * FROM books WHERE title LIKE :searching_string ORDER BY id ",{"searching_string":search_string}) Additionally can do it lower search_string= f"%{search_string}%".lower() cur.execute("SELECT * FROM books WHERE LOWER(title) LIKE :searching_string ORDER BY id ", {"searching_string":search_string})

http://stackoverflow.com/q/49846883
upvote count: 7
has title: selenium ConnectionRefusedError: [WinError 10061] in python 3
has comment: http://stackoverflow.com/comment/86717876
downvote count: 1
favorite count: 0
type: Question
score: 6
tagged with: python
type: AnsweredQuestion
has body: I have a python program that uses selenium to go to a site and get the value of an element. Now, I have a list of dicts, each one having a url parameter. I iterate through the list and go to the url from each dict. The problem is that after the first run of the loop it gives me an error: ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it Traceback (most recent call last): File "C:\Users\Me\Desktop\mfile\getfuncs.py", line 15, in <module> browser.get(newurl) File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 324, in get self.execute(Command.GET, {'url': url}) File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 310, in execute response = self.command_executor.execute(driver_command, params) File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 466, in execute return self._request(command_info[0], url, body=data) File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 489, in _request self._conn.request(method, parsed_url.path, body, headers) File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1026, in _send_output self.send(msg) File "C:\Users\Me\AppData\Local\Programs\Python\Python36-32\li…
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/49877373
accepted answer: http://stackoverflow.com/a/49877373

http://stackoverflow.com/comment/86770308
has text: try to update Pip: `pip install -U pip`
type: Comment
comment on: http://stackoverflow.com/q/49872110
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86827065
score: 0
type: AnswerComment
has text: This is perfect, but confirm or clarify what I'm finding to be true about the use of the strip method in this example? Is it just there to remove the newline character from each line, which somehow is parsed as whitespace? (I get the same result if I use `line.strip('\n')` or if I leave it blank.)
type: Comment
comment on: http://stackoverflow.com/a/49904461

http://stackoverflow.com/q/49853360
tagged with: python
tagged with: influxdb-python
score: 4
favorite count: 0
tagged with: influxdb
has body: What is the preferred way of properly building InfluxDB queries in Python? (I have been looking for a proper InfluxDB query builder. The ones I've found are either old/outdated or can't really generate valid queries for InfluxDB.)
has title: Query builder for InfluxDB?
answer count: 1
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/54630874
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/49857765
type: AnsweredQuestion
downvote count: 0
answer count: 3
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86785149
has answer: http://stackoverflow.com/a/49859006
accepted answer: http://stackoverflow.com/a/49859006
possible better answer: http://stackoverflow.com/a/49857875
has body: I am trying to output the sum of consonant and vowel values from a dictionary containing letter_number_pairs as shown below: vowels = ['a','e','i','o','u'] consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] letter_number_pairs = {'a': 1,'b': 8,'c': 3,'f': 3,'h': 8,'i': 2,'l': 4,'p': 2,'q': 1,'s': 5,'u': 9,'w': 0,'y': 5,'z': 2} The question I'm wondering is: "Can I sum the vowel values and sum the consonant values in a single pass?" That is, can I avoid executing two passes of the dictionary as shown in my working example below: vowel_value_sum = sum(value for (letter, value) in letter_number_pairs.items() if letter in vowels) consonant_value_sum = sum(value for (letter, value) in letter_number_pairs.items() if letter in consonants)
has answer: http://stackoverflow.com/a/49858625
favorite count: 0
type: Question
tagged with: python-3.x
has title: Can I produce two sums from a single python dictionary comprehension based on matching the keys with two mutually exclusive key lists?
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/9442724
has answer: http://stackoverflow.com/a/49857875

http://stackoverflow.com/a/50010299
answers question: http://stackoverflow.com/q/49836676
has body: Check if pip has been cached on another path, to do so, call $ which pip and check that the path is different from the one prompted in the error, if that's the case run: $ hash -r When the cache is clear, pip will be working again. reference: http://cheng.logdown.com/posts/2015/06/14/-usr-bin-pip-no-such-file-or-directory
downvote count: 1
upvote count: 18
type: Answer
score: 17

http://stackoverflow.com/a/49888220
has comment: http://stackoverflow.com/comment/86874361
type: Answer
has body: About your second pattern (".*?"){2}: A cite from the rules of matching If a group is contained in a part of the pattern that matched multiple times, the last match is returned. And findall does the following: If one or more groups are present in the pattern, return a list of groups; Your pattern (".*?"){2} means that (".*?") should match twice in a row, and according to the first rule, only the content of the last match is captured. For your data findall finds the sequence (".*?"){2} only once, so it returns a list consisting of the last captured group for a single match: ['"y"']. This example would make it more obvious: import re print (re.findall(r'(\d){2}', 'a12b34c56')) # ['2', '4', '6'] You can see that findall finds the sequence (\d){2} three times and for each it returns the last captured content for the group (\d). Now about your first pattern: ".*?"".*?". This one does not contains subgroups, and, according to findall again, in this case it returns: all non-overlapping matches of pattern in string, as a list of strings. So for your data it is ['"x""y"'].
has comment: http://stackoverflow.com/comment/86874350
has comment: http://stackoverflow.com/comment/86872221
score: 0
answers question: http://stackoverflow.com/q/49887702

http://stackoverflow.com/q/49838002
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/49840640
has comment: http://stackoverflow.com/comment/86817370
type: AnsweredQuestion
tagged with: xpath
has body: I am working on a bot for a website and it requires a color and keyword to find the item. I am using selenium to look for the item from the keyword and then pick a color option (some items on the website, provide the item in multiple colors). I am having trouble looking for both the keyword and color at the same time, and then after choosing the correct colored version of the item from the user's color and keyword input. I want it to select on that option. Formula I am trying to make in Python: If the first Xpath(keyword) is found and the 2nd Xpath(color) is found Then select on the item that contains those 2 properties. This is the current code I have: Item = driver.find_element_by_xpath('//*[contains(text(), "MLK")]' and contains ("Black")]') if (item != None): actions.moveToElement(item).click() I've tried the code above and it doesn't work. Here are the 2 pieces of code that I want to merge to find the item: driver.find_element_by_xpath('//a[contains(text(), "MLK")]') driver.find_element_by_xpath('//a[contains(text(), "Black")]') The keyword is called MLK The Color is called Black After Merging, I want to find that Exact Element (Called MLK, Color version = Black) This combined item should be clicked on, I only know to use .click() If a better way, please let me know. The website I am using to make a bot for: supremenewyork.com The item I am using as an example, to pick a certain color (It's the Sweatshirt with MLK on it): http://www.supremenewyork.com/shop/all/sweatshirts
answer count: 3
score: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/49840640
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49843883
type: Question
has answer: http://stackoverflow.com/a/49842389
has title: Looking for 2 things in 2 different Xpaths - Python Selenium
linked to: http://stackoverflow.com/q/9567069
has comment: http://stackoverflow.com/comment/86819295
has comment: http://stackoverflow.com/comment/86818707
accepted answer: http://stackoverflow.com/a/49843883
tagged with: python
linked to: http://stackoverflow.com/q/19030742

http://stackoverflow.com/comment/86754915
comment on: http://stackoverflow.com/q/49869373
score: 0
type: Comment
type: QuestionComment
has text: Just as an FYI, `count >= 5000 and count < 10000` can very neatly be replaced by `5000 <= count < 10000` in Python. Any sequence of rich comparison operators `a op1 b op2 c ...` gets effectively computed as `a op1 b and b op2 c ...`. The only difference is that if `a`, `b` or `c` are complex expressions, they only get evaluated once.

http://stackoverflow.com/q/49847756
type: Question
tagged with: python-3.x
type: UnansweredQuestion
answer count: 1
has body: I have this code which uses the change in mouse cursor position to detect mouse movement: import win32api from time import sleep savedpos = win32api.GetCursorPos() count = 0 while(True): curpos = win32api.GetCursorPos() if savedpos != curpos: count = count +1 savedpos = curpos print("Mouse Movement # ", count) sleep(0.05) The problem is that when the mouse cursor is in one of the corners of the screen, my Python code may not recognize mouse movement. For example, if the mouse cursor is in the upper left corner of the screen, moving my physical mouse up and/or left will not have any effect on my Python code (it won't print "Mouse Movement #"). Can someone please help me get my Python code to recognize physical mouse movement even when the mouse cursor is unable to move on the screen?
downvote count: 0
has comment: http://stackoverflow.com/comment/86759935
has answer: http://stackoverflow.com/a/77152549
upvote count: 7
favorite count: 0
score: 7
tagged with: windows
tagged with: python
has title: Detecting Physical Mouse Movement with Python and Windows 10 Without Cursor Movement
tagged with: mouseevent
has comment: http://stackoverflow.com/comment/86710804

http://stackoverflow.com/a/49781891
type: Answer
has body: @Chadvandehey's answer is correct - if you want to go over infinite loop just do while True or maybe without outer loop at all : just use xrange instead of range and assign value of 0 in the inner loop when i == nt-1. use while loop , something like this: i = 0 while i &lt; nt: //do whatever you want if i == nt-1: i=0 just be very careful with infinite loops.
answers question: http://stackoverflow.com/q/49781727
score: 0

http://stackoverflow.com/comment/86578796
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49781472
type: Comment
has text: also `print(df.groupby(['state_code']).sum())` working nice and get numeric values?

http://stackoverflow.com/q/49807819
has title: Making a graph with unknown datetime format
score: 0
tagged with: datetime
has comment: http://stackoverflow.com/comment/86634530
has body: How could I make a graph with the columns EventTime and Price from the following CSV format? The datetime format is unknown to me, and I don't even know how to reformat it so that I could make a simple graph. #=TimeAndSale,EventSymbol,EventTime,Time,Sequence,ExchangeCode,Price,Size,BidPrice,AskPrice,SaleConditions,Flags TimeAndSale,AKER,20180402-070000.164-0400,20180402-070000-0400,162:2,Q,0.8998,1991,0.899,0.92,"@FT ",22604 TimeAndSale,AKER,20180402-070000.165-0400,20180402-070000-0400,162:4,Q,0.9,300,0.899,0.92,"@FT ",22604 TimeAndSale,AKER,20180402-070000.165-0400,20180402-070000-0400,162:6,Q,0.899,1000,0.899,0.92,"@FT ",22604 TimeAndSale,AKER,20180402-070000.165-0400,20180402-070000-0400,162:8,K,0.9,4000,0.9,0.92,"@ T ",8268 TimeAndSale,AKER,20180402-070150.608-0400,20180402-070150-0400,605:10,P,0.91,2000,0.905,0.92,"@ T ",8236 TimeAndSale,AKER,20180402-070521.770-0400,20180402-070521-0400,765:12,P,0.91,1000,0.9,0.91,"@FT ",22572 TimeAndSale,AKER,20180402-070527.239-0400,20180402-070527-0400,234:14,P,0.91,647,0.9,0.91,"@FT ",22572 TimeAndSale,AKER,20180402-070558.330-0400,20180402-070558-0400,325:15,K,0.92,30,0.91,0.92,"@ TI",8232 TimeAndSale,AKER,20180402-070643.959-0400,20180402-070643-0400,953:17,K,0.92,4470,0.92,0.925,"@ T ",8268 TimeAndSale,AKER,20180402-070809.017-0400,20180402-070809-0400,11:19,P,0.925,1985,0.91,0.925,"@FT ",22572 TimeAndSale,AKER,20180402-071030.623-0400,20180402-071030-0400,622:21,P,0.92,2000,0.92,0.925,"@ T ",8268 TimeAndSale,AKER,20180402-071140.207-0400,20180402-071140-0400,206:23,P,0.92,2073,0.92,0.925,"@ T ",8268 TimeAndSale,AKER,20180402-071203.431-0400,20180402-071203-0400,430:25,P,0.92,1000,0.92,0.925,"@ T ",8268 TimeAndSale,AKER,20180402-071204.798-0400,20180402-071204-0400,797:27,P,0.92,700,0.915,0.925,"@ T ",8268 TimeAndSale,AKER,20180402-071255.654-0400,20180402-071255-0400,652:28,P,0.92,80,0.918,0.925,"@ TI",8264 TimeAndSale,AKER,20180402-071601.928-0400,20180402-071601-0400,926:30,P,0.92,535,0.91,0.92,"@ T ",8236 TimeAndSa…
has comment: http://stackoverflow.com/comment/86631068
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/86660515
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49826697
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/49781370
has body: Try to reuse int_list as the output, along the lines replace = 0 for i in range(5 ** k): if i in int_list[replace:]: int_list[replace] = int_to_string(i, k) replace += 1 return int_list Edit: In case input list contains duplicates, consider while i in int_list[replace:]: instead of if .....
score: 0
has comment: http://stackoverflow.com/comment/86578482
answers question: http://stackoverflow.com/q/49781154
type: Answer

http://stackoverflow.com/q/49813130
has body: Why is it throwing this error on some files, and for other files it doesn't ? The files are all .mp4 videos. 'ValueError: MoviePy couldn't find the codec associated with the filename. Provide the 'codec' parameter in write_videofile.' The code, with comments: # The videos on which we will work on (intro &amp; a video) intro = VideoFileClip('./videos/intro.mp4') original = VideoFileClip('./videos/original_video.mp4') # We cut 2s and crop the original video original.cutout(0, 2) original = vfx.crop(original, x1=10) # Adding a watermark on top of the original video watermark = (ImageClip("./images/watermark.png") .set_duration(original.duration) .set_position(("center","bottom")) .resize(width=intro.w)) watermaked = CompositeVideoClip([original, watermark], size=original.size) # Our final video: Intro + Waterkarmed, and output it. final_render = concatenate_videoclips([intro, watermaked], method='compose') final_render.write_videofile('./videos/output_video.mp4', fps=30, threads=1) The error stack: final_render.write_videofile('./videos/output_video.mp4', fps=30, threads=1) File "&lt;decorator-gen-51&gt;", line 2, in write_videofile File "/usr/lib/python2.7/site-packages/moviepy/decorators.py", line 54, in requires_duration return f(clip, *a, **k) File "&lt;decorator-gen-50&gt;", line 2, in write_videofile File "/usr/lib/python2.7/site-packages/moviepy/decorators.py", line 137, in use_clip_fps_by_default return f(clip, *new_a, **new_kw) File "&lt;decorator-gen-49&gt;", line 2, in write_videofile File "/usr/lib/python2.7/site-packages/moviepy/decorators.py", line 22, in convert_masks_to_RGB return f(clip, *a, **k) File "/usr/lib/python2.7/site-packages/moviepy/video/VideoClip.py", line 288, in write_videofile raise ValueError("MoviePy couldn't find the codec associated " ValueError: MoviePy couldn't find the codec associated with the filename. Provide the 'codec' parameter in write_videofile.
downvote count: 0
tagged with: codec
upvote count: 7
has answer: http://stackoverflow.com/a/79317411
possible better answer: http://stackoverflow.com/a/79317411
accepted answer: http://stackoverflow.com/a/67798357
favorite count: 0
has title: ValueError: MoviePy couldn't find the codec associated with the filename. Provide the 'codec' parameter in write_videofile
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/118467364
score: 7
tagged with: python
tagged with: moviepy
has answer: http://stackoverflow.com/a/67798357
has comment: http://stackoverflow.com/comment/86648425
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/86642090

http://stackoverflow.com/a/49906839
answers question: http://stackoverflow.com/q/49900714
upvote count: 0
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49900714
has body: This will probably be deleted but here goes: First one is start at second position, head left as far as you can go. Second is start at rightmost, head left ending before -3. Third is start at-3 and head all the way to left.
type: Answer
score: -1

http://stackoverflow.com/a/49901862
upvote count: 1
type: Answer
has body: Try this: import pandas as pd import re # regular expressions def coeff_comp(s): # Separate stoichiometric coefficient and compound result = re.search('(?P&lt;coeff&gt;\d*)(?P&lt;comp&gt;.*)', s) coeff = result.group('coeff') comp = result.group('comp') if not coeff: coeff = '1' # coefficient=1 if it is missing return comp, int(coeff) equations = ['R1: A + 2B + C &lt;=&gt; D', 'R2: A + B &lt;=&gt; C'] # some test data reactions_dict = {} # results dictionary for equation in equations: compounds = {} # dict -&gt; compound: coeff eq = equation.replace(' ', '') r_id, reaction = eq.split(':') # separate id from chem reaction lhs, rhs = reaction.split('&lt;=&gt;') # split left and right hand side reagents = lhs.split('+') # get list of reagents products = rhs.split('+') # get list of products for reagent in reagents: comp, coeff = coeff_comp(reagent) compounds[comp] = - coeff # negative on lhs for product in products: comp, coeff = coeff_comp(product) compounds[comp] = coeff # positive on rhs reactions_dict[r_id] = compounds # insert dict into DataFrame, replace NaN with 0, let values be int df = pd.DataFrame(reactions_dict).fillna(value=0).astype(int) The output looks like R1 R2 A -1 -1 B -2 -1 C -1 1 D 1 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49896768
answers question: http://stackoverflow.com/q/49896768
downvote count: 0
score: 1

http://stackoverflow.com/a/49842702
answers question: http://stackoverflow.com/q/49766933
score: 0
type: Answer
has body: I found a workaround by using a pipe to redirect serial output to python. Works now.

http://stackoverflow.com/comment/86933023
type: Comment
type: AnswerComment
has text: You were right about the order of the for loops. I changed the answer accordingly.
comment on: http://stackoverflow.com/a/49908196
score: 0

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

http://stackoverflow.com/q/49768588
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/49769373
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49769452
has answer: http://stackoverflow.com/a/49769373
score: 0
has title: Class & View for displaying Max & Avg values for each day in Django
answer count: 3
has answer: http://stackoverflow.com/a/49769452
tagged with: sqlite
has answer: http://stackoverflow.com/a/50011532
has body: I am extremely new to python (and django) and I've searched but honestly I'm not sure if I'm searching for the right stuff so decided to ask for some help. Here is my class. I have a script setup to enter and save these values every 5 minutes into the db. class Entry(models.Model): class Meta: ordering = ['time'] time = models.DateTimeField(default=timezone.now) inside = models.FloatField() outside = models.FloatField() gavg = models.IntegerField() ghigh = models.IntegerField() I am wanting to setup a class/view to display the date obviously, the average(and high) for 'inside' &amp; 'outside' for that day. The average of gavg for that day. The high for 'ghigh' that day. And this would need to be done for every single day from the Entry class. I've tried to understand what I need to do in ORM but had issues with timezone aware datetime. I'm guessing I need another class, and I've seen some functions out there that might do what I need but I am having a difficulty time visualizing how the class should be defined and how/where the average/high functions should go. Or would this be better suited as an SQL query?
type: Question
has comment: http://stackoverflow.com/comment/86552538

http://stackoverflow.com/comment/86606188
type: Comment
type: QuestionComment
has text: int.from_bytes is standard python function.https://docs.python.org/3/library/stdtypes.html
comment on: http://stackoverflow.com/q/49790194
score: 0

http://stackoverflow.com/a/70550573
score: 0
has comment: http://stackoverflow.com/comment/124715608
answers question: http://stackoverflow.com/q/49822676
has comment: http://stackoverflow.com/comment/124730506
type: Answer
has body: My half a day gone just breaking my head around it. Such a sad state, Jinja really sucks...the message was not clear, I literally had to run through the entire code to check for matching if/for what else... Now I removed all the comments from the page and it worked.. There were no blocks inside such comments..even then it worked... Angry with Jinja...

http://stackoverflow.com/a/49841882
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86698514
answers question: http://stackoverflow.com/q/49841474
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/136476093
has body: A Celery periodic task may be the best solution for this, however a simpler alternative may be a Django custom management command running from a crontab. The management command would automatically have access to the Django ORM and could thus perform the database check and send the reminders. You could run it from the crontab such as: # Run the command every 15 minutes */15 * * * * python /path/to/manage.py your_command_name Using a management command would also give you the ability to execute the reminder process manually from the command line should you ever have to.

http://stackoverflow.com/q/49901863
downvote count: 0
type: Question
has body: the directions that were given asked for code that returned the length of each word in a string. so like it would count the number of letters in each word and print it next to the word I have this code: def word_lengths(a): a = a.lower() c = list(a) a = "" for x in c: if x == "," or x == "." or x == "'" or x == "!" or x == "?": c[c.index(x)] = "" for x in c: a += x y = a.split() z = {} for x in y: z[x] = len(x) return z print(word_lengths("I ate a bowl of cereal out of a dog bowl today.")) Which returns: {'dog': 3, 'bowl': 4, 'a': 1, 'out': 3, 'of': 2, 'ate': 3, 'cereal': 6, 'i': 1, 'today': 5}
tagged with: string
accepted answer: http://stackoverflow.com/a/49901946
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49901946
has answer: http://stackoverflow.com/a/49902318
score: 3
has comment: http://stackoverflow.com/comment/86819126
has answer: http://stackoverflow.com/a/49902122
tagged with: python
answer count: 5
tagged with: dictionary
has title: Map length of words in a sentence to a list of words
possible better answer: http://stackoverflow.com/a/49902114
tagged with: list
has answer: http://stackoverflow.com/a/49902114
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/49902112

http://stackoverflow.com/q/49818846
has title: Why is np.nextafter(0, 1) not equivalent to the float64 epsilon value?
tagged with: numpy
answer count: 2
score: 0
tagged with: floating-point
tagged with: scipy
has body: This is very weird! np.nextafter returns the smallest number after 0. Shouldn't this be equal to the float64 epsilon? In [25]: np.nextafter(0, 1).dtype == np.finfo(np.float64).eps.dtype Out[25]: True In [26]: np.nextafter(0, 1) &lt; np.finfo(np.float64).eps Out[26]: True
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49820053
accepted answer: http://stackoverflow.com/a/49819384
has answer: http://stackoverflow.com/a/49819384
tagged with: python
possible better answer: http://stackoverflow.com/a/49820053
type: Question

http://stackoverflow.com/a/49853213
has body: TensorFlow while loops are designed to allow different iterations to be run in parallel. This causes them to behave rather differently from what you'd expect coming from other programming languages. One such oddity is that if you create a tensor inside the loop, you cannot access it from outside. In your case, you are creating a new tensor with every tf.concat op. Yes, even though that tensor is stored under the same Python variable name as the previous version, it is still a new tensor: indeed, the original H_l is a constant, so its value cannot be changed; you can only create a new tensor in its place. The same is true for h_tl. To solve this problem for H_l, what you want is to store an array of tensors, and add another entry to this array at each iteration. The data structure for doing this is tf.TensorArray, which you should initialize outside the loop and then write into at each iteration. For h_tl, in which you only want to examine the final value, you don't need a tf.TensorArray; you could use a tf.Variable instead, and use tf.assign to update its value. In both cases, take care to ensure that the mutating ops are executed, by including them in a tf.control_dependencies block.
has comment: http://stackoverflow.com/comment/86758740
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49852645
has comment: http://stackoverflow.com/comment/86721880
type: Answer

http://stackoverflow.com/a/49958813
downvote count: 0
type: Answer
has body: As far as I can surmise the only alternatives, from this issue, are to Call the underlying function like main.callback(*args). Then you're missing default arguments from the click interface. To use the click testing interface via something like click.testing.CliRunner().invoke(main, ['--host', '127.0.0.1'], catch_exceptions=False). I suppose from my point of view, option 1 is the best we can do; default parameters just have to be done manually. I would be curious too if there were any better alternatives though.
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/49843017

http://stackoverflow.com/q/49785753
has answer: http://stackoverflow.com/a/49785844
type: Question
accepted answer: http://stackoverflow.com/a/49785808
tagged with: rounding
tagged with: math
has answer: http://stackoverflow.com/a/49785808
tagged with: python
tagged with: decimal
type: AnsweredQuestion
has title: How to properly round half down a decimal number?
score: 0
has body: I am trying to round half down a number, but my program doesn't want to round half down but up. For instance, I have 0.0498512222 I want to get 0.049, but the program round half up and give me 0.050 Code #!/usr/bin/python import sys, signal, json, time import random import decimal from decimal import Decimal, ROUND_HALF_DOWN num = 0.049852124 num = Decimal(num) numCoins = Decimal(num.quantize(Decimal('0.001'), rounding=ROUND_HALF_DOWN)) numCoins = float(numCoins) print numCoins I don't know how to resolve this error, because it's for a cryptocurrency bot, and the numCoins is the number of a coin that I have. If the program round half up I'll get an error like 'Account has insufficient balance for requested action' because I can't sell more than I have.
answer count: 2
has comment: http://stackoverflow.com/comment/86586927
possible better answer: http://stackoverflow.com/a/49785844
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/49788992
accepted answer of: http://stackoverflow.com/q/49788407
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49788407
has body: the follow code could work, i am not sure this is the best approach, but this is how i managed to get the the tensroflow working for me. void* object = (void*)resized.ptr() ; int64_t* dims; //set dims //C API TF_Tensor* tftensor = TF_NewTensor(TF_DataType::TF_FLOAT, dims, nDims, object, data_size, &amp;deallocator, 0); //C++ API tensorflow::Tensor input_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({ batch_size, objectHeight, objectWidth, objectChannels })); int data_size = objectHeight * objectWidth * objectChannels * batch_size * sizeof(float); std::copy_n((float*)object, data_size, (input_tensor.flat&lt;float&gt;()).data());
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86727543
has text: Great job. I just got it mainly by `ellipse mask` and `cv2.distanceTransform`. While you get the `analytical solution`.
type: Comment
comment on: http://stackoverflow.com/a/49848093
type: AnswerComment
score: 1

http://stackoverflow.com/q/49800452
upvote count: 1
has title: Retrieve List of Bluetooth Devices Using Python 3 and Terminal
has answer: http://stackoverflow.com/a/49801075
favorite count: 0
accepted answer: http://stackoverflow.com/a/49801075
tagged with: bluetooth
type: Question
tagged with: terminal
score: 1
linked to: http://stackoverflow.com/q/21029154
possible better answer: http://stackoverflow.com/a/68798180
tagged with: python
has answer: http://stackoverflow.com/a/68798180
has answer: http://stackoverflow.com/a/71659510
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/23140638
has body: When using the Linux terminal inside the Raspberry pi, i have to use only 3 commands to retrieve a list of Bluetooth capable devices in the area. These are the commands that are executed in order: "sudo bluetoothctl" "agent on" "scan on" the final command above will over-time retrieve a list of scanned devices. When i manually put it into my raspberry pi terminal it works (found instrustions from here: Instruction Link) QUESTION: how do i translate the series of commands above into a Python 3 script using the standard subprocess module? I Tried: import time import subprocess arguments = ["sudo", "bluetoothctl"] #to be able to access Bluetooth commands output = subprocess.Popen(arguments, shell=True) time.sleep(0.1) arguments = ["agent", "on"] output = subprocess.Popen(arguments, shell=True) time.sleep(0.1) arguments = ["scan", "on"] output = subprocess.check_output(arguments, shell=True) time.sleep(0.1) print(output) #not even close huh.. yea.. As you can see i'm pretty new to both Linux terminal commands and the subprocess module. Therefore any help and guidance is greatly appreciated! UPDATE: i am able to get my first command sudo bluetoothctl to work as it returns list of previously paired devices. However when i get to the next command output = subprocess.Popen("agent on", shell=True) it returns a message: /bin/sh: 1: agent: not found. How do i get my other commands to work? New code: import time import subprocess output = subprocess.Popen("sudo bluetoothctl", shell=True) time.sleep(0.1) output = subprocess.Popen("agent on", shell=True) time.sleep(0.1) output = subprocess.check_output("scan on", shell=True) time.sleep(2) What the terminal spits out: [NEW] Controller XX:XX:XX:XX:XX:XX raspberrypi [default] [NEW] Device XX:XX:XX:XX:XX:XX Galaxy J3 Emerge [bluetooth]# /bin/sh: 1: agent: not found /bin/sh: 1: scan: not found Traceback (most recent call last): File "/home/pi/pywork/test.py", line 9, in &lt;module&gt; output = subprocess.check_output("scan on", shell=…
tagged with: raspberry-pi
tagged with: subprocess
answer count: 3
downvote count: 0

http://stackoverflow.com/q/49915600
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: keras
has title: Keras : Building a train function within for loop creates memory issue
score: 0
has body: I am trying to train a double hidden layer CNN with policy gradient. I have a custom loss function for this. I am trying to implement it in Keras (backend TF) using the code for Cartpole game by kkweon. The code is as follows, def _build_train_fn(network): action_prob_placeholder = network.output action_onehot_placeholder = K.placeholder(shape=(None, output_dim), name = "action_onehot") discount_reward_placeholder = K.placeholder(shape=(None, ), name = "discount_reward") action_prob = K.sum(action_prob_placeholder * action_onehot_placeholder, axis=1) log_action_prob = K.log(action_prob) loss = -log_action_prob * discount_reward_placeholder loss = K.mean(loss) adam = optimizers.Adam() updates = adam.get_updates(loss = loss, params = network.trainable_weights) train_fn = K.function(inputs=[network.input, action_onehot_placeholder, discount_reward_placeholder], outputs=[], updates=updates) return(train_fn) Now I run the training function inside a for loop, where I take mini batches of episodes and train for that. So I need to build the train function for each mini batch, as it depends on the network output. The batch-wise training inside the for loop goes like this, if episode_number % batch_size == 0: mini_batch_states = np.asarray(mini_batch_states).reshape([len(mini_batch_states), 14]) mini_batch_moves = np.asarray(mini_batch_moves) train_fn = _build_train_fn(network) train_fn([mini_batch_states, mini_batch_moves, mini_batch_rewards]) The issue is that the memory usage continues to grow on size as the number of mini batches grow. I have tried building the function once before the loop, which solves the memory issue but removes the aspect of dynamic learning and converges to a 0.5 winrate instead of growing consistently. Also using a del train_fn does not solve the memory issue. I am very new to both TF and Keras. Any help is much appreciated.
has comment: http://stackoverflow.com/comment/86921786
has comment: http://stackoverflow.com/comment/86847381
tagged with: tensorflow
type: Question

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/49870228
tags question: http://stackoverflow.com/q/49848481
tags question: http://stackoverflow.com/q/49893574
tags question: http://stackoverflow.com/q/49803673
tags question: http://stackoverflow.com/q/49906690
tags question: http://stackoverflow.com/q/49866771
tags question: http://stackoverflow.com/q/49794587
tags question: http://stackoverflow.com/q/49777924
tags question: http://stackoverflow.com/q/49803439
tags question: http://stackoverflow.com/q/49793476
tag name: json
tags question: http://stackoverflow.com/q/49824358
tags question: http://stackoverflow.com/q/49763394
tags question: http://stackoverflow.com/q/49761926
tags question: http://stackoverflow.com/q/49845285
tags question: http://stackoverflow.com/q/49843623
tags question: http://stackoverflow.com/q/49911196
tags question: http://stackoverflow.com/q/49802121
tags question: http://stackoverflow.com/q/49860301
tags question: http://stackoverflow.com/q/49837602
tags question: http://stackoverflow.com/q/49903579
tags question: http://stackoverflow.com/q/49800216
tags question: http://stackoverflow.com/q/49764405
tags question: http://stackoverflow.com/q/49842873
tags question: http://stackoverflow.com/q/49822874
tags question: http://stackoverflow.com/q/49784658
tags question: http://stackoverflow.com/q/49873460
tags question: http://stackoverflow.com/q/49829286
tags question: http://stackoverflow.com/q/49854765
tags question: http://stackoverflow.com/q/49876442
tags question: http://stackoverflow.com/q/49843914
tags question: http://stackoverflow.com/q/49821337
tags question: http://stackoverflow.com/q/49854487
tags question: http://stackoverflow.com/q/49807373
tags question: http://stackoverflow.com/q/49769428
tags question: http://stackoverflow.com/q/49826979
tags question: http://stackoverflow.com/q/49837092
tags question: http://stackoverflow.com/q/49814863
tags question: http://stackoverflow.com/q/49882054
tags question: http://stackoverflow.com/q/49812167
type: Tag
tags question: http://stackoverflow.com/q/49865442
tags question: http://stackoverflow.com/q/49880156
tags question: http://stackoverflow.com/q/49804906
tags question: http://stackoverflow.com/q/49823173
tags question: http://stackoverflow.com/q/49871662
tags question: http://stackoverflow.com/q/49835232
tags question: http://stackoverflow.com/q/49772489
tags question: http://stackoverflow.com/q/49893522
tags question: http://stackoverflow.com/q/49820759
tags question: http://stackoverflow.com/q/49831993
tags question: http://stackoverflow.com/q/49802305
tags question: http://stackoverflow.com/q/49868352
tags question: http://stackoverflow.com/q/49897549
tags question: http://stackoverflow.com/q/49839323
tags question: http://stackoverflow.com/q/49857964
tags question: http://stackoverflow.com/q/49867703
tags question: http://stackoverflow.com/q/49804815
tags question: http://stackoverflow.com/q/49893777
tags question: http://stackoverflow.com/q/49814936
tags question: http://stackoverflow.com/q/49818754
tags question: http://stackoverflow.com/q/49850258
tags question: http://stackoverflow.com/q/49874289

http://stackoverflow.com/comment/86772702
comment on: http://stackoverflow.com/q/49877928
score: 0
has text: Thanks for the comment @stephenmallette, I will try to access a Gremlin Console but as it's managed product not sure I can. Keep you in touch
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86677994
type: QuestionComment
comment on: http://stackoverflow.com/q/49831320
has text: Could you explain us why you want to cast a linked_list into an integer? Can't you just get the integer attribute?
score: 1
type: Comment

http://stackoverflow.com/comment/86840943
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49905006
has text: Another target: https://stackoverflow.com/questions/19506105/flask-sqlalchemy-query-with-keyword-as-variable

http://stackoverflow.com/a/49812979
has body: The solution is to set the variables in an object-level (not class-level). You do this by creating the variables inside the init area like below. You can then change the values externally. Then you need to calculate whatever you want in a different function, using that variable. Then just call that function where you need it. VERY IMPORTANT (the mistake I made): The init is written with TWO underscores _ x 2 on each side class ClassTester: def __init__(self): self.age = 10 def msg(self): self.seconds = self.age * 365 * 24 * 60 * 60 self.txt = "You have lived for " + str(self.seconds) + " seconds." return self.txt Tester = ClassTester() Tester.age = 20 print(Tester.msg()) Tester.age = 30 print(Tester.msg())
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49812261

http://stackoverflow.com/q/49829467
tagged with: google-cloud-platform
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/55668205
downvote count: 0
score: 6
has body: In my scenario I'm scheduling tasks using PubSub. This is up to 2.000 PubSub messages that are than consumed by a Python script that runs inside a Docker Container within Google Compute Engine. That script consumes the PubSub messages. The processing of each message is about 30seconds to 5min. Therefore the acknowledgement deadline is 600sec (10min). from google.cloud import pubsub_v1 from google.cloud.pubsub_v1.subscriber.message import Message def handle_message(message: Message): # do your stuff here (max. 600sec) message.ack() return def receive_messages(project, subscription_name): subscriber = pubsub_v1.SubscriberClient() subscription_path = subscriber.subscription_path(project, subscription_name) flow_control = pubsub_v1.types.FlowControl(max_messages=5) subscription = subscriber.subscribe(subscription_path, flow_control=flow_control) future = subscription.open(handle_message) # Blocks the thread while messages are coming in through the stream. Any # exceptions that crop up on the thread will be set on the future. # The subscriber is non-blocking, so we must keep the main thread from # exiting to allow it to process messages in the background. try: future.result() except Exception as e: # do some logging raise Because I'm working on so many PubSub messages, I'm creating a template for a Compute Engine that uses auto-scaling in either of these two ways: gcloud compute instance-groups managed create my-worker-group \ --zone=europe-west3-a \ --template=my-worker-template \ --size=0 gcloud beta compute instance-groups managed set-autoscaling my-worker-group \ --zone=europe-west3-a \ --max-num-replicas=50 \ --min-num-replicas=0 \ --target-cpu-utilization=0.4 gcloud beta compute instance-groups managed set-autoscaling my-worker-group \ --zone=europe-west3-a \ --max-num-replicas=50 \ --min-num-replicas=0 \ --update-stackdriver-metric=pubsub.googleapis.com/subscription/num_undelivered_messages \ --stackdriver-metric-filter="resource.type = pubsub_subscription AND res…
tagged with: google-compute-engine
favorite count: 0
tagged with: docker
has comment: http://stackoverflow.com/comment/87451342
has comment: http://stackoverflow.com/comment/87452104
has title: Google PubSub and auto-scaling Compute Engine instances (Python)
has comment: http://stackoverflow.com/comment/87747438
has comment: http://stackoverflow.com/comment/87451259
tagged with: google-cloud-pubsub
tagged with: python
has comment: http://stackoverflow.com/comment/87451132
has comment: http://stackoverflow.com/comment/87451265
upvote count: 6
has answer: http://stackoverflow.com/a/49859718
has comment: http://stackoverflow.com/comment/87451656
type: Question
answer count: 2

http://stackoverflow.com/comment/86849910
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49916232
has text: @GPhilo thanks.. have added indents
type: Comment

http://stackoverflow.com/comment/86627287
score: 0
comment on: http://stackoverflow.com/q/49785006
type: QuestionComment
type: Comment
has text: Can you provide example input parameters you would intend to pass to the Elsevier API and your expected outputs? does your task require an "Institutional Token"? https://dev.elsevier.com/tecdoc_developer_faq.html

http://stackoverflow.com/q/49818697
upvote count: 0
score: -2
downvote count: 2
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49818808
accepted answer: http://stackoverflow.com/a/49818808
tagged with: text
type: AnsweredQuestion
has title: Python concatanate files
has body: file 1.csv: traider1,domain.net,tomb,Raider1 traider,domain.net,tomb,Raider file 2.txt: TECH-1377 TECH-1366 How to combine these 2 files into 3rd ? so i can get 3.csv: traider1,domain.net,tomb,Raider1,TECH-1377 traider,domain.net,tomb,Raider,TECH-1366 i tried : import fileinput files= ['1.csv','2.txt'] allfiles = fileinput.input(files) for line in allfiles: # this will iterate over lines in all the files print(line) and got traider1,domain.net,tomb,Raider1 traider,domain.net,tomb,Raider TECH-1377 TECH-1366
tagged with: file
favorite count: 0
type: Question

http://stackoverflow.com/a/49866080
type: Answer
has comment: http://stackoverflow.com/comment/86778036
has comment: http://stackoverflow.com/comment/86776589
score: 0
answers question: http://stackoverflow.com/q/49865313
has body: You can try to do something like this: from collections.abc import MutableMapping # We need to implement those method: __getitem__, __setitem__, __delitem__, __iter__, __len__ class TwoWayDict(MutableMapping): __slots__ = '__dict__' def __init__(self, *args, **kwargs): self.__dict__.update(*args, **kwargs) def __getitem__(self, key): return self.__dict__[key] def __setitem__(self, key, value): self.__dict__[key] = value self.__dict__[value] = key def __delitem__(self, key): self.__dict__.__delitem__(self[self[key]]) self.__dict__.__delitem__(self[key]) # this do not work if key == value def __iter__(self): return iter(self.__dict__) def __len__(self): return len(self.__dict__) def get(self, key, default=None): return self[key] if key in self else default def __str__(self): return str(self.__dict__) Tests: a = TwoWayDict() a['key1'] = 'key2' print(a) print(a['key1']) print(a['key2']) print(len(a)) for key, val in a.items(): print(key, val) Results: {'key1': 'key2', 'key2': 'key1'} key2 key1 2 key1 key2 key2 key1 Note that the length and iteration might be ambiguous. If you don't want duplicate key to show, you'll need to find the the key in the dict item and return the corresponding key. For pop you can use the solution propose by SW Williams. EDIT: if you really need to inherit from dict (Probably an assignment...) don't forget to implement update, since it will bypass __setitem__ and get in the dict. Also if you have a 1 to 1 map for on of the key, you need to deal with this in the __del__ and __pop__ functions.

http://stackoverflow.com/a/49896616
has body: I think this will solve your problem import pandas as pd d = {'ID': ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E","F","F"], 'value': [23, 23, 52, 52, 36, 36, 46, 46, 9, 9, 110, 110]} df = pd.DataFrame(data=d) df['value']=df['value'].shift(1) df2=df[1:11] #here 11 is n-1,it depends on number of rows print(df2)
upvote count: 2
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49895663

http://stackoverflow.com/comment/86728078
type: QuestionComment
has text: `command=lambda:sum.calc_total` does not, at any point, actually execute the `calc_total` method. You want `command=lambda:sum.calc_total()`, or just `command=sum.calc_total` since the method requires no parameters (which is the usual reason for needing a lambda in a case like this).
score: 0
comment on: http://stackoverflow.com/q/49845752
type: Comment

http://stackoverflow.com/comment/86572839
has text: how does this go against `list_of_strings[:, 1]` ?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49778743
score: 0

http://stackoverflow.com/q/49777115
tagged with: flask
type: AnsweredQuestion
score: 0
has body: I just get started to read the source code of Flask. I found there is a helper function which can be imported as below: from flask.helpers import total_seconds It's source code: def total_seconds(td): """Returns the total seconds from a timedelta object. :param timedelta td: the timedelta to be converted in seconds :returns: number of seconds :rtype: int """ return td.days * 60 * 60 * 24 + td.seconds My question is, if I ever had a timedelta object, why do not just to get the total seconds via td.total_seconds() (provided by Python standard library) instead of using total_seconds(td) (provided by Flask)?
answer count: 1
has title: Where is the helper function flask.helpers.total_seconds() useful for?
type: Question
has answer: http://stackoverflow.com/a/49779930
accepted answer: http://stackoverflow.com/a/49779930
has comment: http://stackoverflow.com/comment/86569982
tagged with: python

http://stackoverflow.com/comment/86651699
score: 3
type: QuestionComment
comment on: http://stackoverflow.com/q/49818392
type: Comment
has text: I believe this is called the "discrete logarithm problem"? Please correct me if I'm wrong.

http://stackoverflow.com/q/49910238
answer count: 1
has body: I'm using Socket communication to make two Raspberry Pi's communicate. And I'm using python. The program is very simple, because I'm trying to test the socket communication and how can two Pi's communicate. What I want is to capture the traffic (communication of the two Pi's) from my PC. The problem is that when I use Wireshark on my PC, I can't see the traffic generated from s.send() and conn.sendall() between the two Pi's, I'm still a student and not very advanced in Networking so I'm not sure if this problem is related to Raspberry Pi, Networking or Wireshark. This is the code for the first Raspberry Pi (Server) import socket host = '' port = 5560 storedValue = "Yo, what's up?" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(1) conn, address = s.accept() print("Connected to: " + address[0] + ":" + str(address[1])) while True: data = conn.recv(1024) # receive the data data = data.decode('utf-8') dataMessage = data.split(' ', 1) command = dataMessage[0] reply = storedValue s.close() conn.sendall(str.encode(reply)) conn.close() This is for the second Raspberry Pi (Client) import socket host = '192.168.2.2' port = 5560 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) while True: command = input("Enter you command: ") s.send(str.encode(command)) reply = s.recv(1024) print(reply.decode('utf-8')) s.close()
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49910379
has title: Sniffing Socket Communication - Python
tagged with: network-programming
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49910379
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/49765286
has comment: http://stackoverflow.com/comment/86546291
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49765651
has body: Suppose I have two classes like this: class Root: def __init__(self): self.children = [] class Child: def __init__(self): # How do I make this attribute (or property if I must change # it to one) automatically reference the root object (if the # current object is a an item of root.children) self.root = ??? So my question is partially already in the code, but it needs some clarification. Suppose I create objects from the class like so: root_obj = Root() child_obj = Child() root_obj.children.append(child_obj) How would I make it so child_obj.root automatically detects that the current object is being stored under root_obj and reference that object? This way, if I later decide to store child_obj inside a new object another_root_obj.children then child_obj.root will reference that object instead. If this is not possible the way I'm trying to do it, then what would be the correct way to design a system like this in Python?
type: Question
has answer: http://stackoverflow.com/a/49765651
possible better answer: http://stackoverflow.com/a/49765527
answer count: 2
has title: Automatic "root object" detection implementation in Python?
tagged with: python
has answer: http://stackoverflow.com/a/49765527
has comment: http://stackoverflow.com/comment/86546655
type: AnsweredQuestion
score: 0
tagged with: pep8

http://stackoverflow.com/a/49826695
score: 2
has body: To handle that UnicodeDecodeError, you do the exact same thing you already did to handle urllib.error.HTTPError and urllib.error.URLError. So: try: fileContents = soupify(url) except urllib.error.HTTPError: # If the website returns an HTTP error, such as a 404 inaccessibleSites += 1 isError = True queue.pop(0) except urllib.error.URLError: # If the website does not exist or does not have a valid URL inaccessibleSites += 1 isError = True queue.pop(0) except UnicodeDecodeError: # If the website is not in UTF-8 inaccessibleSites += 1 isError = True queue.pop(0) Or, since you're not actually doing anything different for the three errors, you could use one except: try: fileContents = soupify(url) except (urllib.error.HTTPError, # If the website returns an HTTP error, urllib.error.URLError, # If the website does not exist or does not have a valid URL UnicodeDecodeError): # If the website is not in UTF-8 inaccessibleSites += 1 isError = True queue.pop(0) But meanwhile, what you probably really want to do here is stop assuming every web page is in UTF-8 and instead use the headers and/or meta tags that tell you what the encoding actually is. Doing this correctly is not trivial. and you might be happier using requests instead of urllib, because it has all the logic builtin (except the final "heuristic" step—but BeautifulSoup does that part). If you can't use anything outside the stdlib for some reason: The first step is easy: page.headers.get_content_charset(). The last step is also easy: if you can't figure out the encoding, just pass BeautifulSoup the bytes and it will use the "Unicode, damnit" heuristics. Parsing META tags, on the other hand, can be painful. You need to either soupify the binary data and cross your fingers, or decode to ASCII with a non-strict error handling and soupify that, then do soup.find_all('meta'), and check each one to see if it has either an http-equiv="Content-Type" attribute with a charset value, or a charset attribute, then you can use that t…
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49826440
has comment: http://stackoverflow.com/comment/86702938
answers question: http://stackoverflow.com/q/49826440
type: Answer

http://stackoverflow.com/a/49803231
answers question: http://stackoverflow.com/q/49779590
has body: You are putting the same field list_price after list_price, you should replace the field that is inside the xpath by the field you want. product.template.common.form product.template
has comment: http://stackoverflow.com/comment/86641901
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86641929
score: 1
type: Answer

http://stackoverflow.com/a/49792063
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86608614
score: 3
has body: Attribute value can be extracted using [] brackets. For instance, if to extract alt value an img tag use: image_example = soup.find('img') and then print(image_example['alt']) Updated code: from bs4 import BeautifulSoup data = ''' Do not need Do not need! Do not need ... Do not need Do not need! Do not need ... ''' soup = BeautifulSoup(data, 'html.parser') url_address = soup.find('a')['href'] print (url_address) # Output: /link-i-want/to-get.html The format is as follows. soup.find('<tag>')['<attribute-name>'] . We can use .get(attr) like mentioned. soup.find('<tag>').get('<attr>') Reference: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#quick-start
answers question: http://stackoverflow.com/q/49791969
has comment: http://stackoverflow.com/comment/86602023
upvote count: 3

http://stackoverflow.com/comment/86709591
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49847272
has text: this is very close to https://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists. Use itertools.product to generate lists, then add a step of doing a join of each list w/ its symbols. Should be flagged as duplicate?

http://stackoverflow.com/comment/86752375
type: Comment
comment on: http://stackoverflow.com/q/49868445
score: 1
has text: It would be more helpful if you could include your dataframe as text instead of as an image.
type: QuestionComment

http://stackoverflow.com/q/49835342
tagged with: numpy
answer count: 3
has body: I have to handle sparse matrix that can occasionally be very big, nearing or exceeding RAM capacity. I also need to support mat*vec and mat*mat operations. Since internally a csr_matrix is 3 arrays data, indices and indptr is it possible to create a csr matrix from numpy memmap.
possible better answer: http://stackoverflow.com/a/76007555
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/76007555
tagged with: sparse-matrix
has comment: http://stackoverflow.com/comment/86687990
favorite count: 0
accepted answer: http://stackoverflow.com/a/50985982
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50985982
score: 1
has answer: http://stackoverflow.com/a/62990659
has title: Using memory mapped buffers for scipy sparse
tagged with: python
has comment: http://stackoverflow.com/comment/86695114
tagged with: scipy
type: Question

http://stackoverflow.com/comment/86688088
comment on: http://stackoverflow.com/q/49831540
score: 1
type: Comment
type: QuestionComment
has text: The last input field is dynamic, generated by js. If `selenium` is not an option, you can find the values (two large hex strings) in the document in the 11th ` ` tag. Note that the js code is also dynamic - and obfuscated - but you should be able to parse it with regex.

http://stackoverflow.com/q/49866349
has comment: http://stackoverflow.com/comment/86748702
has answer: http://stackoverflow.com/a/49866584
tagged with: colors
has comment: http://stackoverflow.com/comment/86748472
has comment: http://stackoverflow.com/comment/86748254
type: AnsweredQuestion
upvote count: 3
score: 3
has title: Tkinter askcolor returning wrong RGB values?
possible better answer: http://stackoverflow.com/a/62773449
has body: I am using Python 3.6.1. I need to get a string (or int values) of RGB values of a color chosen with Tkinter askcolor method. My code: from tkinter.colorchooser import askcolor color = askcolor() rgb_tuple = color[0] #gets tuple of RGB values color_result_rgb = ' '.join(format(x, "1.0f") for x in rgb_tuple) #tuple into a string Now, say i choose a pink color with values (255, 0, 128) &gt;&gt;&gt; rgb_tuple returns: (255.99609375, 0.0, 128.5) And &gt;&gt;&gt; color_result_rgb returns: '256 0 128' How do I fix this so the returned values are correct?
has comment: http://stackoverflow.com/comment/86748410
tagged with: python
favorite count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86748460
type: Question
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/49866584
has answer: http://stackoverflow.com/a/62773449

http://stackoverflow.com/comment/86750263
comment on: http://stackoverflow.com/q/49867288
type: Comment
type: QuestionComment
has text: `df.data.sort_values().diff().isin([0,1]).ne(True).cumsum().sort_index() `
score: 0

http://stackoverflow.com/comment/86767929
has text: The same code provides the nice icon on my computer. You may have some old fonts on your system. What OS are you using?
comment on: http://stackoverflow.com/a/49875348
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49810724
tagged with: python
tagged with: selenium-webdriver
score: 0
type: Question
has body: In Selenium Python testing -- xpath same but the text is changing to "error" and "success" -- I need to identify "success" and "error" message, how to do this ---please help me out enter image description here enter image description here
has answer: http://stackoverflow.com/a/49811077
has title: How to find dynamic text when xpath is same for all --- Selenium Python testing
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/86569870
type: AnswerComment
score: 0
has text: No, but try running my update *exactly as provided*.
type: Comment
comment on: http://stackoverflow.com/a/49776743

http://stackoverflow.com/comment/86599122
score: 0
type: AnswerComment
has text: @KingVidfamne Just gave it a try and actually `np.dot` is much faster! With `a = np.random.rand(10000, 1000); b = np.random.rand(1000)`, `np.dot(a, b)` takes ~7ms and `np.sum(a * b, axis=1)` ~100ms. I thought `np.dot` was just a convenience function (at least in this use case), but it looks like it has a much more optimized implementation...
comment on: http://stackoverflow.com/a/49779904
type: Comment

http://stackoverflow.com/comment/86573348
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49778904
has text: Do you want one image or do you want to have a dynamic display ?

http://stackoverflow.com/q/49788027
has comment: http://stackoverflow.com/comment/86592075
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/49788382
accepted answer: http://stackoverflow.com/a/49805567
has body: i'm working with python/numpy and search in the docs but cant find the method to accomplish this i have this two arrays and want to concatenate the elements inside the array into a second array this is my first array import numpy as np a = np.array([0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0]) my goal is Output: [[00000000], [00000000]] the reason of this is for later transform every element of the array into hex
has answer: http://stackoverflow.com/a/49805567
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/86611682
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/86592868
favorite count: 0
has comment: http://stackoverflow.com/comment/86593164
tagged with: numpy
possible better answer: http://stackoverflow.com/a/61917778
has title: Concatenate elements of an array with numpy?
linked to: http://stackoverflow.com/q/27572219
type: Question
has answer: http://stackoverflow.com/a/61917778

http://stackoverflow.com/comment/86785922
type: AnswerComment
comment on: http://stackoverflow.com/a/49884395
score: 0
type: Comment
has text: it is not working as intended...i have updated my question

http://stackoverflow.com/comment/86800664
has text: by the way: is your distance calculation correct? https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49892500
score: 0

http://stackoverflow.com/comment/86826063
score: 0
has text: Yes that is correct - ID is the name I gave to the index column
type: QuestionComment
comment on: http://stackoverflow.com/q/49905078
type: Comment

http://stackoverflow.com/q/49804580
has body: I'm trying to validate user input, however my problem is that with the current code if the first IF statement is true then the rest of the ELIF statements will not be sought through. This means that if there is an error in the first entry box the rest of the entry boxes do not get validated, this is my code: if (len(MemberID)) &gt; 4: self.MemberIDError.configure(fg = "red") elif (len(Postcode)) &gt; 7: self.PostcodeError.configure(fg = "red") elif (len(Age)) &gt; 3: self.AgeError.configure(fg = "red") elif (len(Mass)) &gt; 3: self.MassError.configure(fg = "red") elif (Name == '') or (MemberID == '') or (Postcode == '') or (Age == '') or (Gender == '') or (Mass == ''): self.CreateError.configure(fg = "red") conn.commit() else: List = [Name, MemberID, Postcode, Age, Gender, Mass] cursor.execute("INSERT INTO memb(Name, MemberID, Postcode, Age, Gender, Mass) VALUES (?,?,?,?,?,?)",(Name, MemberID, Postcode, Age, Gender, Mass)) conn.commit() Alternatively, if I change the "ELIF" statements to "IF" statements, wrong user input will still be added to the database. What can I do to ensure the user input is properly validated, and why are the "ELIF" statements not being used.
has comment: http://stackoverflow.com/comment/86623888
favorite count: 0
has title: Python IF statements with common ELSE
type: Question
has answer: http://stackoverflow.com/a/49804657
score: 0
has comment: http://stackoverflow.com/comment/86623889
tagged with: if-statement
has answer: http://stackoverflow.com/a/49804671
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86626723
has answer: http://stackoverflow.com/a/49804660
has comment: http://stackoverflow.com/comment/86624104
answer count: 3
upvote count: 1
tagged with: validation
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86623886

http://stackoverflow.com/q/49862197
has comment: http://stackoverflow.com/comment/86739718
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/47691718
type: Question
has body: I am trying to get django rest framework user registration working and I am stuck. I have a custom user that adds a field to the django auth user and I am following the first answer on this link but it's giving me a 'KeyError' and I don't really know how to solve it. Any help is appreciated! Here is my Model: class CustomUser(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) birthday = models.DateField() Here the Serializer: class CustomUserSerilizer(serializers.Serializer): birthday = serializers.DateField() class Meta: model = CustomUser fields = ('birthday') class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) custUser = CustomUserSerilizer(required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'custUser') def create(self, validated_data): profile_data = validated_data.pop('custUser') user = User.objects.create(**validated_data) user.set_password(validated_data['password']) user.save() Customer.objects.update_or_create(user=user,**profile_data) return user And the Views: @api_view(['POST']) def create_auth(request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) Traceback: File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\AppData\Local\Pro…
has answer: http://stackoverflow.com/a/49862749
has title: Django rest framework custom user registration
has comment: http://stackoverflow.com/comment/86740314
score: 1
favorite count: 0
tagged with: python-3.x
tagged with: serialization
has comment: http://stackoverflow.com/comment/86739586

http://stackoverflow.com/comment/86830394
type: Comment
type: QuestionComment
has text: Yeah the general way to find a good alpha is [cross-validation](https://en.wikipedia.org/wiki/Cross-validation_(statistics)), where for *each alpha*, you repeatedly partition your data, train on the first partition, test on the other partition, and find the average test error. So the result of k-fold or leave-one-out cross-validation is a plot of average test error against alpha, and you pick the alpha that gave you the lowest cross-validated error. Does that make sense? (I'll double-check, I'm sure scikit-learn has a way to automate cross-validation and find the best alpha for you.)
score: 0
comment on: http://stackoverflow.com/q/49907180

http://stackoverflow.com/q/49781866
has comment: http://stackoverflow.com/comment/86580168
has comment: http://stackoverflow.com/comment/86579205
score: 0
has body: Requirement Given tensor like: SparseTensorValue(indices=array([[0, 0], [1, 0], [1, 1], [1, 2]]), values=array([2, 0, 2, 5]), dense_shape=array([2, 3])) the shape is 2x3 | 2 na na | | 0 2 5 | Need a new tensor with value in the index, like below: Note that the total num of values is 6 (set of [0, 1, 2, 3, 4, 5]) the shape is 2x6 | 0 0 1 0 0 0 | | 1 0 1 0 0 1 | The tensor can be created by the code below: SparseTensorValue(indices=array([[0, 2], [1, 0], [1, 2], [1, 5]]), values=array([1, 1, 1, 1]), dense_shape=array([2, 6])) How to do it in TensorFlow way? Neither approach below is working import tensorflow as tf tags = tf.SparseTensor(indices=[[0, 0], [1, 0], [1, 1], [1, 2]], values=[2, 0, 2, 5], dense_shape=[2, 3]) print(type(tags.indices)) # approach 1: the TensorFlow way to implement the python logic new_indices = [[tags.indices[i], tags.values[i]] for i in range(tags.values.shape[0])] # syntax incorrect # approach 2: indice_idx = tf.map_fn(lambda x : x[0], tags.indices) value_idx = tf.map_fn(lambda x : x[1], tags.indices) value_arr = tf.gather(tags.values, value_idx) with tf.Session() as s1: print(indice_idx.eval()) print(tags.values.eval()) print('value_arr', value_arr.eval()) """ [0 0 1 2] &lt;-- value_idx, which is the index of tags.values want to combine [0 1 1 1] &lt;-- indice_idx [2 2 0 2] &lt;-- value_arr, which is the value of tags.values ==&gt; [[0,2], [1,2], [1,0], [1,2]] """ new_indices = tf.concat(indice_idx, value_arr) # syntax incorrect with tf.Session() as s: s.run([tf.global_variables_initializer(), tf.tables_initializer()]) print(s.run(value_arr)) print(s.run(tags.values)) print(s.run(new_indices)) print(s.run(tags.indices[3, 1]))
has comment: http://stackoverflow.com/comment/86580389
answer count: 1
has comment: http://stackoverflow.com/comment/86582714
upvote count: 1
tagged with: machine-learning
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86580436
has title: manipulate Tensor by indices and values in TensorFlow
tagged with: tensor
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/49783804
has answer: http://stackoverflow.com/a/49802073
tagged with: python
has comment: http://stackoverflow.com/comment/86579551
tagged with: indices

http://stackoverflow.com/q/49819927
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49820221
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49820063
tagged with: python
type: Question
possible better answer: http://stackoverflow.com/a/49820063
accepted answer: http://stackoverflow.com/a/49820287
has body: I am trying to count the number of times a record has a frequency greater than 3 in my pandas column 'Subject' - grouped by date. Currently this code works but it is for the data-frame overall. main_subj = df['Subject'].value_counts( [df['Subject'].value_counts()&gt;3] count_main_subj = main_subj.shape[0] I would like to group the data by 'date' - in order to see how many records have a frequency above 3 each day. My data-frame looks like this: Subject Verb Object ID Date trump got jobs 820108 20170803 voters begin to 182912 20170803 steve miss colleague 980828 20170804 For example if on one day there were 10 records: 5 with the subject trump 3 with the subject clinton 2 with the subject obama The result would be 2 - the number of subjects that occur more than 3 times. Thank you!
has title: Number of records with a certain frequency in a grouped data-frame
has answer: http://stackoverflow.com/a/49820287

http://stackoverflow.com/q/49856748
has comment: http://stackoverflow.com/comment/86739396
tagged with: flask-wtforms
upvote count: 0
type: UnansweredQuestion
has body: I am trying to set up two different forms on the same Flask page with validators, but it keeps telling me my forms are not defined. I get error: The code is designed to allow users to input a number and check if it is abundant, perfect, or deficient, and then with a separate form to allow users to define a range and get how many abundant, perfect or deficient numbers there are within that range. My code is as follows: from flask import Flask, render_template, request from flask_wtf import Form from wtforms import IntegerField from wtforms.validators import InputRequired from perfect_numbers import classify, listInRange app = Flask(__name__) app.config['SECRET_KEY'] = 'DontTellAnyone' class PerfectForm(Form): inputNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')]) class PerfectRangeForm(Form): startNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')]) endNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')]) @app.route('/', methods=['GET', 'POST']) def index(): form1 = PerfectForm(request.form, prefix="form1") num = 1 Classify = classify(num) if form.validate_on_submit() and form.data: num = request.form1['inputNumber'] Classify = classify(form1.inputNumber.data) return render_template('index.html', form1=form1, num=num, classify=Classify) return render_template('index.html', num=1, form1=form1, classify=Classify) @app.route('/aliRange', methods=['GET', 'POST']) def aliRange(): form2 = PerfectRangeForm(request.form2, prefix="form2") startNumber = 1 endNumber = 1 aliquot = 'abundant' Classify = classify(num) ListInRange = listInRange(startNumber, endNumber, aliquot) if form2.validate_on_submit() and form2.data: startNumber = request.form2['startNumber'] endNumber = request.form2['endNumber'] aliquot = request.form2['aliquot'] ListInRange = listInRange(startNumber, endNumber, aliquot) retur…
has answer: http://stackoverflow.com/a/49856803
answer count: 1
tagged with: flask
downvote count: 1
favorite count: 0
type: Question
has title: Multiple forms with Flask keeps saying I haven't defined forms
tagged with: python
score: -1

http://stackoverflow.com/comment/86579024
comment on: http://stackoverflow.com/q/49781435
has text: I got different problems when I used directly built-in open because of that I had to switch fs.open (The main problem was that built-in open couldn't reach the direct path of the file upload because it's dynamic but was working when it was static path.)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86760905
score: 2
type: Comment
type: QuestionComment
has text: Can you also post the code for `views.post_detail`
comment on: http://stackoverflow.com/q/49868725

http://stackoverflow.com/q/49878814
has answer: http://stackoverflow.com/a/49879915
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/49878951
has title: Count total number of occurrences in pandas dataframe with a condition
score: 4
has answer: http://stackoverflow.com/a/49878951
upvote count: 4
type: AnsweredQuestion
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49878910
downvote count: 0
has body: I have this dataframe: cat_df.head() category depth 0 food 0.0 1 food 1.0 2 sport 1.0 3 food 3.0 4 school 0.0 5 school 0.0 6 school 1.0 ... Where depth = 0 stands for root publication, depth &gt; 0 are comments. For each category I want to count the number of root publications (depth=0) and number of comments (depth&gt;0). I use value_counts() for counting the unique values: cat_df['category'].value_counts().head(15) category total number food 44062 sport 38004 school 11080 life 8810 ... I thought I could put ['depth'] == 0 as a condition inside the dataframe but it didn't work: cat_df[cat_df['depth'] == 0].value_counts().head(5) How do I get the total number of occurences for depth=0 and depth>0? I want to put it in a table like this: category | total number | depth=0 | depth&gt;0 ...
favorite count: 0
accepted answer: http://stackoverflow.com/a/49878910
type: Question

http://stackoverflow.com/q/49844084
accepted answer: http://stackoverflow.com/a/49877068
favorite count: 0
tagged with: beautifulsoup
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1732348
has title: the right approach to use BeautifulSoup n python3
has answer: http://stackoverflow.com/a/49877068
tagged with: python
tagged with: web-crawler
tagged with: python-3.x
score: 0
answer count: 1
tagged with: web-scraping
upvote count: 1
has body: i am trying to build web scraper on python with BeautifulSoup libary. I want to get information from all pages of bitcoin forum topic topic. i am using the following code to get username , status, date and time of post , post text , activity, merit from forum https://bitcointalk.org/index.php?topic=2056041.0 url='https://bitcointalk.org/index.php?topic=2056041.0' from bs4 import BeautifulSoup import requests import re def get_html(url): r = requests.get(url) return r.text html=get_html(url) soup=BeautifulSoup(html, 'lxml') results= soup.findAll("td", {"valign" : "top"}) usernames=[] for i in results: x=i.findAll('b') try: s=str(x[0]) if 'View the profile of' in s : try: found = re.search('of (.+?)"&gt;', s).group(1) if found.isdigit()==False: usernames.append(found) except Exception as e :print(e) except Exception as e :pass#print(e) print(len(usernames)) status=[] for i in results: x=i.findAll("div", {"class": "smalltext"}) s=str(x) try: found = re.search(' (.+?)&lt;br/&gt;', s).group(1) if len(found)&lt;25: status.append(found) except:pass print(len(status)) activity=[] for i in results: x=i.findAll("div", {"class": "smalltext"}) s=str(x) try: x=s.split('Activity: ')[1] x=x.split('&lt;br/&gt;')[0] activity.append(x) except Exception as e :pass print(activity) print(len(activity)) posts=[] for i in results: x=i.findAll("div", {"class": "post"}) s=str(x) try: x=s.split('="post"&gt;')[1] x=x.split('&lt;/div&gt;]')[0] if x.isdigit()!=True: posts.append(x) except Exception as e :pass print(len(posts)) i feel what its a very ugly and not correct solution using re all these try except and etc. Is there more straight and elegant solution for this task?
downvote count: 1

http://stackoverflow.com/q/49853649
has body: I have a model like this: class Category(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey('self', null=True) I do the query: categories = Category.objects.filter(name__contains=something) And I want to prefetch 2 levels of parents above the categories. So I will be able to iterate them and do category.parent.parent without extra queries. In SQL that will be equivalent to LEFT JOIN with the same table two times. How to do this in django ORM?
type: Question
tagged with: hierarchy
tagged with: django
tagged with: django-models
tagged with: python
has title: django select_related vs prefetch_related in tree like table
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49853739
accepted answer: http://stackoverflow.com/a/49853739
downvote count: 0
upvote count: 1
score: 1
tagged with: parent
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/88446109
score: 0
type: AnswerComment
has text: i do save the png file on my computer fig.savefig() and after that i paste the png file in an excel file. no need to mark it as not correct because it works i have tested it
comment on: http://stackoverflow.com/a/49830538
type: Comment

http://stackoverflow.com/q/49780160
favorite count: 0
type: AnsweredQuestion
has title: Is it possible to create new fields using django admin page interface?
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49780443
accepted answer: http://stackoverflow.com/a/49780443
type: Question
answer count: 2
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49780288
possible better answer: http://stackoverflow.com/a/49780288
tagged with: django
has body: Is it possible to create and delete new charfields or textareas through the Django admin page without harcoding them? For example, I have a simple model, registered in Django admin page class DocumentList(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.title Obviously, it has only one charfield on admin page, something like: DocumentList: [___________] How can I add another one and delete her later if needed from Django admin page without actually hardcoding another charfield/textarea in models.py, to make it look like: DocumentList: [___________] *****************[___________]
tagged with: backend

http://stackoverflow.com/comment/86577469
has text: Working . Thanks.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49781044
type: Comment

http://stackoverflow.com/q/49916374
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49916454
accepted answer: http://stackoverflow.com/a/49916454
has comment: http://stackoverflow.com/comment/86848167
has title: Syntax error on apostrophe
tagged with: python
type: Question
tagged with: python-3.x
upvote count: 0
answer count: 2
tagged with: compiler-errors
has answer: http://stackoverflow.com/a/49916431
possible better answer: http://stackoverflow.com/a/49916431
tagged with: syntax-error
score: -4
has comment: http://stackoverflow.com/comment/86848209
has comment: http://stackoverflow.com/comment/86848460
downvote count: 4
favorite count: 0
has body: the apostrophe at the end of 'you answered: ' is registering as a syntax error, not sure why as it is just ending the string. I don't know what to try print('You got the following questions wrong:' 'Question' , incorrectnum[i] , incorrect_Q[i] 'You answered:' , incorrect_A[i] 'The correct answer was:' , correct_answers[int(incorrectnum[i])])

http://stackoverflow.com/q/49830115
tagged with: python
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86675785
has body: I'm trying to scrape some data from an URL and save it to a CSV file in Windows. The file runs perfectly in Ubuntu and even on some Windows machines, but not on mine. This is my code. from bs4 import BeautifulSoup import requests# import csv# import pandas as pd import csv import time import random url = 'some url' print(url) headers = { 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'User-Agent': random.choice(user_agent_list), 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'en-US,en;q=0.8' } r = requests.get(url, headers = headers) data = r.text soup = BeautifulSoup(data, "html.parser") try: tagline = soup.select("div.clp-lead__headline")[0].text except: tagline = ''# print(tagline) try: rating = soup.select(".tooltip-container.tooltip--rate-count-container")[0].select('span')[0].text# print(rating) except: rating = '' try: what_you_learn = soup.select(".what-you-get")[0]# print(what_you_learn) except: what_you_learn = '' try: includes_things = soup.select(".incentives")[0].select(".clp-component-render")[0]# print(len(includes_things))# print(includes_things.text) except: includes_things = '' try: description = soup.select(".description__title")[0].parent# print(description) except: description = '' return tagline, rating, what_you_learn, includes_things, description with open('some.csv', newline = '', encoding = "utf8") as csvfile: courses = csv.reader(csvfile, delimiter = ',') index = 0 for row in courses: index += 1 if index &lt; 3500: #print(index) continue if index &gt; 4000: break url = row[3] if len(url) &lt; 4: continue# print(url) tagline, rating, what_you_learn, includes_things, description = scape_data(url) with open('u_courses.csv', 'a', encoding = 'utf-8') as csvfile2: fieldnames = ['url', 'tagline', 'rating', 'what_you_learn', 'includes_things', 'description'] writer = csv.DictWriter(csvfile, fieldnames = fieldnames)# print(descriptio…
score: 1
has comment: http://stackoverflow.com/comment/86676307
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
answer count: 0
upvote count: 2
type: UnansweredQuestion
has title: Scraped data saving as CSV file under other OSes but not in Windows
has comment: http://stackoverflow.com/comment/86675746
has comment: http://stackoverflow.com/comment/86675857
has comment: http://stackoverflow.com/comment/86675759
tagged with: web-scraping

http://stackoverflow.com/a/60529858
type: Answer
answers question: http://stackoverflow.com/q/49848517
has body: On windows it installs the bio package in a top level directory named bio with lower case b. To fix the problem rename the directory to upper case b, Bio. Obviously the biopython people don't pay much attention to the win
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86600596
type: QuestionComment
comment on: http://stackoverflow.com/q/49792746
score: 1
has text: Keep your `try: ... except: ...` blocks small and specify the error you want to catch. This way the Interpreter could tell you the Error that occured.
type: Comment

http://stackoverflow.com/comment/86759493
comment on: http://stackoverflow.com/a/49869394
type: AnswerComment
score: 0
has text: See my edit for the standardized alternative. You might not want to go down this route as it changes interpretation, but might help your visualization
type: Comment

http://stackoverflow.com/comment/86874604
type: Comment
has text: Ok i will try with data augmentation techniques to see if i can get more images. Do you think that the number of weight filters could be adecuated? thanks you so much iga for your supporting
type: AnswerComment
comment on: http://stackoverflow.com/a/49911729
score: 0

http://stackoverflow.com/q/49808828
has title: What is the proper way to pass multiple variables to MIMEText
accepted answer: http://stackoverflow.com/a/49818942
has comment: http://stackoverflow.com/comment/86652065
tagged with: python
type: Question
score: 2
tagged with: python-2.7
has body: I am trying to pass some variables to MIMEText then send those variables as a body in a plain text email. Seems simple enough but no matter what I try I don't get the expected result. Here is what I have: import cgi from datetime import datetime import smtplib from email.mime.text import MIMEText arguments = cgi.FieldStorage() cid = arguments.getvalue('cid') cin = arguments.getvalue('cin') dn = arguments.getvalue('dn') sttime = datetime.now().strftime('%m/%d/%Y_%H:%M:%S') msg = MIMEText(cid, cin, sttime) #Here's the problem msg['Subject'] = '911 was dialed' sender = 'first_last@domain.com' recipient = 'user@gmail.com' s = smtplib.SMTP('localhost') msg['From'] = sender msg['To'] = recipient s.sendmail(sender, recipient, msg.as_string()) It sends the email but it only sends the first variable (cid) and it sends it as an attachment. I would like all variables to be in the body of the email, not an attachment. If I try to print the same thing that I'm passing to MIMEText it produces what I would expect: print(cid, cin, sttime) ('9545551212', 'UserA', '04/12/2018_23:03:47') If I simply feed a string of text to MIMEText it sends just fine. What am I doing wrong with the variables? I'm using python 2.7.14. Thanks in advance.
upvote count: 2
answer count: 1
tagged with: mime
downvote count: 0
has answer: http://stackoverflow.com/a/49818942
has comment: http://stackoverflow.com/comment/86652179
favorite count: 0
type: AnsweredQuestion
tagged with: smtplib

http://stackoverflow.com/q/49879086
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86814551
has comment: http://stackoverflow.com/comment/86775877
has title: Tkinter isn't respoding while loop is running! PYTHON
tagged with: tkinter
score: 0
linked to: http://stackoverflow.com/q/36969724
has comment: http://stackoverflow.com/comment/86789708
answer count: 0
has comment: http://stackoverflow.com/comment/86774869
type: Question
has body: So I was just programming basic spam program that I could come up with in python. However when I press "Spam" button in the Tkinter window,It wont respond until function is ended :(! Here is the code : import pyautogui import time from tkinter import * import keyboard root = Tk() root.geometry("300x250") def retrive_input(): inputValue = textBox.get("1.0","end-1c") spams(inputValue) print(inputValue) textBox = Text(root,height=5,width=30) textBox.grid(row=1) buttonCommit = Button(root,height=1,width=10,text="Spam Word!",command=lambda:retrive_input()) buttonCommit.grid(row=2) def spams(wordtospam): x_cor = 962 y_cor=541 pyautogui.click(962,541) for i in range(9999): pyautogui.press("enter") pyautogui.typewrite(wordtospam) pyautogui.press("enter") time.sleep(10) pyautogui.press("enter") pyautogui.typewrite('random stuff') pyautogui.press("enter") time.sleep(8) upali = True #spams('') root.mainloop() I also want to add a keydown checker, so if I press (for example) f5, program will stop working until I press f4. Thanks ahead! (This is in game program that will spam me something :), so to type in game u press enter, typewrite, enter and it sends )

http://stackoverflow.com/a/49799647
answers question: http://stackoverflow.com/q/49797288
score: 0
has body: where s=&lt;your string&gt; for x in re.findall('(?:\s*)({.*?})', s): print(json.loads(x)) worked pretty well for me :) {'__CURSOR': 's=b0110bcb6bd44e8394728027cb5d82ce;i=b06;b=8ee885ed17a141abb35b8ef4903e8a41;m=158e9e2920;t=569a4d5ac3942;x=d80562ac11b34953', '__REALTIME_TIMESTAMP': '1523531563940162', '__MONOTONIC_TIMESTAMP': '92587043104', '_BOOT_ID': '8ee885ed17a141abb35b8ef4903e8a41', 'SYSLOG_FACILITY': '3', 'PRIORITY': '6', '_UID': '0', '_GID': '0', '_MACHINE_ID': '07c42c0296d34aea8b37c0acb2c260a8', 'SYSLOG_IDENTIFIER': 'systemd', '_TRANSPORT': 'journal', 'CODE_FILE': '../git/src/core/job.c', 'CODE_LINE': '803', 'CODE_FUNCTION': 'job_log_status_message', 'MESSAGE_ID': '39f53479d3a045ac8e11786248231fbf', 'RESULT': 'done', '_PID': '1', '_COMM': 'systemd', '_EXE': '/lib/systemd/systemd', '_CMDLINE': '/sbin/init', '_CAP_EFFECTIVE': '3fffffffff', '_SYSTEMD_CGROUP': '/init.scope', '_SYSTEMD_UNIT': 'init.scope', '_SYSTEMD_SLICE': '-.slice', '_HOSTNAME': 'tait-uvh-7381982', 'UNIT': 'audiorotator.service', 'MESSAGE': 'Started Rotates audio files if they have filled up above the high tide mark..', '_SOURCE_REALTIME_TIMESTAMP': '1523531563938118'} {...} {...}
type: Answer

http://stackoverflow.com/q/49786624
tagged with: python
has answer: http://stackoverflow.com/a/49786765
has body: I have a list as follows: A D C TELECOMMUNICATIONS COM NEW 000886309 39 6290 SH SOLE 6290 0 0 A D C TELECOMMUNICATIONS COM NEW 000886309 156 25100 SH DEFINED 2 25100 0 0 AAR CORP COM 000361105 7 305 SH SOLE 6 305 0 0 ATMOS ENERGY CORP COM 049560105 186 6342 SH SOLE 6342 0 0 CLEAR CHANNEL OUTDOOR HLDGS CL A 18451C109 6 609 SH SOLE 6 609 0 0 I am trying to transform above list to the following row by column format (where the first row contains the column titles): CUSIP VALUE SHARES DETAILS TYPE MGRNO SOLE SHARED OTHER 000886309 39 6290 SH SOLE 6290 0 0 000886309 156 25100 SH DEFINED 2 25100 0 0 000361105 7 305 SH SOLE 6 305 0 0 049560105 186 6342 SH SOLE 6342 0 0 18451C109 6 609 SH SOLE 6 609 0 0 Although I have tried some codes to transform the list into a more organized way, I got stuck with handling this step of the code. Is there any way to transform such an unclassified list? As you can see, there are occasionally gaps in the first column (which is the name of the company) and the second column (which is the stock ticker), but then the data gets cleaner (i.e., columns 3 to the end). I do actually not need the first two column information (i.e., stock ticker and firm name), but everything else. Could someone please provide some tips on how to handle such a data transformation? Thanks in advance for any tips / codes. EDITED: I thought that it would be helpful to provide the data (from a US government source) and the code to get to the part I am stuck at. Link to the text file I am working with: https://www.sec.gov/Archives/edgar/data/1364742/000108636410008916/blkinc.txt Code: def group_by_heading(some_source): buffer= [] for line in some_source: if line.startswith( "&lt;S&gt;"): if buffer: yield buffer buffer= [line] elif line.startswith("&lt;/TABLE&gt;"): break else: buffer.append(line ) yield buffer with open("/Users/MacBook/Desktop/SEC_DATA/13F/13F_BLK/0001086364-10-008916.txt", "r") as source: for heading_and_lines in group_by_heading( source ): heading= headi…
has comment: http://stackoverflow.com/comment/86588649
has comment: http://stackoverflow.com/comment/86588707
accepted answer: http://stackoverflow.com/a/49787410
tagged with: list
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49786765
has comment: http://stackoverflow.com/comment/86588577
has title: Construct column and rows from list in Python
downvote count: 1
has comment: http://stackoverflow.com/comment/86590180
score: -1
favorite count: 0
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/49787410
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86588599

http://stackoverflow.com/comment/86675820
score: 0
comment on: http://stackoverflow.com/q/49825857
type: Comment
type: QuestionComment
has text: @abarnert I have put the entire code in the post if you'd like to look not sure if everything other than this is right anyway because this is the first time I've tried using oop

http://stackoverflow.com/q/49877595
tagged with: python-3.x
has title: Does this algorithm take up too much extra space to be "in place"?
possible better answer: http://stackoverflow.com/a/49877797
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/49878002
has answer: http://stackoverflow.com/a/49877797
accepted answer: http://stackoverflow.com/a/49878121
tagged with: sorting
has comment: http://stackoverflow.com/comment/86771050
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86771803
has comment: http://stackoverflow.com/comment/86772228
tagged with: algorithm
linked to: http://stackoverflow.com/q/35484864
has answer: http://stackoverflow.com/a/49878121
tagged with: python
has comment: http://stackoverflow.com/comment/86772164
has body: The assignment is to sort negative and positive numbers from a vector. The catch is that the algorithm must be O(n) and in place. My "solution" is: def Rearrange(arr): neg = [] pos = [] for x in arr: if x &lt; 0: neg.append(x) else: pos.append(x) return neg + pos So, what I'm wondering is if this algorithm is in place or not? I know that the loop and append operations satisfy an in place algorithm. But what about the list that stores the values? Does it use too much extra space to satisfy an in place algorithm? If it does, is there an easy fix to this problem that's apparent? Right now I'm kind of stuck.
score: 2
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/q/49770671
tagged with: deep-learning
type: AnsweredQuestion
upvote count: 0
has body: I made a direct copy from the coursera`s code But it turns out like thisenter image description here What should I do? import numpy as np import h5py import matplotlib.pyplot as plt from testCases_v4 import * from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' %load_ext autoreload %autoreload 2 np.random.seed(1) that`s what I get ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-4-5084fe490343&gt; in &lt;module&gt;() 2 import h5py 3 import matplotlib.pyplot as plt ----&gt; 4 from testCases_v4 import * 5 from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward 6 ModuleNotFoundError: No module named 'testCases_v4'
accepted answer: http://stackoverflow.com/a/49772767
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/86560133
has answer: http://stackoverflow.com/a/49772767
favorite count: 0
possible better answer: http://stackoverflow.com/a/49772904
type: Question
has answer: http://stackoverflow.com/a/49772904
answer count: 2
downvote count: 2
has title: No module named 'testCases_v4'
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/86557121

http://stackoverflow.com/comment/86743112
has text: Thanks, and I've made it more explicit in my answer what the readability/taste refers to.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49863696
type: AnswerComment

http://stackoverflow.com/comment/86763473
type: Comment
score: 0
type: AnswerComment
has text: Is the same as before, where should I put it? @jezrael
comment on: http://stackoverflow.com/a/49873857

http://stackoverflow.com/q/49877816
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49878007
has title: Take two random tuples from a list, such that all elements are different
tagged with: random
score: 1
answer count: 1
downvote count: 0
has body: In Python3 I have a list of tuples as below ('A', object1) ('B', object5) ('B', object3) ('D', object2) ('E', object3) ('F', object1) ('G', object1) I want to take two random elements from the tuple such that the first and second element of the first random tuple are different that the first and second element of the second random tuple. I.e., I can select from the above list ('A', object1) and ('B', object5), but I cannot select ('F', object1) and ('G', object1) or ('B', object5) and ('B', object3).

http://stackoverflow.com/q/49862560
has body: I'm trying to setup Debug Toolbar to debug some API methods via DRF's Browsable API. I've went through the steps described on the Installation page (like updating INSTALLED_APPS, MIDDLEWARE, etc.) but still can't see any toolbar. So does Debug Toolbar work with DRF? How to debug the issue with it not showing up?
has answer: http://stackoverflow.com/a/60078702
tagged with: python
has title: Does Django Debug Toolbar work with DRF?
favorite count: 0
type: Question
downvote count: 0
tagged with: django
tagged with: django-rest-framework
tagged with: django-debug-toolbar
has answer: http://stackoverflow.com/a/53559299
accepted answer: http://stackoverflow.com/a/53559299
has comment: http://stackoverflow.com/comment/108559001
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/60078702
answer count: 3
has answer: http://stackoverflow.com/a/49862640
score: 26
upvote count: 26

http://stackoverflow.com/comment/86680510
score: 0
comment on: http://stackoverflow.com/q/49832548
has text: Secondly, your delimiter is not a comma, but the space character.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86827994
type: Comment
has text: ,like how many minutes on an average i should wait so that it will be processed by google and since i have given mysite reference in hosts can i use the same as mentioned in this question
type: AnswerComment
comment on: http://stackoverflow.com/a/49861538
score: 0

http://stackoverflow.com/q/49872471
tagged with: peewee
answer count: 1
tagged with: pymysql
has body: I am pretty new to Python and trying to use a very simple one table DB. I'm using python 3, peewee and pymysql. The database is MySQL, local on my Windows 10 PC (wampserver) and the code is; import pymysql pymysql.install_as_MySQLdb() import MySQLdb import peewee from peewee import * db = MySQLdb.connect(user='xxxxx', passwd='xxxxx', host='localhost', port=3306, db='xxxxx') class SearchUrl(peewee.Model): id = peewee.AutoField() url = peewee.TextField() page_title = peewee.TextField() date_found = peewee.DateField() date_last_changed = peewee.DateField() article_status = peewee.CharField() description = peewee.TextField() class Meta: database = db newUrl = SearchUrl.create(url='http://cropnosis.co.uk', page_title="Cropnosis Ltd.", date_found='2018-04-13', status='new', description='Cropnosis website') newUrl.save() for url in SearchUrl.filter(url='http://cropnosis.co.uk'): print(url.description) db.close() Whenever I run this I get the following error in the "SearchUrl.create" line. I have searched for the 'returning_clause' attribute but have found little or no mention of it esp. with regard to MySQL. Any help or relevant links greatly appreciated. Traceback (most recent call last): File "researcherDb.py", line 26, in &lt;module&gt; date_found='2018-04-13', status='new', description='Cropnosis website') File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5161, in create inst.save(force_insert=True) File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5284, in save pk_from_cursor = self.insert(**field_dict).execute() File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5128, in insert return ModelInsert(cls, cls._normalize_data(__data, insert)) File "C:\.dev\Client\Cropnosis\Researcher\lib\site-packages\peewee.py", line 5868, in __init__ if self.model._meta.database.returning_clause: AttributeError: 'Connection' object has no attribute 'returning_clause'
type: Question
type: AnsweredQuestion
score: 0
tagged with: python
tagged with: mysql
accepted answer: http://stackoverflow.com/a/49879484
has title: Can't seem to get Python, Peewee, pymysql & MySql database to work no 'returning_clause' error
has answer: http://stackoverflow.com/a/49879484
tagged with: python-3.x

http://stackoverflow.com/q/49821643
favorite count: 0
type: Question
has body: I am currently working on a program to help me simplify putting notes into work tickets. I have been able to get the UI working just fine on one machine but on other machines it looks different. The only issue I have is with the scrollbars. I am using Tkinter for the UI framework as that is the only one that is whitelisted and all machines are running the same Windows 7 64-bit and Python environment. from tkinter import * import tkinter as tk import tkinter.ttk as ttk import tkinter.messagebox import tkinter.simpledialog # create the window top = Tk() top.title("Notes Generator") top.resizable(0, 0) top.option_add("*Font", "Times 10") txtDiscovery = Text(top, height=6, wrap=WORD) scrolldiscovery = ttk.Scrollbar(top, orient=VERTICAL, command=txtDiscovery.yview) txtDiscovery['yscrollcommand'] = scrolldiscovery.set txtDiscovery.grid(row=3, columnspan=4, rowspan=6, padx=(8, 0), pady=8) scrolldiscovery.grid(row=3, column=4, rowspan=6, sticky='nsew', padx=(0, 8), pady=8) # Loop the loop top.mainloop() This is the way it's supposed to look This is the way it's actually looking EDIT: My apologies for not including all necessary information. The working frame of the program that still generates the layout anomaly has been included.
tagged with: python-3.x
has title: Tkinter scrollbar strangeness
has comment: http://stackoverflow.com/comment/86659429
accepted answer: http://stackoverflow.com/a/49866049
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86659463
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86658705
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86659818
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49866049
has comment: http://stackoverflow.com/comment/86660198
downvote count: 1

http://stackoverflow.com/comment/86651962
type: Comment
score: 0
type: AnswerComment
has text: Although the fastest solution, but be careful, it is wrong. Try check my data from my answer.
comment on: http://stackoverflow.com/a/49815035

http://stackoverflow.com/q/49912851
has title: 2dHistogram: ValueError: too many values to unpack (expected 2)
tagged with: pandas
score: 1
answer count: 1
tagged with: histogram
has comment: http://stackoverflow.com/comment/86843755
downvote count: 1
has answer: http://stackoverflow.com/a/49913948
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
accepted answer: http://stackoverflow.com/a/49913948
tagged with: python
has body: I am trying to create a 2d Histogram from a scatter plot. But I get the error: ValueError: too many values to unpack (expected 2) using the code below If I alter the input data to contain one list for the xy coordinates it works fine. It also works if I only select the first list in the 2dhistogram line. e.g zi, xi, yi = np.histogram2d(x[0], y[0], bins=bins). import matplotlib.pyplot as plt import numpy as np import random from functools import partial ##create list of lists (x,y coordinates) x_list = partial(random.sample, range(80), 10) y_list = partial(random.sample, range(80), 10) x = [x_list() for _ in range(10)] y = [y_list() for _ in range(10)] fig, ax = plt.subplots() ax.set_xlim(0,80) ax.set_ylim(0,80) bins = [np.linspace(*ax.get_xlim(), 80), np.linspace(*ax.get_ylim(), 80)] ##error occurs in this line zi, xi, yi = np.histogram2d(x, y, bins=bins) zi = np.ma.masked_equal(zi, 0) ax.pcolormesh(xi, yi, zi.T) ax.set_xticks(bins[0], minor=True) ax.set_yticks(bins[1], minor=True) ax.grid(True, which='minor') scat = ax.scatter(x, y, s = 1) The only post I could find about this suggested to try and change the x,y to a numpy array. I tried this but still get the same error code. zi, xi, yi = np.histogram2d(np.asarry(x), np.asarray(y), bins=bins) Any other suggestions?
has comment: http://stackoverflow.com/comment/86842734
linked to: http://stackoverflow.com/q/952914
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86842544

http://stackoverflow.com/q/49821426
has body: I'm trying to make a custom queryset where I need to check the type of a foreign key. The code below works but seems not optimal to me: class BadgeQuerySet(models.QuerySet): def linked_to_convive(self): pks_badges_linked_to_convive = [badge.pk for badge in Badge.objects.all() if badge.owner and type(badge.owner.profile) == Convive] return self.filter(pk__in=pks_badges_linked_to_convive) I browsed Django doc and didn't find something like this: Badge.objects.filter(owner__profile__type=Convive) Question 1: Why Django does not provide this kind of tool? Question 2: Is there a way to improve my working code, making it simpler? Thanks.
has comment: http://stackoverflow.com/comment/86658419
has comment: http://stackoverflow.com/comment/86658558
favorite count: 0
has comment: http://stackoverflow.com/comment/86658294
type: Question
answer count: 0
type: UnansweredQuestion
has title: Filter by type in Django queryset?
downvote count: 0
tagged with: django
tagged with: python
score: 3
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/86658359
upvote count: 3
has comment: http://stackoverflow.com/comment/86658439

http://stackoverflow.com/comment/86735430
has text: Why not just use an ordered dict?
score: 0
comment on: http://stackoverflow.com/q/49860217
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52723956
answers question: http://stackoverflow.com/q/49855087
has body: Instead of use apply_async try with: pool = Pool(cores) df = pd.concat(pool.map(func, [value_1,...,value_n])) pool.close() pool.join() I wrote you my code that it works great and I expect you can reuse some lines. Basically, I run multiples queries in Athena at the "same" time (I parallelized the array named endpoints), and I store each result in a row of a Pandas dataframe. Also, you can fetch data for each query and I added a status print then you can see the status of each query. Remember that Athena has a limit of queries that you can run concurrently. import time import boto3 import pandas as pd from multiprocessing import Pool class QueryAthena: def __init__(self, endpoint, init_date, end_date): self.s3_input = 's3://my_bucket/input' self.s3_output = 's3://my_bucket/output' self.database = 'datalake' self.table = 'my_table' self.endpoint = "'" + endpoint + "'" self.init_date = "'" + init_date + "'" self.end_date = "'" + end_date + "'" self.year = self.init_date[1:5] self.month = self.init_date[6:8] self.day = self.init_date[9:11] self.region_name = 'us-east-1' self.aws_access_key_id = "my_id" self.aws_secret_access_key = "my_key" def load_conf(self, q): self.client = boto3.client('athena', region_name = self.region_name, aws_access_key_id = self.aws_access_key_id, aws_secret_access_key= self.aws_secret_access_key) try: response = self.client.start_query_execution( QueryString = q, QueryExecutionContext={ 'Database': self.database }, ResultConfiguration={ 'OutputLocation': self.s3_output, } ) print('Execution ID: ' + response['QueryExecutionId']) except Exception as e: print(e) return response def query(self): self.query = "SELECT count(*) as total_requests, SUM(CASE WHEN count_endpoints &gt; 1 THEN 1 ELSE 0 END) as total_repeated, AVG(CASE WHEN count_endpoints &gt; 1 THEN count_endpoints END) as TRAFFIC_QUALITY FROM (SELECT * from (SELECT domain, size, device_id, ip, array_join(array_agg(distinct endpoint), ',') as endpoints_all, count(distinct endpoint) as co…
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/q/49762947
answer count: 2
has comment: http://stackoverflow.com/comment/86541564
linked to: http://stackoverflow.com/q/1653970
has comment: http://stackoverflow.com/comment/86541562
has answer: http://stackoverflow.com/a/49763202
has answer: http://stackoverflow.com/a/49763167
possible better answer: http://stackoverflow.com/a/49763167
has comment: http://stackoverflow.com/comment/86541615
accepted answer: http://stackoverflow.com/a/49763202
downvote count: 3
has comment: http://stackoverflow.com/comment/86541634
has comment: http://stackoverflow.com/comment/86541586
has comment: http://stackoverflow.com/comment/86541521
upvote count: 1
has body: I want to remove all duplicates values from a list of list. So I have a list of lists like this. a=[['102 min', '', 'Comedy', 'User Rating: 6.6/10 (4,072 user ratings)', '69', 'Metascore', '', 'Rank:', '10', 'Showtimes:', 'Studio Movie Grill - Downey', '11:00 am', '', '1:35 pm', '', '4:10', '', '4:55', '', '7:40', '', '9:55', '', '10:35'], ['110 min', '', 'Comedy', '', 'Drama', '', 'Romance', 'User Rating: 8.1/10 (11,478 user ratings)', '73', 'Metascore', '', 'Rank:', '18', 'Showtimes:', 'Studio Movie Grill - Downey', '11:30 am', '', '2:10 pm', '', '4:45', '', '7:25', '', '10:00'], ['111 min', '', 'Action', '', 'Adventure', '', 'SciFi', 'User Rating: 6/10 (23,905 user ratings)', '44', 'Metascore', '', 'Rank:', '7', 'Showtimes:', 'Studio Movie Grill - Downey', '11:05 am', '', '1:50 pm', '', '4:35', '', '7:20', '', '10:05'], ['118 min', '', 'Action', '', 'Adventure', '', 'Drama', '', 'Fantasy', '', 'Thriller', 'User Rating: 6.8/10 (45,126 user ratings)', '48', 'Metascore', '', 'Rank:', '8', 'Showtimes:', 'Studio Movie Grill - Downey', '11:10 am', '', '1:55 pm', '', '4:40', '', '7:35', '', '10:20'], ['120 min', '', 'Thriller', 'User Rating: 4.9/10 (1,002 user ratings)', '32', 'Metascore', '', 'Rank:', '16', 'Showtimes:', 'Studio Movie Grill - Downey', '11:20 am', '', '2:05 pm', '', '4:50', '', '7:45', '', '10:40'], ['134 min', '', 'Action', '', 'Adventure', '', 'SciFi', 'User Rating: 7.8/10 (223,161 user ratings)', '88', 'Metascore', '', 'Rank:', '4', 'Showtimes:', 'Studio Movie Grill - Downey', '12:00 pm', '', '4:05', '', '7:15', '', '10:15'], ['140 min', '', 'Action', '', 'Adventure', '', 'SciFi', 'User Rating: 7.9/10 (76,138 user ratings)', '64', 'Metascore', '', 'Rank:', '1', 'Showtimes:', 'Studio Movie Grill - Downey', '11:45 am', '', '4:00 pm', '', '7:10', '', '10:10'], ['86 min', '', 'Animation', '', 'Adventure', '', 'Comedy', '', 'Family', '', 'Fantasy', '', 'Mystery', '', 'Romance', 'User Rating: 4.7/10 (1,275 user ratings)', '36', 'Metascore', '', 'Rank:', '7…
favorite count: 0
has comment: http://stackoverflow.com/comment/86541708
type: Question
has comment: http://stackoverflow.com/comment/86541778
has comment: http://stackoverflow.com/comment/86541874
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86541646
has comment: http://stackoverflow.com/comment/86541577
score: -2
has comment: http://stackoverflow.com/comment/86541736
has comment: http://stackoverflow.com/comment/86541542
tagged with: python
has title: remove all duplicates values from a list of list
has comment: http://stackoverflow.com/comment/86541734
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86541935
has comment: http://stackoverflow.com/comment/86541834

http://stackoverflow.com/q/49819148
score: 1
has title: TensorFlow can't convert from float32 to float32_ref while restoring frozen_graph
tagged with: tensorflow
favorite count: 0
type: Question
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
has body: I've having this issue where I want to import a TensorFlow graph I've previously frozen. The error : graph_def is invalid at node 'block1/conv2d/kernel/Assign': Input tensor 'block1/conv2d/kernel:0' Cannot convert a tensor of type float32 to an input of type float32_ref. I've built a custom model mainly for proof of concept purpose within my application. I'm using the tf.layers wrappers for the conv2d and batch_norm. The custom model code : ... @staticmethod def conv_batch_relu(inputs, filters, kernel_size, is_training): cv = tf.layers.conv2d(inputs=inputs, filters=filters, kernel_size=kernel_size, use_bias=True, activation=None) bn = tf.layers.batch_normalization(inputs=cv, training=is_training, fused=True) return tf.nn.relu(bn) def build_network(self): x = tf.placeholder(tf.float32, [None] + self.dataset['input_dims'], name='input') y = tf.placeholder(tf.float32, [None] + [self.dataset['output_dims']], name='labels') is_training = tf.placeholder(tf.bool, name='is_training') with tf.variable_scope('block1'): conv1 = CNN.conv_batch_relu(inputs=self.x, filters=64, kernel_size=3, is_training=self.is_training) conv2 = CNN.conv_batch_relu(inputs=conv1, filters=64, kernel_size=3, is_training=self.is_training) pool1 = tf.layers.max_pooling2d(inputs=conv2, pool_size=2, strides=2) with tf.variable_scope('block2'): conv3 = CNN.conv_batch_relu(inputs=pool1, filters=128, kernel_size=3, is_training=self.is_training) conv4 = CNN.conv_batch_relu(inputs=conv3, filters=128, kernel_size=3, is_training=self.is_training) pool2 = tf.layers.max_pooling2d(inputs=conv4, pool_size=2, strides=2) next_shape = int(pool2.shape[1] * pool2.shape[2] * pool2.shape[3]) next_output = (next_shape // 4) with tf.name_scope('fc1'): flat_fc1 = tf.layers.flatten(inputs=pool2) fc1 = tf.layers.dense(inputs=flat_fc1, units=next_output, activation=tf.nn.relu) with tf.name_scope('dropout'): fc1_drop = tf.layers.dropout(inputs=fc1) with tf.name_scope('logits'): self.yhat = tf.layers.dense(inputs=fc1_drop, units…
upvote count: 1

http://stackoverflow.com/a/49767553
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49765382
has comment: http://stackoverflow.com/comment/86576216
score: 1
answers question: http://stackoverflow.com/q/49765382
type: Answer
has body: Since @Paul Panzer solution didn't give out the same output as your function, I revised on his work by trying boolean array. Hopefully its what you want. Code: def my_translate(arr, x=0): arr = arr.copy() if x == 0: return arr.copy() elif x &gt; 0: replacement1 = np.zeros(arr.shape) replacement1[:-x] = arr[x:] else: replacement1 = np.zeros(arr.shape) replacement1[-x:] = arr[:x] replacement2 = np.zeros(arr.shape)+255 # Array filled with 255 for second logic l = [np.repeat(i,arr.shape[1]) for i in range(arr.shape[0])] firstlooplogic1 = np.asarray(l)+x &lt; arr.shape[0] firstlooplogic2 = np.asarray(l)+x &gt; 0 secondlooplogic1 = np.asarray(l)+x &gt; arr.shape[0] secondlooplogic2 = np.asarray(l)+x &lt; 0 part1logic = np.logical_and(firstlooplogic1,firstlooplogic2) part2logic = np.logical_or(secondlooplogic1,secondlooplogic2) part1 = part1logic*replacement1 part2 = part2logic*replacement2 part3 = ((part1 == 0) * (part2 == 0)) * arr return (part1 + part2 +part3).astype(arr.dtype) Result: arr = 3 - np.maximum.outer(*2*(np.abs(np.arange(-3, 4)),)) output1 = my_translate(arr,-2) #output from my function output2 = translate(arr,-2) #output from your function above np.array_equal(output1,output2) &gt;Out[10]: True Basically, I just break down your nested for-loop into boolean array and do the operation.
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49758505
has body: At the moment you are only outputting one td for each row. {% for instance in query %} {% for field, value in instance.items %} {{ value }} {% endfor %} {% endfor %} It sounds like should loop inside the tr tag: {% for instance in query %} {% for field, value in instance.items %} {{ value }} {% endfor %} {% endfor %} However, you can't assume the order of the keys in the dictionary, so you should either access the items by key, or rethink whether you want to use dictfetchall. {% for instance in query %} {{ instance.EQUIP_ID }} {{ instance.LINE_ID }} {{ instance.PLANT_CODE }} {% endfor %} {% endfor %}
accepted answer of: http://stackoverflow.com/q/49758347
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/86532140
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49758347

http://stackoverflow.com/a/49823013
downvote count: 1
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/86679639
score: 0
answers question: http://stackoverflow.com/q/49817786
has comment: http://stackoverflow.com/comment/86676215
has body: press ctrl+shift+p to launch command pallete and type python interpreter and you will get an option select interpreter then select python interpreter Choosing an environment By default, the Python extension relies on the first Python interpreter it finds in the path, but it's easy to switch between environments. To use a specific interpreter, select the Python: Select Interpreter command from the Command Palette (Ctrl+Shift+P).

http://stackoverflow.com/q/49815924
type: AnsweredQuestion
tagged with: printing
answer count: 3
possible better answer: http://stackoverflow.com/a/73200273
has body: I'm trying to build a function that prints a given string in large text through command line. Each letter is a 5x5 grid of *'s and spaces. How would I print the next 5x5 character on the same line as the previous to print out the given string? Code: options = { 'a': ' * \n * * \n*****\n* *\n* *', 'b': '**** \n* *\n*****\n* *\n**** ', 'c': ' ****\n* \n* \n* \n ****', 'd': '**** \n* *\n* *\n* *\n**** ', 'e': '*****\n* \n*****\n* \n*****', 'f': '*****\n* \n*****\n* \n* ', 'g': '*****\n* \n* ***\n* *\n*****', 'h': '* *\n* *\n*****\n* *\n* *', 'i': '*****\n * \n * \n * \n*****', 'j': '*** \n * \n * \n * \n*** ', 'k': '* *\n* * \n* \n* * \n* *', 'l': '* \n* \n* \n* \n*****', 'm': '* *\n** **\n* * *\n* *\n* *', 'n': '* *\n** *\n* * *\n* **\n* *', 'o': ' *** \n* *\n* *\n* *\n *** ', 'p': '**** \n* *\n**** \n* \n* ', 'q': ' *** \n* *\n* * *\n* * \n ** *', 'r': '**** \n* *\n**** \n* * \n* **', 's': ' ****\n* \n *** \n *\n**** ', 't': '*****\n * \n * \n * \n * ', 'u': '* *\n* *\n* *\n* *\n *** ', 'v': '* *\n* *\n * * \n * * \n * ', 'w': '* *\n* *\n* * *\n* * *\n * * ', 'x': '* *\n * * \n * \n * * \n* *', 'y': '* *\n * * \n * \n * \n * ', 'z': '*****\n * \n * \n * \n*****', ',': ' \n \n **\n **\n * ', ':': ' \n * \n \n * \n ' } def Print_Big(inputString): lst = list(inputString) for i in lst: print(options[i], end = "") while True: userIn = input('Please enter a letter to big-ify: ').lower() if userIn == "exit": break elif userIn != "" and len(userIn) &gt;= 1: Print_Big(userIn) else: print('Please enter a valid string')
tagged with: formatting
accepted answer: http://stackoverflow.com/a/49817784
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/49817784
linked to: http://stackoverflow.com/q/312443
has answer: http://stackoverflow.com/a/73200273
downvote count: 0
has answer: http://stackoverflow.com/a/49833202
tagged with: python
score: 4
has title: Python: How to print a 5x5 grid on the same line as another

http://stackoverflow.com/q/49780627
accepted answer: http://stackoverflow.com/a/50106090
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50106090
tagged with: python
has comment: http://stackoverflow.com/comment/86605553
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: expression
tagged with: cvxpy
has title: CVXPY expression doesn't give expected result
has body: I am using CVXPY (version 1.0). I do not understand what causes the difference between a ZERO expression and a NONNEGATIVE expression as demonstrated by the following code: &gt;&gt;&gt; import cvxpy as cv &gt;&gt;&gt; a = cv.Variable(1) &gt;&gt;&gt; b = cv.Variable(1) &gt;&gt;&gt; print((cv.square(a-b)*1/(1e-6)).__repr__()) Expression(CONSTANT, ZERO, (1,)) &gt;&gt;&gt; print((cv.square(a-b)*float(1/1e-6)).__repr__()) Expression(CONVEX, NONNEGATIVE, (1,))
type: Question
upvote count: 2

http://stackoverflow.com/comment/86588129
type: AnswerComment
comment on: http://stackoverflow.com/a/49786016
score: 0
type: Comment
has text: The OP isn't explicitly calling `next()`...and the rest of your answer sounds mostly like pure speculation to me.

http://stackoverflow.com/q/49876947
upvote count: 1
has answer: http://stackoverflow.com/a/49877050
tagged with: loops
has title: Python: loop doesn't break
has comment: http://stackoverflow.com/comment/86770267
favorite count: 0
type: Question
has body: Having problem with breaking the loop. I want to break it when it reach the end word. Hopefully you can help me what's I'm missing on this code. Thank you. def y(): with open('test.conf', 'r') as rf: x = list() for line in rf: if 'config system global' in line: x.append('config system global\n') while True: x.append(rf.__next__()) if 'end\n' in line: break with open('test.txt', 'w') as wf: wf.writelines(x) config system global set admin-maintainer disable set admin-scp enable set admin-server-cert "Fortinet_Firmware" set admintimeout 15 set anti-replay disable set fgd-alert-subscription advisory latest-threat set gui-dynamic-routing enable set gui-multiple-utm-profiles enable set gui-replacement-message-groups enable set gui-sslvpn-personal-bookmarks enable set gui-sslvpn-realms enable set gui-wireless-opensecurity enable set hostname "XXXXXX" set internal-switch-mode interface set revision-backup-on-logout enable set revision-image-auto-backup enable set strong-crypto enable set tcp-timewait-timer 120 set timezone 80 set vdom-admin enable end config system accprofile edit "prof_admin" set admingrp read-write set authgrp read-write set endpoint-control-grp read-write set fwgrp read-write set loggrp read-write set mntgrp read-write set netgrp read-write set routegrp read-write set sysgrp read-write set updategrp read-write set utmgrp read-write set vpngrp read-write set wanoptgrp read-write set wifi read-write
accepted answer: http://stackoverflow.com/a/49877996
tagged with: break
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86769961
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/49877050
has answer: http://stackoverflow.com/a/49877996
has comment: http://stackoverflow.com/comment/86769907
score: 1

http://stackoverflow.com/comment/86834157
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49908829
has text: sorry, wanted to know how to make the output dependent on the input, right now the code executes and gives me a constant wall of numbers that are the same (all the multiplication tables of 1-12) I am very new to programming and am not sure what I am doing wrong at the moment. Thank you for your time
score: 0

http://stackoverflow.com/comment/86546188
has text: I think you are missing refindex, which contains n_calc according to the import statement in fir.py.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49761020

http://stackoverflow.com/comment/86682712
has text: @tdelaney you are right, forgot about that one, updated my answer
type: AnswerComment
comment on: http://stackoverflow.com/a/49833624
score: 0
type: Comment

http://stackoverflow.com/comment/86654141
type: Comment
type: QuestionComment
has text: oh you're using windows... which program .sh files are associated to? Try "cmd /c sleep.sh" in a console, see if that blocks...
score: 1
comment on: http://stackoverflow.com/q/49819399

http://stackoverflow.com/a/49843297
downvote count: 0
type: Answer
has body: Use UnevaluatedExpr(5) instead of 5: &gt;&gt;&gt; latex(f.subs(x, UnevaluatedExpr(5))) '\\sqrt{2 + 3 \\cdot 5}' This wrapper prevents the expression inside of it ("5") from interacting with the outside terms. Reference: Prevent expression evaluation The order of addends isn't the same after substitution, as 3*x + 2 and 3*5 + 2 get sorted differently by the printer. To avoid this, one can use order='none' which keeps whatever internal order the arguments have, without trying to put them in a human-friendly arrangement. &gt;&gt;&gt; latex(f, order='none') '\\sqrt{2 + 3 x}' &gt;&gt;&gt; latex(f.subs(x, UnevaluatedExpr(5)), order='none') '\\sqrt{2 + 3 \\cdot 5}'
upvote count: 3
answers question: http://stackoverflow.com/q/49842196
score: 3

http://stackoverflow.com/comment/86700007
score: 0
comment on: http://stackoverflow.com/a/49842389
has text: I am not getting errors. But it's not clicking on the item
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49842398
has body: Properties can't take arguments. But there is no reason to make this a property. You are calling it as a normal method. Remove the @property decorator. Also note, your code is pretty inefficient. There's no need to query all the related users and iterate through. If you just want to get the first user that isn't current_user, then do so directly: return self.users.exclude(username=current_user.username).first()
accepted answer of: http://stackoverflow.com/q/49842200
type: Answer
answers question: http://stackoverflow.com/q/49842200
upvote count: 4
score: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49789836
has comment: http://stackoverflow.com/comment/86633659
has comment: http://stackoverflow.com/comment/86595548
score: 1
has comment: http://stackoverflow.com/comment/86633585
has comment: http://stackoverflow.com/comment/86597234
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49789478
has body: You want to measure how "close" the prediction vector is to the expected vector. A good formula that describes the "amount of difference" between two vectors is to check the magnitude (or square magnitude) of the delta vector (prediction - expected). In this case, you can do something like this: def square_magnitude(vector): return sum(x*x for x in vector) def inaccuracy(pred, test): #should only get equal-length items return square_magnitude([pred[i] - test[i] for i in range(len(pred))]) / len(pred) Since you have three samples: total_inaccuracy = sum(inaccuracy(y_pred[i], y_test[i]) for i in range(len(y_pred))) / len(y_pred) This should be 0 when it's perfectly accurate and higher (positive) when it's less accurate.
has comment: http://stackoverflow.com/comment/86595082
type: Answer
has comment: http://stackoverflow.com/comment/86595676
has comment: http://stackoverflow.com/comment/86597163

http://stackoverflow.com/comment/86742112
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49861287
has text: @Sacul, What if i want to convert the dictionary to a dataframe again? Because i read like the value is stored as string
type: Comment

http://stackoverflow.com/comment/86577833
type: Comment
comment on: http://stackoverflow.com/a/49775382
score: 0
type: AnswerComment
has text: Not entirely correct. Creating a list out of range is quick, and you do it once and load it to memory. Then when *iteration* starts it accesses list[index]. All items are accessed in *O(1)* while with generators, accessing an item is a different story - you actually executes code, and yield *one* object. Then again on next iteration, and again.. so yielding an element (in the OP scenario) is more *expensive* in terms of time than just accessing a *ready* list. Also, I'm pretty sure there are some optimizations when generating a list.

http://stackoverflow.com/q/49859230
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49955095
tagged with: python
has comment: http://stackoverflow.com/comment/86786971
tagged with: arcpy
score: 0
has body: I have a python script to add points to a feature class. The points have an XY value but they don't display where they should on the map. I've read Adding new record with specific coordinates into shapefile using ArcGIS for Desktop? so I understand why it isn't working. And I know I can export the FC to a table, display XY data and save to a shapefile. My question is, can this all be automated in a python script and if so, what happens at the end when the I run the script to add another point? Also I've tried using arcpy.MakeXYEventLayer_management and arcpy.SaveToLayerFile_management but nothing seems to appear. I'd be grateful to anyone who gets back to me with some advise. Thanks Here is the code I'm trying; import arcpy, os arcpy.env.workspace = r'F:\MyWork\Assignment\folklore.gdb' arcpy.MakeXYEventLayer_management('Folklore', 'x_coord', 'y_coord', 'folklore_Layer', "PROJCS['IRENET95_Irish_Transverse_Mercator',GEOGCS['GCS_IRENET95',DATUM['D_IRENET95',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',600000.0],PARAMETER['False_Northing',750000.0],PARAMETER['Central_Meridian',-8.0],PARAMETER['Scale_Factor',0.99982],PARAMETER['Latitude_Of_Origin',53.5],UNIT['Meter',1.0]];-5022200 -15179500 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision", '#') save_output = r'F:\MyWork\Assignment\studyquadsLyr.lyr' save_output2 = r'F:\MyWork\Assignment\folklore.gdb/folklore' arcpy.SaveToLayerFile_management('folklore_Layer', save_output) arcpy.Delete_management(r'F:\MyWork\Assignment\folklore.gdb/folklore') arcpy.CopyFeatures_management('studyquadsLyr.lyr', save_output2)
answer count: 1
upvote count: 1
has title: arcpy; create points with XY and display them correctly
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86735044

http://stackoverflow.com/q/49792651
has comment: http://stackoverflow.com/comment/86602144
has comment: http://stackoverflow.com/comment/86600003
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86599875
tagged with: pandas
has body: I am extracting some data from an API and having challenges transforming it into a proper dataframe. The resulting DataFrame df is arranged as such: Index Column 0 {'email@email.com': [{'action': 'data', 'date': 'date'}, {'action': 'data', 'date': 'date'}]} 1 {'different-email@email.com': [{'action': 'data', 'date': 'date'}]} I am trying to split the emails into one column and the list into a separate column: Index Column1 Column2 0 email@email.com [{'action': 'data', 'date': 'date'}, {'action': 'data', 'date': 'date'}]} Ideally, each 'action'/'date' would have it's own separate row, however I believe I can do the further unpacking myself. After looking around I tried/failed lots of solutions such as: df.apply(pd.Series) # does nothing pd.DataFrame(df['column'].values.tolist()) # makes each dictionary key as a separate colum where most of the rows are NaN except one which has the pair value Edit: As many of the questions asked the initial format of the data in the API, it's a list of dictionaries: [{'email@email.com': [{'action': 'data', 'date': 'date'}, {'action': 'data', 'date': 'date'}]},{'different-email@email.com': [{'action': 'data', 'date': 'date'}]}] Thanks
has title: Separate pd DataFrame Rows that are dictionaries into columns
has comment: http://stackoverflow.com/comment/86601809
has comment: http://stackoverflow.com/comment/86600130
has comment: http://stackoverflow.com/comment/86601904
has comment: http://stackoverflow.com/comment/86600867
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86600741
has comment: http://stackoverflow.com/comment/86599740
has answer: http://stackoverflow.com/a/49793109
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49793065
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86600216

http://stackoverflow.com/a/49788993
has comment: http://stackoverflow.com/comment/86694408
answers question: http://stackoverflow.com/q/49787327
downvote count: 2
type: Answer
score: 6
has body: The error says it all : selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home The error clearly mentions that the chromedriver which is getting detected have wrong permissions. Solution Download the latest chromedriver binary from ChromeDriver - WebDriver for Chrome and save it in your system. Ensure that chromedriver binary have the required permissions. While initiating the WebDriver and WebClient pass the argument executable_path along with the absolute path of the chromedriver binary as follows : from selenium import webdriver link = "https://accounts.google.com" driver = webdriver.Chrome(executable_path='/path/to/chromedriver') driver.get(link) Reference You can find a detailed relevant discussion in: 'Webdrivers' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49787327
upvote count: 8

http://stackoverflow.com/a/49918714
type: Answer
score: 2
has body: App Engine does not support what you want in the way that you want it. There are a few alternative approaches that you might want to consider. It sounds like your primary constraint is wanting to enable individual developers to store alternative configuration to what they might find in production. You might want to consider allowing developers to store said configuration in their local Datastore instances. Your code would look something like: if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'): unix_socket = os.environ['CLOUDSQL_INSTANCES_DIR'] ... else: unix_socket = your_configuration_type.get("CLOUDSQL_INSTANCES_DIR") ... Another alternative would be the approach outlined here where you'd store the relevant env vars in your own version of client_secrets.json and made sure that file was listed in .gitignore.
downvote count: 0
answers question: http://stackoverflow.com/q/49904890
upvote count: 2

http://stackoverflow.com/a/52290497
has comment: http://stackoverflow.com/comment/116753374
type: Answer
has body: I had the same issue just recently. I think mypy does not (yet) support the special behavior of __new__(). My workaround is using typing.cast() twice, like this: def __new__(cls, x: str) -&gt; "B": return typing.cast( "B", super().__new__( typing.cast(typing.Type[A], cls), int(x), ), )
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49795830

http://stackoverflow.com/a/49825211
has body: Keras' functional api lets you call layers. This lets you chain another layer on top the output of an existing layer by calling it. For example here: encoder_inputs = Input(shape=(None, num_encoder_tokens)) encoder = LSTM(latent_dim, return_sequences=True) encoder_outputs, state_h, state_c = LSTM(latent_dim, return_state=True)(encoder(encoder_inputs))
accepted answer of: http://stackoverflow.com/q/49824967
type: Answer
has comment: http://stackoverflow.com/comment/91871353
has comment: http://stackoverflow.com/comment/86671939
score: 4
answers question: http://stackoverflow.com/q/49824967
upvote count: 4
has comment: http://stackoverflow.com/comment/96686806
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49956566
type: Answer
score: 4
has body: You got a logic problem on integers, not a representation problem. Neural networks are relevant to problem with complex representation (eg., image with pixels, objects in differents shape and color, sometimes hidden etc), as they build their own set of features (descriptors) and mipmaps; they also are a good match with problems dealing with reals, not integer; and last, as they are today, they don't really deal with reasonning and logic, or eventually with simple logic like a small succession of if/else or switch but we don't really have a control over that. What I see is closer to a cryptographic-ish problem with constraints (10% change, max 100 articles). Solution for all sets of fruits There is a way to reach all solutions very quickly. We start by factoring into primes the total, then we find few solutions through brute force. From there we can change the set of fruits with equal total. Eg., we exchange 1 orange for 1 apple and 1 pear with prices = (1,2,3). This way we can navigate through solutions without having to go through brute force. Algorithm(s): you factorize in prime numbers the total, then you split them into two or more groups; let's take 2 groups: let A be one common multiplier, and let B the other(s). Then you can add your fruits to reach the total B. Examples: Day 1: Apple = 1, Pears = 2, Oranges = 3, Basket Value = 217 Day 2: Apple = 2, Pears = 3, Oranges = 5, Basket Value = 348 217 factorizes into [7, 31], we pick 31 as A (common multiplier), then let say 7=3*2+1 (2 orange, 0 pear, 1 apple), you got an answer: 62 oranges, 0 pears, 31 apples. 62+31&lt;100: valid. 348 factorizes into [2, 2, 3, 29], you have several ways to group your factors and multiply your fruits inside this. The multiplier can be 29, (or 2*29 etc), then you pick your fruits to reach 12. Let's say 12=2*2+3+5. You got (2 apples, 1 pear, 1 orange) * 29, but it's more than 100 articles. You can fuse recursively 1 apple and 1 pear into 1 orange until you are below 100 articles, or …
has comment: http://stackoverflow.com/comment/86941211
has comment: http://stackoverflow.com/comment/86946981
has comment: http://stackoverflow.com/comment/86947033
has comment: http://stackoverflow.com/comment/86957628
answers question: http://stackoverflow.com/q/49890536
upvote count: 4
has comment: http://stackoverflow.com/comment/87086609
has comment: http://stackoverflow.com/comment/86975828
has comment: http://stackoverflow.com/comment/86991382
has comment: http://stackoverflow.com/comment/86946996
has comment: http://stackoverflow.com/comment/86985934
downvote count: 0

http://stackoverflow.com/q/49838872
has comment: http://stackoverflow.com/comment/86693297
score: -1
has comment: http://stackoverflow.com/comment/86693148
linked to: http://stackoverflow.com/q/49757471
has body: I have a list of lists, say [[1,2], [2,3], [1,3]] to list of tuples [(1,2), (2,3), (1,3)]. This can be accomplished easily by list comprehensions as [tuple(l) for l in list] This however will be slow for large lists. So I would like to perform the same using pure numpy operations. Edit 1 I will try to make it more clear. I have a function say foo() which will return a python list of lists def foo(*args): # Do something return arr arr will have a list of lists structure arr = [[a,b], [c,d],...]. Each inner list ( e.g [a, b]) will be 2 elements long, and arr will contain a large number of such lists (typically larger than 90,000). I however, require each inner list to be a tuple, for immutability, like arr = [(a,b), (c, d),...] This can be performed using list comprehensions as def result(arr): return [tuple(l) for l in arr] However, considering that the list is large, I would avoid this, and use pure numpy functions to accomplish this. (as @hpaulj suggested using arr.view(), see his other method using dict() and zip() in his answer below). I would like to know if this is feasible or not. If feasible, please tell me how.
tagged with: numpy
type: AnsweredQuestion
has title: list of lists to list of tuples without loops or list comprehensions
has comment: http://stackoverflow.com/comment/86692843
has comment: http://stackoverflow.com/comment/86692828
has comment: http://stackoverflow.com/comment/86693019
has comment: http://stackoverflow.com/comment/86692973
downvote count: 2
accepted answer: http://stackoverflow.com/a/49839182
has comment: http://stackoverflow.com/comment/86692733
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49839182
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86692825
has comment: http://stackoverflow.com/comment/86693120
has comment: http://stackoverflow.com/comment/86692890
tagged with: python

http://stackoverflow.com/q/49892444
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86800736
tagged with: python
score: -1
type: Question
has title: print similar word matches to the number using python
accepted answer: http://stackoverflow.com/a/49893118
upvote count: 0
has comment: http://stackoverflow.com/comment/86801733
answer count: 1
has answer: http://stackoverflow.com/a/49893118
has comment: http://stackoverflow.com/comment/86804980
has comment: http://stackoverflow.com/comment/86800652
has comment: http://stackoverflow.com/comment/86800548
downvote count: 1
favorite count: 0
has body: I have a text file which contains - A 1 2 @ ~ 7 8 3 12389390 B 1 3 6 ~ 1 1 9 -3 2 34789021 C 4 5 ~ 2 4 1 1 $ -1 12389390 D 2 4 1 ~ 1 1 @ -1 6 @ 34789021 E 3 3 9 ~ 2 4 0 -1 2 12389390 34789021 25909052 The output should be - A C E B D E E Because the value of A,C,E have same numbers. I have tried this code - import re maxline = 7 with open ('letter.txt','r') as file: for line in file: if re.match('^[a-zA-Z]+', line) is not None: print(line.split()[0]) with open('letter.csv','a+') as output: output.write(line) The outputs are like - A B C D E I just print the first letter of each line. But could not find any logic to do just like the output should be.Is there any way to do this?
has comment: http://stackoverflow.com/comment/86804088
tagged with: logic
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86801354
has comment: http://stackoverflow.com/comment/86804945

http://stackoverflow.com/comment/86825877
has text: Are those links really having content?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49904801
type: QuestionComment

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/49873194
tags question: http://stackoverflow.com/q/49777828
tags question: http://stackoverflow.com/q/49787200
tags question: http://stackoverflow.com/q/49884143
tags question: http://stackoverflow.com/q/49783892
tags question: http://stackoverflow.com/q/49826277
tags question: http://stackoverflow.com/q/49831402
tags question: http://stackoverflow.com/q/49800438
tags question: http://stackoverflow.com/q/49886388
tags question: http://stackoverflow.com/q/49805707
tags question: http://stackoverflow.com/q/49882131
tags question: http://stackoverflow.com/q/49819853
tags question: http://stackoverflow.com/q/49793830
tags question: http://stackoverflow.com/q/49887289
tags question: http://stackoverflow.com/q/49760763
tags question: http://stackoverflow.com/q/49805467
tags question: http://stackoverflow.com/q/49910402
tags question: http://stackoverflow.com/q/49860354
tags question: http://stackoverflow.com/q/49912393
tags question: http://stackoverflow.com/q/49838179
tags question: http://stackoverflow.com/q/49867912
tags question: http://stackoverflow.com/q/49854765
tags question: http://stackoverflow.com/q/49849567
tags question: http://stackoverflow.com/q/49828956
tags question: http://stackoverflow.com/q/49834210
tags question: http://stackoverflow.com/q/49903773
tags question: http://stackoverflow.com/q/49808157
tags question: http://stackoverflow.com/q/49832618
tags question: http://stackoverflow.com/q/49758864
tags question: http://stackoverflow.com/q/49826581
tags question: http://stackoverflow.com/q/49787118
tags question: http://stackoverflow.com/q/49878632
tags question: http://stackoverflow.com/q/49832735
tags question: http://stackoverflow.com/q/49809231
tags question: http://stackoverflow.com/q/49825133
tags question: http://stackoverflow.com/q/49833648
tags question: http://stackoverflow.com/q/49872426
tags question: http://stackoverflow.com/q/49770909
tags question: http://stackoverflow.com/q/49791969
type: Tag
tags question: http://stackoverflow.com/q/49845144
tag name: html
tags question: http://stackoverflow.com/q/49881000
tags question: http://stackoverflow.com/q/49861167
tags question: http://stackoverflow.com/q/49890130
tags question: http://stackoverflow.com/q/49758347
tags question: http://stackoverflow.com/q/49889448
tags question: http://stackoverflow.com/q/49851316
tags question: http://stackoverflow.com/q/49794878
tags question: http://stackoverflow.com/q/49799905
tags question: http://stackoverflow.com/q/49859752
tags question: http://stackoverflow.com/q/49898071
tags question: http://stackoverflow.com/q/49824504
tags question: http://stackoverflow.com/q/49767015
tags question: http://stackoverflow.com/q/49898842
tags question: http://stackoverflow.com/q/49776101
tags question: http://stackoverflow.com/q/49862691
tags question: http://stackoverflow.com/q/49822676
tags question: http://stackoverflow.com/q/49889702
tags question: http://stackoverflow.com/q/49851889
tags question: http://stackoverflow.com/q/49879471

http://stackoverflow.com/q/49868820
upvote count: 0
has body: 1st File: Comma Separated File LastName, FirstName, Gender 2nd File: Pipe delimited File LastName|FirstName|Gender 3rd File: Space Delimited File LastName Gender First Name Using Python 2, I need to merge all these files and then output the result in a single delimited file. How to achieve this? Also, if I want to Sort by last name ascending and output to another file, Sort by Gender and output to another file.
tagged with: python
score: -1
tagged with: merge
has comment: http://stackoverflow.com/comment/86795330
has answer: http://stackoverflow.com/a/49904557
has title: python merge comma delimited, pipe delimited, space delimited
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86753136
type: UnansweredQuestion

http://stackoverflow.com/q/49778388
tagged with: opencv
accepted answer: http://stackoverflow.com/a/49780289
linked to: http://stackoverflow.com/q/43822389
has answer: http://stackoverflow.com/a/49780289
type: AnsweredQuestion
has body: I have been running python script with nodejs using python-shell package.. and i am getting this error: Error: init done at PythonShell.parseError (F:\github\pythonShellDemo\node_modules\python-shell\index.js:191:17) at terminateIfNeeded (F:\github\pythonShellDemo\node_modules\python-shell\index.js:98:28) at ChildProcess.&lt;anonymous&gt; (F:\github\pythonShellDemo\node_modules\python-shell\index.js:89:9) at emitTwo (events.js:126:13) at ChildProcess.emit (events.js:214:7) at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12) after some debugging and research i got to know that this error is with opencv but i cant find any solution.. here is the code: import cv2 import zbar from PIL import Image import sys video = cv2.VideoCapture(0) count=0 qrcode=[] while True: ret, frame = video.read() cv2.imshow('Camera', frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break grayscale = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) image = Image.fromarray(grayscale) width, height = image.size zbarimage = zbar.Image(width, height,'Y800', image.tobytes()) scanner = zbar.ImageScanner() scanner.scan(zbarimage) for x in zbarimage: if count == 0: qrcode=x.data count=count+1 if qrcode: break video.release() cv2.destroyAllWindows() print(qrcode) sys.stdout.flush() I am using python 2.7 UPDATE: nodejs code for calling python script: PythonShell.run('python/scan.py', options, function (err, results) { if (err) { console.log(err) reject(err) } // results is an array consisting of messages collected during execution console.log(results) resolve(results) }) UPDATE: i tried running opencv only without zbar.. still got the error import cv2 cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/86572601
has comment: http://stackoverflow.com/comment/86572425
has comment: http://stackoverflow.com/comment/86572532
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86572830
answer count: 1
has comment: http://stackoverflow.com/comment/86573110
tagged with: node.js
has title: Opencv error init done

http://stackoverflow.com/q/49907382
favorite count: 0
has answer: http://stackoverflow.com/a/49907762
linked to: http://stackoverflow.com/q/24731810
has comment: http://stackoverflow.com/comment/86831237
tagged with: opencv
has answer: http://stackoverflow.com/a/64499989
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65656287
possible better answer: http://stackoverflow.com/a/64499989
tagged with: opencv3.0
answer count: 3
downvote count: 0
has title: How to remove whitespace from an image in OpenCV?
has comment: http://stackoverflow.com/comment/86830791
score: 24
upvote count: 24
tagged with: image-processing
has comment: http://stackoverflow.com/comment/86830931
has comment: http://stackoverflow.com/comment/86830588
accepted answer: http://stackoverflow.com/a/49907762
type: Question
has comment: http://stackoverflow.com/comment/86831277
has comment: http://stackoverflow.com/comment/86830731
tagged with: python
has body: I have the following image which has text and a lot of white space underneath the text. I would like to crop the white space such that it looks like the second image. Cropped Image Here is what I've done &gt;&gt;&gt; img = cv2.imread("pg13_gau.jpg.png") &gt;&gt;&gt; gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) &gt;&gt;&gt; edged = cv2.Canny(gray, 30,300) &gt;&gt;&gt; (img,cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) &gt;&gt;&gt; cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:10]

http://stackoverflow.com/comment/86777647
score: 0
comment on: http://stackoverflow.com/q/49879465
type: Comment
type: QuestionComment
has text: http://tpcg.io/GZNfns The first example gives the correct final response which is 242. The complete image of the first example is here : https://imgur.com/a/x5JHM But for the 2nd, I obtain two 0 which can't happen normally. So I thought that the problem came from the point S but even if I test with all the possible points there is always some 0 at some point.

http://stackoverflow.com/a/49890809
answers question: http://stackoverflow.com/q/49890481
has body: Try out this code. Previous code was for one node not the whole tree. else was also checking the right node and not the left node. import collections class BinarySearchTree: Node = collections.namedtuple('Node', ['left', 'right', 'value']) @staticmethod def contains(root, value): if root.value == value: return True elif root.value &lt; value: if root.right == None: return False else: return BinarySearchTree.contains(root.right,value) #root.right.value == value #I am using == to return True or #False else: if root.left == None: return False else: return BinarySearchTree.contains(root.left,value) #root.right.value == value n4 = BinarySearchTree.Node(value=4, left=None, right=None) n0 = BinarySearchTree.Node(value=0, left=None, right=None) n1 = BinarySearchTree.Node(value=1, left=n0, right=None) n3 = BinarySearchTree.Node(value=3, left=None, right=n4) n2 = BinarySearchTree.Node(value=2, left=n1, right=n3) print(BinarySearchTree.contains(n2, 14))
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/49907816
has comment: http://stackoverflow.com/comment/86832546
type: Question
has comment: http://stackoverflow.com/comment/86864120
answer count: 0
type: UnansweredQuestion
has body: I am a college student, obviously i am newbie in Machine learning so please bear with me. I am implementing a Java application that would recognize and classify Road/Traffic signs and my major problem is to create and train SVM with SURF descriptors. I read a lot and came across many different things when it comes to SVM i became even more confused but i will try to clarify what i understood. FIRST: i know that i must have a dataset that includes Pos images(images that have my objects) and Neg images(images that don't have my objects) to train SVM. I tried to look how it is done in python due to the lack of documentation in Java and came across this code import numpy as np dataset = np.loadtxt('./datasetExample.csv', delimiter=",") And it was simple as that, what is CSV doing here? where is the images of the dataset? i know that the data has to be represented in numbers like inside the CSV file, but where they came from and what it has to do with SVM. SECOND: I found that in almost all resources SVM can be trained by two ways HOG Descriptors or BagOfWords and didn't find the SURF Descriptor method(ACTUALLY i am not sure if it is possible.. but my Dr. said it can be done). THIRD: Since i am classifying traffic signs i need to have more than one class (EX. One for Warning signs, one for Regulatory signs, etc..), and each class of course has sub-classes like in the Speed limit signs it includes different types of signs. I came across smth called Multi-Class SVM and i really don't know what is that!! Currently i managed to extract SURF Descriptors from a given image using this code. Mat objectImage = Highgui.imread(signObject, Highgui.CV_LOAD_IMAGE_COLOR); featureDetector.detect(objectImage, objectKeyPoints); descriptorExtractor.compute(objectImage, objectKeyPoints, objectDescriptors); datasetObjImage.add(objectImage); datasetKeyPoints.add(objectKeyPoints); datasetDescriptors.add(objectDescriptors); What i was planning to do is to loop over all images of the dataset and…
tagged with: machine-learning
tagged with: python
tagged with: computer-vision
linked to: http://stackoverflow.com/q/16162150
has title: SVM Classifier based on SURF detectors
tagged with: opencv
has comment: http://stackoverflow.com/comment/86847280
score: 0
tagged with: java
has comment: http://stackoverflow.com/comment/86831961
has comment: http://stackoverflow.com/comment/86831775
has comment: http://stackoverflow.com/comment/86832880

http://stackoverflow.com/a/49867240
has comment: http://stackoverflow.com/comment/86783558
has comment: http://stackoverflow.com/comment/86785179
answers question: http://stackoverflow.com/q/49864359
score: 0
has comment: http://stackoverflow.com/comment/86783594
type: Answer
has comment: http://stackoverflow.com/comment/86783198
has comment: http://stackoverflow.com/comment/86783160
has body: Assuming you have a series date which contains your datetime values, you can convert to a string in your desired format before exporting to CSV: import pandas as pd df = pd.DataFrame({'date': pd.date_range('now', periods=4, freq='15D')}) df['date'] = df['date'].dt.strftime('%m/%d/%Y') print(df) # date # 0 04/16/2018 # 1 05/01/2018 # 2 05/16/2018 # 3 05/31/2018

http://stackoverflow.com/q/49815235
accepted answer: http://stackoverflow.com/a/49815956
tagged with: list
has comment: http://stackoverflow.com/comment/86645157
has comment: http://stackoverflow.com/comment/86644894
has comment: http://stackoverflow.com/comment/86644783
has title: converting list to dictionary in a python
upvote count: 1
has comment: http://stackoverflow.com/comment/86645195
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86644952
has comment: http://stackoverflow.com/comment/86644876
favorite count: 0
has comment: http://stackoverflow.com/comment/86644631
has comment: http://stackoverflow.com/comment/86645299
type: Question
has comment: http://stackoverflow.com/comment/86645475
has comment: http://stackoverflow.com/comment/86645184
has comment: http://stackoverflow.com/comment/86644825
has comment: http://stackoverflow.com/comment/86645776
tagged with: python
has comment: http://stackoverflow.com/comment/86644676
tagged with: load
has comment: http://stackoverflow.com/comment/86644815
tagged with: dictionary
has body: I have a data in a list like below: [ {'id': 1, 'first_name': 'Jeanette', 'last_name': 'Penddreth', 'email': 'jpenddreth0@census.gov', 'gender': 'Female', 'ip_address': '26.58.193.2'}, {'id': 2, 'first_name': 'Giavani', 'last_name': 'Frediani', 'email': 'gfrediani1@senate.gov', 'gender': 'Male', 'ip_address': '229.179.4.212'}, {'id': 3, 'first_name': 'Noell', 'last_name': 'Bea', 'email': 'nbea2@imageshack.us', 'gender': 'Female', 'ip_address': '180.66.162.255'}, {'id': 4, 'first_name': 'Willard', 'last_name': 'Valek', 'email': 'wvalek3@vk.com', 'gender': 'Male', 'ip_address': '67.76.188.26'} ] I am loading the data into the dynamoDb. It is failing with the error type: &lt;class 'list'&gt;, valid types: &lt;class 'dict'&gt;: ParamValidationError. How do I convert the above list into a dictionary? EDIT Code used: import boto3 import json s3_client=boto3.client('s3') dynamodb=boto3.resource('dynamodb') def lambda_handler(event, context): bucket=event['Records'][0]['s3']['bucket']['name'] json_filename=event['Records'][0]['s3']['object']['key'] json_object=s3_client.get_object(Bucket=bucket,Key=json_filename) jsonFileReader=json_object['Body'].read() jsonDictionary=json.loads(jsonFileReader) table=dynamodb.Table('EMPLOYEE_DETAILS') table.put_item(Item=jsonDictionary) return 'Done'
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49815956
score: 0

http://stackoverflow.com/comment/86677564
type: AnswerComment
has text: this solution messes up with the order of the dataframe and lists.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49831092

http://stackoverflow.com/comment/86692558
type: QuestionComment
score: 0
has text: Ok, it's slow because Pafy objects retrieve their information lazily. You didn't indicate who is raising the timeout error, but judging from the traceback it is some sort of voice client for `discord`. Maybe you should ensure that the information you need is already available once this is activated? (The 30-seconds timeout for a "voice client" appears reasonable.) As written the question requires a design/debugging session, which is outside the scope of StackOverflow. Please edit it to clearly state the problem and include a **minimal** and **reproducible** example that demonstrates it.
type: Comment
comment on: http://stackoverflow.com/q/49829320

http://stackoverflow.com/a/49827148
has body: I think printing the dataframe as a string should do the job for you. Something like this might work - print(df.to_string()) Hope this helps!
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49826909
score: 8
upvote count: 8

http://stackoverflow.com/comment/87050097
has text: It shows window authentication same as on click on this url -> https://www.engprod-charter.net/ <-- but there is one difference on click of url says abc.com when windows authentication popup appears, url changes say xyz.com. Now I tried to pass credential with both of these url separately. When the password contains special character, it does not work, but if password does not contain any special character it works with second url xyz.com which appears while windows authentication popup is displayed.
type: QuestionComment
comment on: http://stackoverflow.com/q/49899423
type: Comment
score: 0

http://stackoverflow.com/q/49792061
has body: I am trying to scrape data from this website: http://nepalstock.com/indices . I am not being able to scrape table data after changing value of 'Select Indices or Sub Indices' https://i.sstatic.net/J0WMn.png Since the url does not change, I do not know how to proceed on this. So far, this is my code: import requests import pandas from bs4 import BeautifulSoup html=requests.get("http://nepalstock.com/indices") soup=BeautifulSoup(html.content,"html.parser") lst=[] for row in soup.find_all("tr"): l=[] for td in row.find_all("td"): l.append(td.get_text()) lst.append(l) df=pandas.DataFrame(lst[1:]) df.head()
score: 0
has comment: http://stackoverflow.com/comment/86599143
answer count: 0
tagged with: web-scraping
has title: Scraping table data after applying filter
type: Question
tagged with: beautifulsoup
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86598984
tagged with: python
linked to: http://stackoverflow.com/q/28892543

http://stackoverflow.com/q/49881024
has body: I am running the latest Python version 3.6.4. I install pip via these instructions from https://pip.pypa.io/en/stable/installing/ To install pip, securely download get-pip.py. [1]: curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py Inspect get-pip.py for any malevolence. Then run the following: python get-pip.py pip install -U pip Finally when I get to install SciKit Learn here is what I ran into: pip install -U scikit-learn Collecting scikit-learn Could not fetch URL https://pypi.python.org/simple/scikit-learn/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping Could not find a version that satisfies the requirement scikit-learn (from versions: ) No matching distribution found for scikit-learn I couldn't find anything on stackover specifically addresing my problem and tried some suggested solution without success. (i.e. pip uninstall scikit-learn, sudo pip install scikit-learn) I am really stumped here on why I cannot install scikit learn package. I want to start using it. Can anyone help me out?
type: Question
duplicate of: http://stackoverflow.com/q/49748063
upvote count: 1
type: UnansweredQuestion
answer count: 1
tagged with: pip
tagged with: scikit-learn
tagged with: python
has title: Cannot Install Sci-Kit Learn Package on Mac OSX Error
favorite count: 0
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/49748063
has answer: http://stackoverflow.com/a/49881685

http://stackoverflow.com/comment/86597415
has text: Then only use `mm_dates_base[col] = a.combine_first(b).combine_first(c)`
score: 0
comment on: http://stackoverflow.com/a/49780046
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49840721
answer count: 1
tagged with: web
has body: Sorry if this is not a valid question, i personally feel it kind of boarders on the edge. Assuming the website involved has given full permission How could I download the ENTIRE contents (html) of that website using a python data scraper. By entire contents I refer to not only the current page you are on, but any other directory that branches off of that main website. Eg. Using the link: https://www.dogs.com could I pull info from: https://www.dogs.com/about-us and any other directory attached to the "https://www.dogs.com/" (I have no idea is dogs.com is a real website or not, just an example) I have already made a scraper that will pull info from a certain link (nothing further than that), but I want to further improve it so I dont have to have heaps of links. I understand I can use an API but if this is possible I would rather this. Cheers!
has title: How to scrape a website and all its directories from the one link?
type: Question
accepted answer: http://stackoverflow.com/a/49840785
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49840785

http://stackoverflow.com/a/49859201
downvote count: 0
has comment: http://stackoverflow.com/comment/86761913
answers question: http://stackoverflow.com/q/49858013
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49858013
has body: When scp or ssh attempt to read a password they do not read it from stdin. Instead they open /dev/tty and read the password direct from the connected terminal. sshpass works by creating its own dummy terminal and spawning ssh or scp in a child process controlled by that terminal. That's basically the only way to intercept the password prompt. The recommended solution is to use public key authentication, but you say you cannot do that. If as you say you cannot install sshpass and also cannot use a secure form of authentication then about the only thing you can do is re-implement sshpass in your own code. sshpass itself is licensed under the GPL, so if you copy the existing code be sure not to infringe on its copyleft. Here's the comment from the sshpass source which describes how it manages to spoof the input: /* Comment no. 3.14159 This comment documents the history of code. We need to open the slavept inside the child process, after "setsid", so that it becomes the controlling TTY for the process. We do not, otherwise, need the file descriptor open. The original approach was to close the fd immediately after, as it is no longer needed. It turns out that (at least) the Linux kernel considers a master ptty fd that has no open slave fds to be unused, and causes "select" to return with "error on fd". The subsequent read would fail, causing us to go into an infinite loop. This is a bug in the kernel, as the fact that a master ptty fd has no slaves is not a permenant problem. As long as processes exist that have the slave end as their controlling TTYs, new slave fds can be created by opening /dev/tty, which is exactly what ssh is, in fact, doing. Our attempt at solving this problem, then, was to have the child process not close its end of the slave ptty fd. We do, essentially, leak this fd, but this was a small price to pay. This worked great up until openssh version 5.6. Openssh version 5.6 looks at all of its open file descriptors, and closes any that it does not know …
type: Answer
has comment: http://stackoverflow.com/comment/86760966
score: 2
has comment: http://stackoverflow.com/comment/86741643
type: AcceptedAnswer

http://stackoverflow.com/comment/118516445
comment on: http://stackoverflow.com/a/61603758
type: AnswerComment
score: 3
type: Comment
has text: I tried this but it apparently only works on one monitor: `pyautogui` doesn't support multiple monitors yet. Any other methods out there??

http://stackoverflow.com/comment/86737907
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49858798
has text: Only issue, is I have tried that and used the imput example = 3/25/2014 or 3/25 and when I put that in as the input I get this response from the shell: TypeError: strptime() argument 1 must be string, not int

http://stackoverflow.com/comment/86698514
comment on: http://stackoverflow.com/a/49841882
type: AnswerComment
score: 1
type: Comment
has text: I was just thinking if this is some sort of "hard-coding" the task? Doesn't seem to be very flexible and/or adjustable by the user, or am I wrong?

http://stackoverflow.com/a/49904998
has body: You should use .groupby df.groupby('id').sum()
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49904983
upvote count: 1

multiprocessing
tags question: http://stackoverflow.com/q/49847794
tags question: http://stackoverflow.com/q/49759831
tags question: http://stackoverflow.com/q/49888485
tags question: http://stackoverflow.com/q/49840417
tags question: http://stackoverflow.com/q/49791077
tags question: http://stackoverflow.com/q/49817726
tags question: http://stackoverflow.com/q/49898234
tags question: http://stackoverflow.com/q/49807345
tags question: http://stackoverflow.com/q/49782749
tags question: http://stackoverflow.com/q/49843334
tags question: http://stackoverflow.com/q/49831205
tags question: http://stackoverflow.com/q/49804815
tags question: http://stackoverflow.com/q/49822090
tags question: http://stackoverflow.com/q/49857233
tags question: http://stackoverflow.com/q/49806605
tags question: http://stackoverflow.com/q/49791271
tags question: http://stackoverflow.com/q/49899351
type: Tag
tags question: http://stackoverflow.com/q/49762048
tags question: http://stackoverflow.com/q/49848078
tags question: http://stackoverflow.com/q/49837539
tags question: http://stackoverflow.com/q/49842290
tags question: http://stackoverflow.com/q/49901824
tag name: multiprocessing
tags question: http://stackoverflow.com/q/49858968

lmfit
tags question: http://stackoverflow.com/q/49908058
tags question: http://stackoverflow.com/q/49840657
tag name: lmfit
type: Tag

http://stackoverflow.com/comment/86592786
comment on: http://stackoverflow.com/a/49773700
has text: Thank you for you answer. Excluding the solution in the other answer, is there any other solution? Since the value r will vary by changing the input and I can't avoid the base to be negative. Dirty fix may not be allowed as the function will be applied into more sophisticated algorithm that probably induce unexpected error.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49870002
possible better answer: http://stackoverflow.com/a/58623431
has answer: http://stackoverflow.com/a/58623431
tagged with: python
accepted answer: http://stackoverflow.com/a/49870315
answer count: 2
has answer: http://stackoverflow.com/a/49870315
upvote count: 1
tagged with: amazon-web-services
has body: I want to deploy my Flask application to AWS Lambda. I tried deploying it using aws-cli, but it wasn't successful. How can I deploy Flask to Lambda? from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/status', methods = ['GET','POST']) def service_run(): return "service is running"
tagged with: flask
downvote count: 1
tagged with: aws-lambda
favorite count: 0
type: Question
type: AnsweredQuestion
score: 0
has title: Deploy a Flask WSGI application to AWS Lambda

http://stackoverflow.com/comment/86720339
has text: *Better put the second argument of find into a dict* - why?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49849644
type: Comment

http://stackoverflow.com/comment/86738515
type: Comment
score: 0
type: AnswerComment
has text: Thank you so much @Colin Ricardo. I implemented your solution and it worked great, I only had to change one line and add the 2nd parameter in the 'find_data' function. I appreciate your help on this.
comment on: http://stackoverflow.com/a/49861236

http://stackoverflow.com/q/49901216
has answer: http://stackoverflow.com/a/49901476
tagged with: python
has comment: http://stackoverflow.com/comment/86818052
has comment: http://stackoverflow.com/comment/86818148
has comment: http://stackoverflow.com/comment/86818945
has comment: http://stackoverflow.com/comment/86817860
tagged with: for-loop
has title: performing multiple for loops in python automatically and simultaneously
type: AnsweredQuestion
downvote count: 0
has body: I have a challenging questions: Imagine that I have a list of strings with the same length like the following 'seq' list: seq=['FFFSS', 'FFEEE', 'WWQQA', 'PPRSA', 'MMMMM', 'PPEEE','HMSII','KKKDD','WTYUI','OPOPO','YYYYY', 'QQERT','YYRER', 'NNBBB', 'CCXZZ', 'UIOOP', 'QQWEE', ….,'FFGEE'] But Of course my real 'seq' list has so many more strings (at least 100 strings all having the same length). If I want to open string number 0 upto string number 3 simultaneously, I need to write a multiple 'for loop' like the following: n= 0 for a0, a1, a2 in zip(seq[n+0], seq[n+1], seq[n+2]): print(a0, a1, a2) Now if I want to extend the above 'for loop' and open string number 0 upto string number 5 simultenously, I need to change the above code like the following: n= 0 for a0, a1, a2, a3, a4 in zip(seq[n+0], seq[n+1], seq[n+2], seq[n+3], seq[n+4]): print(a0, a1, a2, a4) The output for the above code is as following which is my favorite output: F F W P F F W P F E Q R S E Q S S E A A Finally imagine that I want to extend above code more and more and for example open string number 0 upto string number 100 simultaneously, so of course I can't extend the code manually and I need to find a way to extend the above multiple 'for loop' automatically. Imagine that I need the final multiple loop as the following: n= 0 for a0, a1, a2, a3, a4, …, a100 in zip(seq[n+0], seq[n+1], seq[n+2], seq[n+3], seq[n+4], …, seq[n+100]): print(a0, a1, a2, a4, …, a100) My question is that if I want to have these 100 'a' variables, is there any way to make multiple 'for loop' automatically for a huge number of variables simultaneously?
score: 1
upvote count: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49901470
accepted answer: http://stackoverflow.com/a/49901476
answer count: 2
has answer: http://stackoverflow.com/a/49901470

http://stackoverflow.com/a/49861530
downvote count: 0
has body: You can use np.unique with its axis param to get the starting unique row indices and then filter out the only one row index whose corresponding row is all-zeros, like so - def unq_row_indices_wozeros(a): # Get unique rows and their first occuring indices unq, idx = np.unique(a, axis=0, return_index=1) # Filter out the index, the corresponding row of which is ALL 0s return idx[(unq!=0).any(1)] Sample run - In [53]: # Setup input array with few all zero rows and duplicates ...: np.random.seed(0) ...: a = np.random.randint(0,9,(10,3)) ...: a[[2,5,7]] = 0 ...: a[4] = a[1] ...: a[8] = a[3] In [54]: a Out[54]: array([[5, 0, 3], [3, 7, 3], [0, 0, 0], [7, 6, 8], [3, 7, 3], [0, 0, 0], [1, 5, 8], [0, 0, 0], [7, 6, 8], [2, 3, 8]]) In [55]: unq_row_indices_wozeros(a) Out[55]: array([6, 9, 1, 0, 3]) # Sort those indices if needed In [56]: np.sort(unq_row_indices_wozeros(a)) Out[56]: array([0, 1, 3, 6, 9])
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49857395
upvote count: 2

http://stackoverflow.com/a/49801041
type: Answer
has body: Use Kivy Anchor Layout. If you are going to add more buttons, my suggestion is to use Kivy Drop-Down List. Example main.py from kivy.garden.mapview import MapView from kivy.app import App from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.button import Button from kivy.properties import NumericProperty class RootWidget(AnchorLayout): lat = NumericProperty(50.6394) lon = NumericProperty(3.057) def __init__(self, **kwargs): super(RootWidget, self).__init__(**kwargs) self.anchor_x = 'right' self.anchor_y = 'top' mapview = MapView(zoom=11, lat=self.lat, lon=self.lon) self.add_widget(mapview) touchBarbtn1 = Button(text='Unlock', size_hint=(0.1, 0.1)) touchBarbtn1.bind(on_press=lambda x: self.centerOnUser()) self.add_widget(touchBarbtn1) def centerOnUser(self): pass class MapViewApp(App): def build(self): return RootWidget() MapViewApp().run() Output
score: 0
has comment: http://stackoverflow.com/comment/86629583
answers question: http://stackoverflow.com/q/49800345

time-series
tags question: http://stackoverflow.com/q/49799273
tags question: http://stackoverflow.com/q/49873078
tags question: http://stackoverflow.com/q/49880067
type: Tag
tag name: time-series
tags question: http://stackoverflow.com/q/49773491
tags question: http://stackoverflow.com/q/49873443
tags question: http://stackoverflow.com/q/49861009
tags question: http://stackoverflow.com/q/49913007
tags question: http://stackoverflow.com/q/49806213
tags question: http://stackoverflow.com/q/49837943

http://stackoverflow.com/comment/137932807
type: AnswerComment
comment on: http://stackoverflow.com/a/76894105
type: Comment
has text: Note the DFF() function must appear at the bottom of your notebook so that all above cells which will execute your i) to iv) will run first. These cells can include all that you want visualization logs etc. All this happens inside the called_notebook.ipynb which at the end will generate the dff (dataframe you need in your calling_notebook.ipynb)
score: 0

http://stackoverflow.com/a/55460339
answers question: http://stackoverflow.com/q/49794023
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: I had same problem .finally after searching a lot and testing many solutions , i could to import keras classification trained model in opencv. Firstly you must to replace keras with tensorflow.python.keras. Just remove keras from your code lines and replace it with tensorflow.python.keras Secondly you must to replace flatten layares with this codes : just remove flatten layers and copy and past this: a,b,c,d = model.output_shape a = b*c*d model.add(K.layers.Permute([1, 2, 3])) # Indicate NHWC data layout model.add(K.layers.Reshape((a,))) Now you can retrain your model. After training finished , save your model in .h5 format. Now you must convert keras .h5 model to tensorflow .pb model. In order to converting models i used this workaround : https://stackoverflow.com/a/53386325/5208522 Now you can easily import .pb model in opencv and it works perfectly.

http://stackoverflow.com/comment/87018619
type: Comment
comment on: http://stackoverflow.com/a/49830027
type: AnswerComment
has text: thanks a lot,Please could you let me know how to use href in python?
score: 0

http://stackoverflow.com/q/49811006
has answer: http://stackoverflow.com/a/49814118
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: neural-network
upvote count: 1
tagged with: machine-learning
score: 1
has comment: http://stackoverflow.com/comment/86642589
tagged with: tensorflow
favorite count: 0
has title: Feed stacked RNN output into fully connected layer
has body: I'm trying to solve a regression problem with a stacked RNN in tensorflow. The RNN output should be fed into a fully connected layer for the final prediction. Currently I'm struggeling on how to feed the RNN output into the final fully_connected layer. My input is of shape [batch_size, max_sequence_length, num_features] The RNN Layers are created like this: cells = [] for i in range(num_rnn_layers): cell = tf.contrib.rnn.LSTMCell(num_rnn_units) cells.append(cell) multi_rnn_cell = tf.contrib.rnn.MultiRNNCell(cells) outputs, states = tf.nn.dynamic_rnn(cell=multi_rnn_cell, inputs=Bx_rnn,dtype=tf.float32) Outputs is of shape [batch_size, max_sequence_length, num_rnn_units] I tried using only the output of the last time step like this: final_outputs = tf.contrib.layers.fully_connected( outputs[:,-1,:], n_targets, activation_fn=None) I also found examples and books recommending to reshape the output and target like this: rnn_outputs = tf.reshape(outputs, [-1, num_rnn_units]) y_reshaped = tf.reshape(y, [-1]) Since I'm currently using a batch size of 500 and a sequence length of 10000 this leads into huge matrices, really long training times and huge memory consumption. I've also found many articles recommending unstacking the inputs and stacking outputs again, which I couldn't get to work due to shape mismatches. What would be the correct way to feed the RNN output into a fully_connected layer? Or should I use the RNN states over outputs? Edit: For Clarification: I do need these long sequences, because I'm trying to model a physical system. The Input is a single feature, consisting of a white noise. I have multiple outputs (in this specific system 45). Impulses effect System state for round about 10.000 time steps. i.e. currently I'm trying to model a cars gear bridging which was animated by a shaker. Outputs were measured by 15 acceleration sensors into 3 directions (X,Y &amp; Z). Batch size of 500 was arbitrarily picked. Regardless of probably vanishing gradients or pote…
tagged with: python
tagged with: recurrent-neural-network

http://stackoverflow.com/comment/86644295
comment on: http://stackoverflow.com/q/49814367
has text: I believe there is no way to do so as the value is evaluated at the point of reference i.e. `out_obj.foo` will not leave any information about host_object unless (1) send to host_object in or (2) use the inspect trick which is hacky and not elegant.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49846559
tagged with: flask
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/20524536
answer count: 1
tagged with: flask-restful
accepted answer: http://stackoverflow.com/a/49846998
type: Question
has answer: http://stackoverflow.com/a/49846998
tagged with: api
has title: Sending Millions of data points to flask API
tagged with: upload
has body: This question might be a little too subjective, but I am looking for an optimal way to send millions of datapoints to a flask API. My current approach is essentially as follows: Send a list of data points that are JSON objects, as well as sending some information that pertains to all of the data points such as the person it was collected on and the date it was collected This updates two tables, a Use table that records the person, date, etc. and then a Data table that associates data points to a given use. This all occurs as one POST request to the Use endpoint I'm afraid that with this approach it might timeout when sending millions of datapoints. I'm looking for a way to combat this, some ways I have been considering are Sending an initial POST request to create the Use, then sending the datapoints in patches as a PATCH to the same endpoint or a POST to a new data endpoint sending a csv in a POST request and then parsing through the csv on the server Haven't been able to find any similar questions online, so looking to see if there is an industry standard or best practice when doing something like this
tagged with: python

http://stackoverflow.com/q/49844560
tagged with: pip
tagged with: ssl
upvote count: 1
tagged with: python
has body: I keep getting this SSL error when using pip on my mac. I have done a fresh install of the OS and it hasn't made any different. Turning the firewall off also doesn't make any difference. Anyone got any ideas? Here's the error: &gt; Seans-Mac-mini:~ seanhatch$ pip3 install discord.py Collecting discord.py Could not fetch URL https://pypi.python.org/simple/discord-py/: There was a problem confirming the ssl certificate: EOF occurred in violation of protocol (_ssl.c:719) - skipping Could not find a version that satisfies the requirement discord.py (from versions: ) No matching distribution found for discord.py Discord.py was used as an example but it doesn't work for any packages.
has title: Pip SSL error on Mac
score: 1
linked to: http://stackoverflow.com/q/49748063
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86704133
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86705662

http://stackoverflow.com/q/49913125
type: Question
upvote count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86842300
has answer: http://stackoverflow.com/a/49913550
linked to: http://stackoverflow.com/q/8688569
tagged with: django-templates
has body: I am fairly new to django and am trying out template-inheritance but not able to get it work. I cannot get all the blocks in a page to be displayed simultaneously. Not sure if I am missing something in urls, views or settings. I am using Python 3.6 in venv / Django 2.0.4 on PyCharm Details of my example below - myhome being project name and smarthome being app name Folder Structure base.html navtopbar.html navsidebar.html smarthome urls.py smarthome views.py -- Initially I had this as base.html but based on advice in thread below, changed to navtopbar. But then not sure how to get application to display navsidebar simultaneously settings I followed the advice in this thread but not able to get it to work yet. Appreciate any help here.
answer count: 1
has title: python-django template-inheritance not working when referencing multiple blocks in base
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/86538999
type: QuestionComment
has text: I'm doing Binary Classification. And I put an illustration of the dataset below in answer.
comment on: http://stackoverflow.com/q/49760039
score: 0
type: Comment

http://stackoverflow.com/q/49887909
has comment: http://stackoverflow.com/comment/86792087
has comment: http://stackoverflow.com/comment/86792042
has comment: http://stackoverflow.com/comment/86791987
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49887990
downvote count: 3
has title: Is there documentation for file object?
tagged with: python
score: 11
has comment: http://stackoverflow.com/comment/86792236
upvote count: 14
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49887990
has comment: http://stackoverflow.com/comment/86792064
has comment: http://stackoverflow.com/comment/86792297
has body: This is probably really dumb question, but I honestly can't find documentation for file object's API in Python 3. Python docs for things using or returning file objects like open or sys.stdin have links to glossary with high-level introduction. It doesn't list functions exposed by such objects and I don't know, what can I do with them. I've tried googling for file object docs, but search engines don't seem to understand, what am I looking for. I'm new to Python, but not to programming in general. Until now my scheme of using objects was to find complete API reference, see what it can do and then pick methods to use in my code. Is this wrong mindset in Python world? What are the alternatives?
answer count: 1

http://stackoverflow.com/q/49812802
answer count: 2
tagged with: pycharm
tagged with: pandas
has comment: http://stackoverflow.com/comment/86640419
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86641077
has answer: http://stackoverflow.com/a/49812949
has title: I installed pandas but it is not working
favorite count: 0
type: Question
has body: I have PyCharm 18 and I installed pandas version 0.22.0. When i import it it is not working, this is my code: import pandas as pd datas = pd.DataFrame({ "fsfsd": ["fff", "fss"], "ddfs": ["fsdfsd", "fdfsfs"] }) print(datas) but when it executes it gives me the following errors: Traceback (most recent call last): File "C:/Users/hp/PycharmProjects/PC18/pandas.py", line 1, in &lt;module&gt; import pandas as pd File "C:\Users\hp\PycharmProjects\PC18\pandas.py", line 3, in &lt;module&gt; datas = pd.DataFrame({ AttributeError: module 'pandas' has no attribute 'DataFrame' Process finished with exit code 1 pls help; thanks
has comment: http://stackoverflow.com/comment/86639993
accepted answer: http://stackoverflow.com/a/49815129
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/49812949
has answer: http://stackoverflow.com/a/49815129
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/49907285
possible better answer: http://stackoverflow.com/a/49908096
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/86833674
has answer: http://stackoverflow.com/a/49908083
score: 2
type: AnsweredQuestion
has title: Python3 regex escape function
has comment: http://stackoverflow.com/comment/86831099
downvote count: 0
has comment: http://stackoverflow.com/comment/86830996
has comment: http://stackoverflow.com/comment/86830519
accepted answer: http://stackoverflow.com/a/49908083
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
answer count: 2
has body: So I am given a string of digits of variable length and I need to find all possible number combinations using the digits in that string where only the digits in between may be changed, for example: if I am given 123, I need to find the combinations of 1x2y3 where x, y are any digits. if I am given 5312, I need to find the combinations of 5a3b1c2 where a, b, c are any digits. I'm thinking this is possible using python's re.escape function, this is as far as I've come: #Given the digits '123' from STDIN #create a string "1\d2\d3" my_regex_string = '\d'.join(input().split()) #Set x as starting point, set y as limit (not the most efficient) x = 10**(len(my_regex_string)-1) * int(my_regex_string[0]) y = 10**(len(my_regex_string)-1) * (int(my_regex_string[0]) + 1) while x &lt; y: if bool(re.match(re.escape(p), str(x))) print(x) x+=1 I need feedback, does my approach make sense? Is this task doable with regex or do I need another approach?
has answer: http://stackoverflow.com/a/49908096
has comment: http://stackoverflow.com/comment/86832352

http://stackoverflow.com/a/65479925
score: 0
answers question: http://stackoverflow.com/q/49830454
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/131584692
has body: I found you have to ensure Django is imported in the file wsgi.py. Hope this answer is useful
upvote count: 1

http://stackoverflow.com/q/49864714
has body: I'm goint to build a temperature measurement application in Python (on a resource constrained IoT device). I'm going to measure the temperature of a sensor, compare it with the previous measurement and only send the data to the server if the new measurement is within some allowed deviation. So: 1) Measure the temperature of a sensor 2) Check if the measurement deviates from the previous measurement by more than some set deviation Example: Previous measurement was 24.0 C, allowed deviation 0,3 C 1) Temperature measured to be 23,5 C 2) The measurement deviates by more than what is allowed. Send to server My initial idea is to do a bitwise xor on the previous and the current measurement and thereafter subtract this from the allowed deviation. If the result is positive -> data is not sent If the result is negative -> send data I'm struggling to do this in Python and would appreciate some help. Alternatively any suggestions on how to do this differently would be highly appreciated!
has answer: http://stackoverflow.com/a/49864866
type: UnansweredQuestion
downvote count: 2
answer count: 1
upvote count: 1
tagged with: floating-point
tagged with: lorawan
has comment: http://stackoverflow.com/comment/86744899
favorite count: 0
tagged with: math
has title: Bitwise xor on float python
has comment: http://stackoverflow.com/comment/86745666
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86744926
tagged with: bitwise-xor
type: Question

http://stackoverflow.com/a/49845505
score: 1
has body: You can use applymap, it will apply some function for each element in dataframe, for this problem you can do this: func = lambda x: re.findall('^.*:\s*(.*)', x)[0] if re.findall('^.*:\s*(.*)', str(x)) else x df.applymap(func) Caution: Avoid to use applymap for huge dataframes due to efficiency issue.
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49823631

http://stackoverflow.com/a/49830789
type: Answer
upvote count: 16
type: AcceptedAnswer
downvote count: 0
score: 16
has body: If you look at sklearn.model_selection.train_test_split, you can see it takes an *arrays argument. To split the first three of your arguments, therefore, you could use CS_tr, CS_te, EN_tr, EN_te, SN_tr, SN_te = train_test_split(CS, EN, SN) (of course, you can pass more arrays than that). Note that current versions of sklearn return sparse arrays when given sparse arrays.
accepted answer of: http://stackoverflow.com/q/49829023
has comment: http://stackoverflow.com/comment/86691795
answers question: http://stackoverflow.com/q/49829023

http://stackoverflow.com/comment/86617673
type: QuestionComment
has text: [QCompleter example](https://doc.qt.io/archives/qt-4.8/qt-tools-completer-example.html) and [PyQt example](https://github.com/baoboa/pyqt5/tree/master/examples/tools/customcompleter).
score: 0
comment on: http://stackoverflow.com/q/49793232
type: Comment

http://stackoverflow.com/q/49771402
answer count: 1
tagged with: gtk3
has answer: http://stackoverflow.com/a/49772269
favorite count: 0
type: Question
downvote count: 0
accepted answer: http://stackoverflow.com/a/49772269
tagged with: python
has title: Getting mousewheel events in DrawArea with python GTK3
has body: I'm trying to get a mousewheel event inside a Gtk.DrawArea. Does someone know howto achieve this? The method DrawTest.on_scroll() is never called currently: #!/usr/bin/env python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class DrawTest(Gtk.DrawingArea): def __init__(self): super(DrawTest, self).__init__() self.connect("scroll-event", self.on_scroll) def on_scroll(self, btn, event): print("Scroll event") return True class MainWindow(Gtk.Window): def __init__(self): super(MainWindow, self).__init__() self.connect("destroy", lambda x: Gtk.main_quit()) evtest = DrawTest() self.add(evtest) self.show_all() def run(self): Gtk.main() def main(args): mainwdw = MainWindow() mainwdw.run() return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv))
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/comment/86563779
has text: thank you for your reply. I think your pointed out is correct, but I do not know how to look up attributes.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49774372
score: 0

http://stackoverflow.com/comment/86754832
type: QuestionComment
has text: I will add more details. @eyllanesc
comment on: http://stackoverflow.com/q/49869767
score: 0
type: Comment

http://stackoverflow.com/comment/86589771
score: 0
type: AnswerComment
has text: You are a life savior! Thank you so much! Just one question, though: If I were to put in the mc.objExists command in the script, where would it go?
type: Comment
comment on: http://stackoverflow.com/a/49786843

http://stackoverflow.com/comment/86826105
has text: I'm not trying to move it, I created it specifically in the U:\ network drive everyone has access to
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49904286

http://stackoverflow.com/comment/86789460
type: QuestionComment
has text: Thanks, that would ease things up. Is it something that one take for granted regardless of Postgres version or it's just some implementation detail that might be subject to change?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49833051

http://stackoverflow.com/a/49863388
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49863191
has comment: http://stackoverflow.com/comment/86742273
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86742680
has comment: http://stackoverflow.com/comment/86742945
has comment: http://stackoverflow.com/comment/86742476
answers question: http://stackoverflow.com/q/49863191
has body: import random as rdm class Multiplizieren: def __init__(self,name): self.name = name self.a = rdm.randint(5,20) self.b = rdm.randint(4,50) self.c = rdm.randint(2,200) def x(self): finished = False while not finished: c = self.a*self.b-self.c if c &lt; 0 or c &gt; 100: print('OUT OF RANGE') self.__init__(self.name) else: print(self.a, '*', self.b, '-', self.c, '=', self.a*self.b-self.c) finished = True return c d = Multiplizieren('h') d.x() Just call self.__init__(self.name) to reinitialize your class when you are out of range instead of return, this will give you new values for a, b and c Just a side note on __init__(): It's a special function that gets called automatically when you create an object, but you can still call it like a regular function.

http://stackoverflow.com/q/49801402
answer count: 1
downvote count: 0
has title: re finditer produces javascript with uncaught exception
tagged with: javascript
upvote count: 1
favorite count: 0
score: 1
tagged with: python
has body: I am trying to compile some simple Python code to Javascript using "transcrypt -e 6". When I use finditer from Python's re module, the resultant Javascript code has an uncaught exception during runtime. python: import re re_token = re.compile('\w+') def tokenize(s): positions = [] for m in re_token.finditer(s): positions.append(m.start(0)) return positions print(tokenize('select * from x')) stack trace: Uncaught Function {__class__: ƒ, __args__: Array(1), stack: "No stack trace available", __cause__: null} (anonymous) @ x.js:2838 (anonymous) @ x.js:53 tokenize @ x.js:3566 (anonymous) @ VM68:1 the top element on the stack: get finditer () {return __get__ (this, function (self, string, pos, endpos) { if (typeof endpos == 'undefined' || (endpos != null &amp;&amp; endpos .hasOwnProperty ("__kwargtrans__"))) {; var endpos = null; }; var __except0__ = NotImplementedError ('No Iterator Support in es5'); __except0__.__cause__ = null; throw __except0__; });},
type: Question
tagged with: transcrypt
has answer: http://stackoverflow.com/a/49810387
type: UnansweredQuestion

http://stackoverflow.com/q/49897492
has title: main has no run member
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49897858
has comment: http://stackoverflow.com/comment/86810684
has answer: http://stackoverflow.com/a/49897858
has body: I have the following structure in code. In main.py: def run(parameters): # do something In execution.py: import main if __name__ = "main": main.run(parameters) However, I get the following error - main has no 'run' member.
tagged with: python
score: -1
type: AnsweredQuestion
downvote count: 2
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/86743305
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49862183
has text: Usually when you run a neural network, you run your data into them a bunch at a time, this is called "batching". So for example, you might feed the neural network 32 or 64 or 128 examples at a time to train on. The advantage of doing this is speed. Programs which utilize vectorization will perform work on 32 or 64 or 128 examples simultaneously and speed up the process significantly. If however, you insist on all your inputs being variable length, then you can not take advantage of this and you will have to force the neural net to train one example at a time.
score: 1

http://stackoverflow.com/q/49818590
linked to: http://stackoverflow.com/q/49760092
has comment: http://stackoverflow.com/comment/86653188
tagged with: pandas
linked to: http://stackoverflow.com/q/48696344
score: 1
duplicate of: http://stackoverflow.com/q/48696344
has comment: http://stackoverflow.com/comment/86656433
type: Question
tagged with: numpy
has title: Does numpy.where(condition, f(x), f(y)) evaluate the f(y) is condition is true?
answer count: 0
has comment: http://stackoverflow.com/comment/86652128
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86651961
downvote count: 0
has body: When using numpy.where(condition, f(x), f(y)), I originally thought numpy where does not evaluate f(y) if the condition is True. However it seems to be not true df = pd.DataFrame({'x':[0, 1, 2, float('nan'), 4, 5]}) df['y'] = np.where(df['x'].isnull(), -1, np.maximum(1, df['x'])) df I got the following warning: "RuntimeWarning: invalid value encountered in maximum" and sometime it just gives me an error and stop executing the code. How to fix that issue?
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/86653137
has comment: http://stackoverflow.com/comment/86661337

http://stackoverflow.com/comment/139008291
type: Comment
has text: These are not class attributes, they're instance attributes. Class attributes are held on the class and are accessible by all instances. Instance attributes are specific to individual instances of a class.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49907111

http://stackoverflow.com/a/49785936
answers question: http://stackoverflow.com/q/49782852
type: Answer
has body: Queues and pipelines work very nicely with each other (architecturally speaking). One of the nicer bits is the fact that slower stages can get more workers than faster stages, allowing the pipeline to be optimized based on the workload.
has comment: http://stackoverflow.com/comment/86587282
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86626416

http://stackoverflow.com/comment/86734600
comment on: http://stackoverflow.com/a/49798984
has text: I am still not sure how i would do this regarding the Thingworx server if you have any more information it would be greatly appreciated
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/86600611
has text: how to use BeautifulSoup https://www.crummy.com/software/BeautifulSoup/bs4/doc/
score: 3
comment on: http://stackoverflow.com/q/49793128
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86749448
type: Comment
type: QuestionComment
score: 0
has text: struct.unpack() takes bytes as a second argument.
comment on: http://stackoverflow.com/q/49866887

http://stackoverflow.com/comment/86708107
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49844195
has text: Which version of python you use ?
type: QuestionComment

http://stackoverflow.com/q/49761512
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86539009
has answer: http://stackoverflow.com/a/49762259
upvote count: 0
type: UnansweredQuestion
has title: Python Flask Redirect
tagged with: python
has comment: http://stackoverflow.com/comment/86538544
score: -1
tagged with: flask
has body: def check(): if 3&gt;2: return redirect(url_for('control')) @app.route('/reason', methods=['GET','POST']) def reason(): check() return render_template('reason.html') @app.route('/control', methods=['GET','POST'] def control(): return render_template('control.html') I have two html files (control.html and reason.html). the code loads reason.html page first and receives user input using POST method then after doing certain checks, I want to reload control.html. the problem is I am not able to load control.html
has comment: http://stackoverflow.com/comment/86539155
has comment: http://stackoverflow.com/comment/86538761
has comment: http://stackoverflow.com/comment/86539603
answer count: 1
has comment: http://stackoverflow.com/comment/86539240
has comment: http://stackoverflow.com/comment/86539865
has comment: http://stackoverflow.com/comment/86539961

http://stackoverflow.com/comment/86656496
comment on: http://stackoverflow.com/q/49820329
score: 0
type: Comment
type: QuestionComment
has text: Yeah, but that’s just the exit code from the script that drives the gfortran call. Is the error output of gfortran, or at least of the script, not included anywhere above that in the huge traceback output that you truncated?

heredoc
tags question: http://stackoverflow.com/q/49885808
type: Tag
tag name: heredoc

http://stackoverflow.com/q/49822456
accepted answer: http://stackoverflow.com/a/49822619
tagged with: pandas
linked to: http://stackoverflow.com/q/49820285
has comment: http://stackoverflow.com/comment/86665756
linked to: http://stackoverflow.com/q/41386443
type: Question
has body: I am struggling to determine as to why my split function along with code is not working. I have a column like this - RegionName Alabama[edit] Auburn (Auburn University) Florence(University of North Alabama) Jacksonville . . . and so on.. The above entries show the cases that are there in the column. What i want to achieve is for entries having state names such as Alabama[edit], i want to have it displayed as NaN, for remaining other entries which are corresponding regions within that particular State, i want to clean all those entries if required. If no cleaning required, i want that entry to stay intact.i am using below code- for x in Town['RegionName']: if re.match(r"\s*\(",x): x.split('(').strip() elif re.match(r"\d+\[",x): x = np.NaN else: x The code runs without any error but all the entries stay intact. The desired output is - RegionName NaN Auburn Florence Jacksonville . . . Cleaning required is - remove the entire content post parenthesis, there could be a space between required content and parenthesis so have to take that as well into account. Please advise.
has answer: http://stackoverflow.com/a/49822497
possible better answer: http://stackoverflow.com/a/49822490
has answer: http://stackoverflow.com/a/49822490
has answer: http://stackoverflow.com/a/49822619
has comment: http://stackoverflow.com/comment/86660482
duplicate of: http://stackoverflow.com/q/41386443
tagged with: python
has comment: http://stackoverflow.com/comment/86662842
has title: Split function not working
type: AnsweredQuestion
score: 0
answer count: 3

http://stackoverflow.com/q/49824101
has title: For a Matplotlib plot, how do I hide the tick marks but keep the tick labels?
tagged with: matplotlib
answer count: 1
downvote count: 0
has body: When creating a 2-D plot in Matplotlib, what method hides the tick marks/lines but not the labels? I want the opposite of this question. I do not see an appropriate method in the Matplotlib API. As a hack, I have considered "hiding" the tick marks by setting the color to match the background (e.g., white). Is there a better way?
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/48695269
type: UnansweredQuestion
tagged with: python
tagged with: plot
has answer: http://stackoverflow.com/a/49826510
score: 2
upvote count: 2

machine-learning
tags question: http://stackoverflow.com/q/49802001
tags question: http://stackoverflow.com/q/49808973
tags question: http://stackoverflow.com/q/49820105
type: Tag
tags question: http://stackoverflow.com/q/49909841
tags question: http://stackoverflow.com/q/49894411
tags question: http://stackoverflow.com/q/49796944
tags question: http://stackoverflow.com/q/49832900
tags question: http://stackoverflow.com/q/49847021
tags question: http://stackoverflow.com/q/49816256
tags question: http://stackoverflow.com/q/49862270
tags question: http://stackoverflow.com/q/49777898
tags question: http://stackoverflow.com/q/49854070
tags question: http://stackoverflow.com/q/49772772
tags question: http://stackoverflow.com/q/49781923
tags question: http://stackoverflow.com/q/49777853
tags question: http://stackoverflow.com/q/49798531
tags question: http://stackoverflow.com/q/49866012
tags question: http://stackoverflow.com/q/49889661
tags question: http://stackoverflow.com/q/49862136
tags question: http://stackoverflow.com/q/49777762
tags question: http://stackoverflow.com/q/49809032
tags question: http://stackoverflow.com/q/49896395
tags question: http://stackoverflow.com/q/49890536
tags question: http://stackoverflow.com/q/49772024
tags question: http://stackoverflow.com/q/49856775
tags question: http://stackoverflow.com/q/49799998
tags question: http://stackoverflow.com/q/49845706
tags question: http://stackoverflow.com/q/49856659
tags question: http://stackoverflow.com/q/49830843
tags question: http://stackoverflow.com/q/49871737
tags question: http://stackoverflow.com/q/49811350
tags question: http://stackoverflow.com/q/49859625
tags question: http://stackoverflow.com/q/49889641
tags question: http://stackoverflow.com/q/49776618
tags question: http://stackoverflow.com/q/49785536
tags question: http://stackoverflow.com/q/49781866
tags question: http://stackoverflow.com/q/49794710
tags question: http://stackoverflow.com/q/49852241
tags question: http://stackoverflow.com/q/49832185
tags question: http://stackoverflow.com/q/49857979
tags question: http://stackoverflow.com/q/49817410
tags question: http://stackoverflow.com/q/49878985
tags question: http://stackoverflow.com/q/49822699
tags question: http://stackoverflow.com/q/49787260
tags question: http://stackoverflow.com/q/49838863
tags question: http://stackoverflow.com/q/49875832
tags question: http://stackoverflow.com/q/49777618
tags question: http://stackoverflow.com/q/49782375
tags question: http://stackoverflow.com/q/49766378
tags question: http://stackoverflow.com/q/49782962
tags question: http://stackoverflow.com/q/49779430
tags question: http://stackoverflow.com/q/49854629
tags question: http://stackoverflow.com/q/49779136
tags question: http://stackoverflow.com/q/49885247
tags question: http://stackoverflow.com/q/49913007
tags question: http://stackoverflow.com/q/49774035
tags question: http://stackoverflow.com/q/49804489
tags question: http://stackoverflow.com/q/49872500
tags question: http://stackoverflow.com/q/49837854
tags question: http://stackoverflow.com/q/49848209
tags question: http://stackoverflow.com/q/49890487
tags question: http://stackoverflow.com/q/49827392
tags question: http://stackoverflow.com/q/49767084
tags question: http://stackoverflow.com/q/49767638
tags question: http://stackoverflow.com/q/49891820
tags question: http://stackoverflow.com/q/49908588
tags question: http://stackoverflow.com/q/49838269
tags question: http://stackoverflow.com/q/49865386
tags question: http://stackoverflow.com/q/49873676
tags question: http://stackoverflow.com/q/49842705
tags question: http://stackoverflow.com/q/49798017
tags question: http://stackoverflow.com/q/49800045
tags question: http://stackoverflow.com/q/49811533
tags question: http://stackoverflow.com/q/49854778
tags question: http://stackoverflow.com/q/49890470
tags question: http://stackoverflow.com/q/49908705
tags question: http://stackoverflow.com/q/49886986
tags question: http://stackoverflow.com/q/49839270
tags question: http://stackoverflow.com/q/49847523

http://stackoverflow.com/q/49860162
tagged with: nltk
tagged with: python
has comment: http://stackoverflow.com/comment/86735994
tagged with: text
tagged with: movie
upvote count: 4
possible better answer: http://stackoverflow.com/a/49863452
score: 4
has body: I'm working on a project about the meaning of women in movies. Therefore I'm analyzing movie scripts to get a ratio of spoken words by main male character/main female character. I'm having a problem to filter the spoken words from the NAMES and the directing instruction. I thought about regex, but I'm not into it. For example: Mia works, photos of Hollywood icons on the wall behind her, as -- CUSTOMER #1 This doesn't taste like almond milk. MIA Don't worry, it is. I know sometimes it -- CUSTOMER #1 Can I see the carton? Mia hands it over. The Customer looks. CUSTOMER #1 (CONT'D) I'll have a black coffee. I've no idea what to do with the blank new line after the spoken text. Any ideas how to reduce the complete movie script to an only dialogue script, where I can count the words and work with the data? from nltk.tokenize import word_tokenize f = open("/...//La_la_land_script.txt", "r") script = f.read() I'm loading the movie script into python def deletebraces (str): klammerauf = str.find('(') klammerzu = str.find(')') while (klammerauf != -1 and klammerzu != -1): if (klammerauf&lt;klammerzu): str = str[:klammerauf] + str[klammerzu+1:] klammerauf = str.find('(') klammerzu = str.find(')') return str This function deletes all brackets def removing(list): for i in list: if i == '?': list.remove('?') if i == '!': list.remove('!') if i == '.': list.remove('.') if i == ',': list.remove(',') if i == '...': list.remove('...') return list This function deletes all the other symbols def countingwords(list): woerter = 0 for i in list: woerter = woerter + 1 return woerter; this function counts the words script = deletebraces(script) def wordsspoken(script, name): a = 0 e = 0 all = -len(name)-1 if script.find(name)==-1: print("This character does not speak") Checks whether there is the character with the name else: while(a != -1 and e != -1): a = script.find(name+'\n ') + len(name) print(a) temp = script[a:] t = temp.split("\n") text = t[1] print(text) textlist = word_tokenize(te…
accepted answer: http://stackoverflow.com/a/49866802
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86737272
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49866802
has comment: http://stackoverflow.com/comment/86738060
has comment: http://stackoverflow.com/comment/86737104
has title: Uncover a dialogue of a movie script to count the words spoken by characters
favorite count: 0
has comment: http://stackoverflow.com/comment/86736206
has comment: http://stackoverflow.com/comment/86736910
type: Question
has answer: http://stackoverflow.com/a/49863452

http://stackoverflow.com/comment/86836184
score: 0
comment on: http://stackoverflow.com/q/49910112
type: Comment
type: QuestionComment
has text: What's the point of having a list of dicts where each dict only has a single key? This looks like you'd do yourself a favor if you got rid of either the list or the dicts. Is there a reason why you can't use a structure like `{'a': Class1(input_data), 'b': Class2(input_data), 'c': Class3(input_data)}`?

http://stackoverflow.com/q/49795022
downvote count: 0
has comment: http://stackoverflow.com/comment/86604346
duplicate of: http://stackoverflow.com/q/2600790
score: 1
upvote count: 1
tagged with: python-collections
tagged with: types
favorite count: 0
type: Question
tagged with: python-3.x
has title: nested defaultdict: TypeError: first argument must be callable or None
duplicate of: http://stackoverflow.com/q/5369723
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86604434
has body: Truing to create a nested defaultdict to avoid having to write long code. The final defaultdict should looks like this: dd = {str:{str:{str:{[]}}}} But when I try to append item into the list it returns TypeError: dd = defaultdict(lambda: defaultdict(lambda: defaultdict([]))) dd['something1']['something11']['something111'].append('something') ----> 1 dd = defaultdict(lambda: defaultdict(lambda: defaultdict([]))) TypeError: first argument must be callable or None Do you know where is the problem?
tagged with: python
has comment: http://stackoverflow.com/comment/86604437
linked to: http://stackoverflow.com/q/5369723
has comment: http://stackoverflow.com/comment/86604737
tagged with: defaultdict
has comment: http://stackoverflow.com/comment/86604716
has comment: http://stackoverflow.com/comment/86604385
answer count: 0

http://stackoverflow.com/a/49842769
has body: @jpp's numpy solution is probably the way to go, for the reasons they gave, but if you wanted to do it from pure python, you could do the following: #Get the maximum value for each list [[max(i)] for i in my_list] # [[0.29786723455046826], [0.2598119564634982], [0.250361664212574], # [0.2933749527592357], [0.2871675245316243], [0.25282876786143976]] # Get the maximum 2 values for each list: [sorted(i)[-2:] for i in my_list] # Get the maximum 3 values for each list: [sorted(i)[-3:] for i in my_list] And so on. Note that this will not reorder the original list, as the sorting is occurring in the sublists being created in the list comprehension
score: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49842547
downvote count: 1
answers question: http://stackoverflow.com/q/49842547
type: Answer
upvote count: 4

http://stackoverflow.com/q/49777682
tagged with: qtextbrowser
answer count: 1
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/86572236
has title: Python - pyqt5 - clear selections of QTextBrowser
type: Question
has body: I want to clear the selection in QTextBrowser (clear the highlighting). self.textBrowser.textCursor().clearSelection() Above code is not working for me.
tagged with: python
accepted answer: http://stackoverflow.com/a/49778827
has comment: http://stackoverflow.com/comment/86572123
tagged with: qt
has answer: http://stackoverflow.com/a/49778827
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49847478
score: 1
downvote count: 0
upvote count: 1
has title: py2exe: run the compiled .exe, got error: type object 'pandas._libs.tslib._TSObject' has no attribute...__'
tagged with: py2exe
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86712212
type: UnansweredQuestion
tagged with: python
has body: I use py2exe to compile python script. The python script runs without any error before compiling. below is the setup.py from distutils.core import setup import py2exe, sys, os import matplotlib import numpy from glob import glob sys.argv.append('py2exe') datafiles = [("Microsoft.VC90.CRT", glob(r'C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.1_none_99b61f5e8371c1d4\*.*'))] datafiles.extend(matplotlib.get_py2exe_datafiles()) setup(windows=['Run.py'], data_files= datafiles, options={"py2exe": {"includes": ["matplotlib"]}}) In the run.py, I imported pandas. Pandas is used in a function as below import pandas def PossDist(Iterations, AssumptionFolder, ResultFolder, SampledResult): SampledLoss = pandas.read_csv(SampledResult) d= pandas.pivot_table(...) The compile finished successfully without error. When I run the compiled run.exe, I got error as below. Traceback (most recent call last): File "Run.py", line 6, in File "xlwings__init__.pyc", line 34, in File "xlwings\main.pyc", line 1727, in File "xlwings\conversion__init__.pyc", line 3, in File "pandas__init__.pyc", line 26, in Main Features File "pandas_libs__init__.pyc", line 4, in File "pandas_libs\tslib.pyc", line 12, in File "pandas_libs\tslib.pyc", line 10, in __load File "pandas_libs\tslib.pyx", line 1514, in init pandas._libs.tslib AttributeError: type object 'pandas._libs.tslib._TSObject' has no attribute 'reduce_cython' Anyone have any clue? Is there other way to let others run my python script on pc without python installed? Thanks,
answer count: 0
tagged with: pandas

http://stackoverflow.com/q/49827330
type: Question
has answer: http://stackoverflow.com/a/49833655
has answer: http://stackoverflow.com/a/49827623
has body: I am having an issue pulling from a combined dictionary and list. I understand how to pull keys from each one individually but I need to combine them and pull the keys from both. The following is an Example of a dictionary listing years. Each year has a title and director associated with it. movie_collection = { 2005: {'Title':'Munich','Director':'Steven Spielberg'}, 2005: {'Title':'The Prestige','Director':'Christopher Nolan'}, 2006: {'Title':'The Departed','Director':'Martin Scorsese'}, 2007: {'Title':'Into the Wild','Director':'Sean Penn'}, 2008: {'Title':'The Dark Knight','Director':'Christopher Nolan'}, 2009: {'Title':'Mary and Max','Director':'Adam Elliot'}, 2010: {'Title':'The King''s Speech','Director':'Tom Hooper'}, 2011: {'Title':'The Artist','Director':'Michel Hazanavicius'}, 2011: {'Title':'The Help','Director':'Tate Taylor'}, 2012: {'Title':'Argo','Director':'Ben Affleck'}, 2013: {'Title':'12 Years a Slave','Director':'Steve McQueen'}, 2014: {'Title':'Birdman','Director':'Alejandro G. Inarritu'}, 2015: {'Title':'Spotlight','Director':'Tom McCarthy'}, 2016: {'Title':'The BFG','Director':'Steven Spielberg'} } I also have the code prompting for an input year between 2005 and 2016. If the year is not between those years it will print a N/A. input_year = int(input('Enter a year between 2005 and 2016:\n')) if input_year &lt; 2005: print('N/A') elif input_year &gt; 2016: print('N/A') else: print(input_year) Now here is where I am having an issue. Right after the else statment, I need to also print the title and director of the movies associated with the input year. Example if you input the year 2011 the output needs to be: Enter a year between 2005 and 2016: 2011 The Artist, Michel Hazanavicius The Help, Tate Taylor I have the following code written. if input_year in movie_collection: for Title,Director in movie_collection.values(): print(Title,',',Director) But it does not output the correct information. Enter a year between 2005 and 2016: 2011 Director , Tit…
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86670559
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
accepted answer: http://stackoverflow.com/a/49827623
has title: Input a number, Search through Lists and Dictionary, print associated key
has comment: http://stackoverflow.com/comment/86670257
possible better answer: http://stackoverflow.com/a/49833655

http://stackoverflow.com/q/49804670
tagged with: visual-studio-2015
tagged with: c++
has title: scipy.io.loadmat() is causing a null pointer to PyImport_Import()
upvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86627079
has body: I am using scipy.io to load a .mat file through python. I then want to import this python script using c++ in visual studio. Ex. 1: testpython.py b=[0,1,2,3] testimport.cpp PyObject *pName = PyUnicode_FromString((char*)"testpython"); std::cout &lt;&lt; pName &lt;&lt; std::endl; // Load the module object PyObject *pModule = PyImport_Import(pName); std::cout &lt;&lt; pModule &lt;&lt; std::endl; PyObject *b = PyObject_GetAttrString(pModule, "b"); std::cout &lt;&lt; b &lt;&lt; std::endl; PyObject *barray = PyArray_FromObject(b, NPY_DOUBLE, 1, 2); std::cout &lt;&lt; barray &lt;&lt; std::endl; This works, but it is not what I want to do. Ex. 2: testpython.py import scipy.io as sio x=sio.loadmat('matfile.m') y=x['variable1'] testimport.cpp PyObject *pName = PyUnicode_FromString((char*)"testpython"); std::cout &lt;&lt; pName &lt;&lt; std::endl; // Load the module object PyObject *pModule = PyImport_Import(pName); std::cout &lt;&lt; pModule &lt;&lt; std::endl; PyObject *b = PyObject_GetAttrString(pModule, "y"); std::cout &lt;&lt; b &lt;&lt; std::endl; PyObject *barray = PyArray_FromObject(b, NPY_DOUBLE, 1, 2); std::cout &lt;&lt; barray &lt;&lt; std::endl; pModule returns null and the code breaks when sio.loadmat is used in python, but it works when sio.loadmat is not used. Does anyone have any suggestions as to what is happening and how to address this problem? Thank you!
downvote count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/86627066
favorite count: 0
has comment: http://stackoverflow.com/comment/86625124
type: Question
has answer: http://stackoverflow.com/a/49806383
tagged with: python
score: -1

http://stackoverflow.com/a/50136751
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/49847976
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49847976
has body: The way I your reference for updateLdapAuthentication is that you do not specify a list of dictionaries but one dictionary with a key server which has a list of dictionaries. So instead of [{'server': {'hostName': '172.20.23.230', 'ldapPortNumber': '3268', 'sslEnabled': 'false'}}, {'server': {'hostName': '172.20.23.250', 'ldapPortNumber': '3268', 'sslEnabled': 'false'}}] try {'server': [{'hostName': '172.20.23.230', 'ldapPortNumber': '3268', 'sslEnabled': 'false'}, {'hostName': '172.20.23.250', 'ldapPortNumber': '3268', 'sslEnabled': 'false'}}]

http://stackoverflow.com/q/49883255
downvote count: 0
score: 1
upvote count: 1
has body: Using python 3.6, all additional libraries required by program are available (and were included in process), but this error is occurring even when there is already hook module available in pyinstaller dir.
has comment: http://stackoverflow.com/comment/86789024
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86813052
tagged with: encoding
type: Question
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/86807059
answer count: 0
tagged with: python
type: UnansweredQuestion
tagged with: module
has title: 'encodings' module not found while using pyinstaller
linked to: http://stackoverflow.com/q/38132755

http://stackoverflow.com/a/49946820
type: Answer
has body: Ok, guys.I've discovered what is wrong on the code. Below the correct code: public static string GetPythonVersion() { string command = "python --version"; string output = null; using (System.Diagnostics.Process p = new System.Diagnostics.Process()) { p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = String.Format(@"/c {0}\{1} ", "C:/Python36/", command); p.StartInfo.CreateNoWindow = true; if (p.Start()) output = p.StandardError.ReadToEnd(); } return output; } yeah, the python version is on StandardError, because, as you can see on : https://docs.python.org/3/using/cmdline.html#generic-options "Print the Python version number and exit." So when run the command on cmd, at the StandardOutput there is nothin... thanks to everyone for trying to help me ! now this case is over!
score: 0
accepted answer of: http://stackoverflow.com/q/49858395
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49858395

http://stackoverflow.com/comment/86806878
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49895284
has text: Okay I see the `client_id` which is good. Now please put `import pdb; pdb.set_trace()` after the opening of `if` statement and then run the server. This will enable debug mod and press `n` for next let's see where the error occours. It's just for debugging.
type: Comment

http://stackoverflow.com/a/49790296
answers question: http://stackoverflow.com/q/49789902
downvote count: 0
has body: You don't need to re-read the file if you already have its contents stored in myBytesVar: myBytesVar = b'line1\nline2' with open('myFile.txt', 'wb') as fw: fw.write(myBytesVar) myVar = myBytesVar.decode('utf-8') The encoding Python assumes when reading files as text without an explicit encoding is platform-dependent, so I'm just assuming UTF-8 will work.
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49789902
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/49787715
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49787617
has body: because of a default parameter on python will be bound only once on program initiation. so for the first call of f() it returns [3] and change array that x refers to [3]. so print([3]+f()) print(f()) then the second call on f(), since [] has changed to [3], the result will be [3,3] and also the array under a reference will be changed too. so print([3,3]+[3,3]) print(f()) similar to the next line. It will return [3,3] + [3] print([3,3]+[3,3]) print([3,3,3]) That is how you get it.
type: Answer

http://stackoverflow.com/q/49787121
favorite count: 0
type: Question
has body: Sorry if I don't know how to give this a proper title. I just cant explain properly since english is not my first language but i'll give it a try. So this is my code structure while True: get_frame() process_frame() show_frame() it executes this way: get_frame() --> process_frame() --> show_frame() --> get_frame() so it only get frames after processing and showing the frame which takes too much time. What I really want is for the get_frame() to execute again when process_frame() executes, and for the process_frame() to execute again when show_frame() executes, and so on Something like this: get_frame() --> process_frame()&amp;get_frame() --> show_frame()&amp;process_frame()&amp;get_frame() --> and so on
type: UnansweredQuestion
tagged with: python
score: 0
has title: How to code functions to execute in parallel (python)?
has comment: http://stackoverflow.com/comment/86589638
answer count: 1
has answer: http://stackoverflow.com/a/49793169
has comment: http://stackoverflow.com/comment/86589523
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/49885701
has body: I'm having issues running my automation test scripts. When I run my script, a browser will appear but it will not type the URL and waits for 10 seconds until it throws an exception. Is there any solutions I can use so then I can get my automation test scripts to work? Geckodriver.log: 1523997052492 geckodriver INFO geckodriver 0.20.1 1523997052531 geckodriver INFO Listening on 127.0.0.1:37807 1523997052592 mozrunner::runner INFO Running command: "/usr/bin/firefox/firefox" "-marionette" "--headless" "-profile" "/tmp/rust_mozprofile.PU1cngaAJ5Tg" 1523997054831 Marionette INFO Listening on port 2828 Stack Traces: Error Traceback (most recent call last): File "/home/kavin/PycharmProjects/untitled/Testing/purchaseAmazonItems.py", line 13, in setUp self.driver = webdriver.Firefox(firefox_binary=binary, firefox_options=opts) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/firefox/webdriver.py", line 162, in __init__ keep_alive=True) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: connection refused Code: def setUp(self): binary = FirefoxBinary('/usr/bin/firefox/firefox') opts = FirefoxOptions() opts.add_argument("--headless") self.driver = webdriver.Firefox(firefox_binary=binary, firefox_options=opts) driver = self.driver driver.get('https://www.amazon.com/') Specs: Ubuntu 16.04 geckodriver 0.20.1 firefox 5…
has comment: http://stackoverflow.com/comment/86806121
tagged with: selenium-webdriver
has title: Selenium Python selenium.common.exceptions.WebDriverException: Message: connection refused using geckodriver and firefox
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86828423
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86828340
has answer: http://stackoverflow.com/a/49908110
accepted answer: http://stackoverflow.com/a/49908110
has answer: http://stackoverflow.com/a/49886140
possible better answer: http://stackoverflow.com/a/49886140
tagged with: selenium
favorite count: 0
type: Question
tagged with: firefox
tagged with: geckodriver
upvote count: 6
score: 6
linked to: http://stackoverflow.com/q/46753393
tagged with: python

http://stackoverflow.com/comment/86653789
type: Comment
has text: Even before running the code, it shows error with "print(cp.out, file=fp)" line.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49812722

http://stackoverflow.com/q/49816258
has comment: http://stackoverflow.com/comment/86647086
has comment: http://stackoverflow.com/comment/86648078
has comment: http://stackoverflow.com/comment/86647004
type: Question
has comment: http://stackoverflow.com/comment/86647403
has comment: http://stackoverflow.com/comment/86647357
has title: Optimizing a feature in Python
linked to: http://stackoverflow.com/q/582336
has comment: http://stackoverflow.com/comment/86647176
has comment: http://stackoverflow.com/comment/86647790
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86647570
has comment: http://stackoverflow.com/comment/86650537
tagged with: python
has comment: http://stackoverflow.com/comment/86647466
has comment: http://stackoverflow.com/comment/86647331
has comment: http://stackoverflow.com/comment/86648089
has comment: http://stackoverflow.com/comment/86647381
has comment: http://stackoverflow.com/comment/86647897
tagged with: optimization
has comment: http://stackoverflow.com/comment/86646826
tagged with: combinations
score: 0
has body: I have a piece of code that requires hours to run on long lists : for elt in listCombinaisons_survivor: effects = [] for idBadge in elt: effects.append(dictBadges[idBadge]["Effect"]) cpt = Counter(effects) for type_effect in cpt.keys(): cpt_effect = cpt[type_effect] if cpt_effect &gt; 3: listCombinaisons_survivor.remove(elt) break My listCombinaisons_survivor contains all the possible combinations of 6 badges among 57 possibilities ([1,2,3,5,6,7],[1,2,3,5,6,8]...). For each possible combination, I pick in a dictionary the "Effect" matching the badge ID (Badge ID 1 = Damage), and I collect all the effects in the list "effects". I then count how much occurencies of each effect I have, and if I have more than 3 badges with the same effect in a combination, I delete this combination. Is there any way I could optimize this code to make it faster ? I also tried this but this is not faster : newlist_combinations = [] for elt in listCombinaisons_survivor: effects = [] for idBadge in elt: effects.append(dictBadges[idBadge]["Effect"]) cpt = Counter(effects) for type_effect in cpt.keys(): cpt_effect = cpt[type_effect] if cpt_effect &gt; 3: break if not cpt_effect &gt; 3: newlist_combinations.append(elt) I don't want to know how much time it takes, but how to optimize this code. The whole code can be found there : https://github.com/yirkkiller/Python/blob/master/badgesRepartition-NEW.py Thanks !
has comment: http://stackoverflow.com/comment/86647676
has comment: http://stackoverflow.com/comment/86646832
has comment: http://stackoverflow.com/comment/86648169
answer count: 1
has answer: http://stackoverflow.com/a/49816984
has comment: http://stackoverflow.com/comment/86646856

http://stackoverflow.com/comment/86712975
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49848989
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169048/discussion-between-ben10-and-aidan).

http://stackoverflow.com/q/49886839
has title: Python - Data processing with array
tagged with: loops
has body: I'm using Python to work with data from csv files, and after reading csv into an array, my data looks like this: data = [ ["10","2018-03-22 14:38:18.329963","name 10","url10","True"], ["11","2018-03-22 14:38:18.433497","name 11","url11","False"], ["12","2018-03-22 14:38:18.532312","name 12","url12","False"] ] I know I can use "for" loop but my data has around millions of records and the "for" loop takes too long time to run, so do you have any idea to do task listed below without using "for"? Convert value from string to integer in column 1 (ie: "10" -> 10) Add "http://" in column 3 (ie: "url10" -> "http://url10") Convert value in column 4 to boolean (ie: "False" -> False) Thank you a lot!
has answer: http://stackoverflow.com/a/49887209
favorite count: 0
type: Question
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49886914
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
tagged with: python
tagged with: data-processing
score: 2
linked to: http://stackoverflow.com/q/1247486
has comment: http://stackoverflow.com/comment/86789922

http://stackoverflow.com/comment/86714497
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49849683
score: 0
has text: Also, assigning to `self` doesn't make sense here.

http://stackoverflow.com/q/49866967
has comment: http://stackoverflow.com/comment/86749475
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86749701
score: 0
has comment: http://stackoverflow.com/comment/86749961
has comment: http://stackoverflow.com/comment/86749757
tagged with: pandas
has comment: http://stackoverflow.com/comment/86749985
answer count: 1
has body: I'm trying to add two columns with NaNs. The behavior I want is: If both are NaNs, then this column should be NaN If one of them are numeric, then the value should be numeric (the NaN is treated as 0's) a = pd.DataFrame([1, np.NaN, 4, 5]) b = pd.DataFrame([3, np.NaN, 5, np.NaN]) a+b 0 4.0 1 NaN 2 9.0 3 NaN Is there a way to do this built-in functions?
has answer: http://stackoverflow.com/a/49867001
has comment: http://stackoverflow.com/comment/86750050
type: Question
has comment: http://stackoverflow.com/comment/86750017
has comment: http://stackoverflow.com/comment/86749573
has comment: http://stackoverflow.com/comment/86749501
has comment: http://stackoverflow.com/comment/86749537
linked to: http://stackoverflow.com/q/16202711
has comment: http://stackoverflow.com/comment/86749519
has comment: http://stackoverflow.com/comment/86749895
has comment: http://stackoverflow.com/comment/86749917
has title: Pandas - Add two columns with NaNs
duplicate of: http://stackoverflow.com/q/16202711
tagged with: python
accepted answer: http://stackoverflow.com/a/49867001

http://stackoverflow.com/comment/86774251
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49877928
score: 0
has text: The proposed version is to use `drop()`, I'm changing the timeout in Neptune configuration system from 2 minutes to 5 minutes. Can you tell me how can I know what error `597` is? (The first error in the question).

http://stackoverflow.com/a/49840320
has comment: http://stackoverflow.com/comment/86836629
type: Answer
answers question: http://stackoverflow.com/q/49837565
has comment: http://stackoverflow.com/comment/86835969
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/86836667
has body: For an older application, it implements the functions that saved the states of the widgets and restored them. In order for it to work properly, the application must meet the following requirements: You have to set OrganizationName, OrganizationDomain and ApplicationName. Each widget that you want to save the state must have an objectName You must use restore() when you want to restore the states, a good option is after creating all the widgets. You must use save() when you want to save the states, a good place would be closeEvent(). In the next part I show an example: import sys from PyQt5 import QtWidgets, QtCore # for PyQt4 change QtWidget to QtGui and PyQt5 to PyQt4 def restore(settings): finfo = QtCore.QFileInfo(settings.fileName()) if finfo.exists() and finfo.isFile(): for w in QtWidgets.qApp.allWidgets(): mo = w.metaObject() if w.objectName() and not w.objectName().startswith("qt_"): settings.beginGroup(w.objectName()) for i in range( mo.propertyCount(), mo.propertyOffset()-1, -1): prop = mo.property(i) if prop.isWritable(): name = prop.name() val = settings.value(name, w.property(name)) if str(val).isdigit(): val = int(val) w.setProperty(name, val) settings.endGroup() def save(settings): for w in QtWidgets.qApp.allWidgets(): mo = w.metaObject() if w.objectName() and not w.objectName().startswith("qt_"): settings.beginGroup(w.objectName()) for i in range(mo.propertyCount()): prop = mo.property(i) name = prop.name() if prop.isWritable(): settings.setValue(name, w.property(name)) settings.endGroup() class Widget(QtWidgets.QWidget): def __init__(self, parent=None): super().__init__(parent) self.setObjectName("widget") self.init_ui() self.settings = QtCore.QSettings() print(self.settings.fileName()) restore(self.settings) def init_ui(self): lay = QtWidgets.QVBoxLayout(self) lineEdit1 = QtWidgets.QLabel("label") lineEdit1.setObjectName("label") lineEdit2 = QtWidgets.QLineEdit() lineEdit2.setObjectName("lineEdit2") combobox = QtWidgets.QComboBox() combobox.addItems(…
downvote count: 0
has comment: http://stackoverflow.com/comment/86753726
has comment: http://stackoverflow.com/comment/86752968
has comment: http://stackoverflow.com/comment/86753793
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86836643
has comment: http://stackoverflow.com/comment/86836557
has comment: http://stackoverflow.com/comment/86835691
has comment: http://stackoverflow.com/comment/86836714
has comment: http://stackoverflow.com/comment/86836540
accepted answer of: http://stackoverflow.com/q/49837565
has comment: http://stackoverflow.com/comment/86753819

http://stackoverflow.com/q/49905190
has comment: http://stackoverflow.com/comment/86826905
has title: Optimize output of a script by varying input parameters
tagged with: python
has comment: http://stackoverflow.com/comment/86827411
has comment: http://stackoverflow.com/comment/86827665
tagged with: optimization
tagged with: mathematical-optimization
answer count: 0
downvote count: 0
has body: I have a written a script that uses the code below and I would like to optimize rsi_high and rsi_low to get the best sharpe_ratio: # import numpy import talib as ta global rsi_high, rsi_low rsi_high = 63 rsi_low = 41 def myTradingSystem(DATE, OPEN, HIGH, LOW, CLOSE, VOL, exposure, equity, settings): ''' This system uses trend following techniques to allocate capital into the desired equities''' nMarkets = CLOSE.shape[1] # SHAPE OF NUMPY ARRAY result, rsi_pos = numpy.apply_along_axis(rsicalc, axis=0, arr=CLOSE) pos = numpy.asarray(rsi_pos, dtype=numpy.float64) return pos, settings def rsicalc(num): # print rsi_high try: rsival = ta.RSI(numpy.array(num,dtype='f8'),timeperiod=14) if rsival[14] &gt; rsi_high: pos_rsi = 1 elif rsival[14] &lt; rsi_low: pos_rsi = -1 else: pos_rsi = 0 except: rsival = 0 pos_rsi = 0 return rsival, pos_rsi def mySettings(): ''' Define your trading system settings here ''' settings = {} # Futures Contracts settings['markets'] = ['CASH','F_AD', 'F_BO', 'F_BP', 'F_C', 'F_CC', 'F_CD', 'F_CL', 'F_CT', 'F_DX', 'F_EC', 'F_ED', 'F_ES', 'F_FC', 'F_FV', 'F_GC', 'F_HG', 'F_HO', 'F_JY', 'F_KC', 'F_LB', 'F_LC', 'F_LN', 'F_MD', 'F_MP', 'F_NG', 'F_NQ', 'F_NR', 'F_O', 'F_OJ', 'F_PA', 'F_PL', 'F_RB', 'F_RU', 'F_S', 'F_SB', 'F_SF', 'F_SI', 'F_SM', 'F_TU', 'F_TY', 'F_US', 'F_W', 'F_XX', 'F_YM'] settings['slippage'] = 0.05 settings['budget'] = 1000000 settings['beginInSample'] = '19900101' settings['endInSample'] = '19931231' settings['lookback'] = 504 return settings # Evaluate trading system defined in current file. if __name__ == '__main__': import quantiacsToolbox results = quantiacsToolbox.runts(__file__, plotEquity=False) sharpe_ratio = results['stats']['sharpe'] I suspect that using something like scipy minimize function would do the trick, but I am having trouble understanding how to package my script so that it can be in a usable form. I have tried putting everything in a function and then running all the code through a number of loops, each time increm…
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: scipy
favorite count: 0
type: Question

http://stackoverflow.com/q/49916290
type: Question
has comment: http://stackoverflow.com/comment/86852062
has answer: http://stackoverflow.com/a/49918425
score: 5
has body: As the title says. When I execute the converted python file (the .exe) I get the following output: Traceback (most recent call last): File "background.py", line 10, in &lt;module&gt; File "site-packages\praw\reddit.py", line 129, in __init__ File "site-packages\praw\config.py", line 72, in __init__ File "site-packages\praw\config.py", line 98, in _initialize_attributes File "site-packages\praw\config.py", line 31, in _config_boolean AttributeError: '_NotSet' object has no attribute 'lower' [1692] Failed to execute script background I did not use a praw.ini file, instead hardcoding the values for the logon as such: import praw import praw.models import urllib.request from random import randint from os import getcwd import ctypes r = praw.Reddit(client_id='client', client_secret='secret', user_agent='user') sub = r.subreddit('earthporn') choose = [] for i in sub.hot(limit=20): a = str(i.url) if "i.redd" in a or "i.imgur" in a: choose.append(i.url) x = choose[randint(0,len(choose)-1)] resource = urllib.request.urlopen(x) output = open("daily_image.jpg","wb") output.write(resource.read()) output.close() direc = getcwd() + "\\daily_image.jpg" ctypes.windll.user32.SystemParametersInfoW(20, 0, direc , 0) The above file works in just python but not when converted to an exe. (obviously with the client,secret and user id's set, feel free to steal it idrc) Any help is really appreciated!
tagged with: pyinstaller
possible better answer: http://stackoverflow.com/a/57314041
has comment: http://stackoverflow.com/comment/86849570
upvote count: 5
has answer: http://stackoverflow.com/a/57314041
tagged with: python
has answer: http://stackoverflow.com/a/67261188
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86955755
tagged with: attributeerror
has title: "AttributeError: '_NotSet' object has no attribute 'lower'" when a PRAW python file is converted to an exe using Pyinstaller
downvote count: 0
tagged with: praw
has answer: http://stackoverflow.com/a/71055497
accepted answer: http://stackoverflow.com/a/49918425
favorite count: 0

http://stackoverflow.com/q/49774825
favorite count: 0
type: Question
upvote count: 25
accepted answer: http://stackoverflow.com/a/49775393
tagged with: lightgbm
has body: I want to do a cross validation for LightGBM model with lgb.Dataset and use early_stopping_rounds. The following approach works without a problem with XGBoost's xgboost.cv. I prefer not to use Scikit Learn's approach with GridSearchCV, because it doesn't support early stopping or lgb.Dataset. import lightgbm as lgb from sklearn.metrics import mean_absolute_error dftrainLGB = lgb.Dataset(data = dftrain, label = ytrain, feature_name = list(dftrain)) params = {'objective': 'regression'} cv_results = lgb.cv( params, dftrainLGB, num_boost_round=100, nfold=3, metrics='mae', early_stopping_rounds=10 ) The task is to do regression, but the following code throws an error: Supported target types are: ('binary', 'multiclass'). Got 'continuous' instead. Does LightGBM support regression, or did I supply wrong parameters?
has answer: http://stackoverflow.com/a/49775393
tagged with: cross-validation
tagged with: python
score: 25
type: AnsweredQuestion
tagged with: regression
answer count: 1
downvote count: 0
has title: How to use lightgbm.cv for regression?

django
tags question: http://stackoverflow.com/q/49842829
tags question: http://stackoverflow.com/q/49860131
tags question: http://stackoverflow.com/q/49824321
tags question: http://stackoverflow.com/q/49830796
tags question: http://stackoverflow.com/q/49915003
tags question: http://stackoverflow.com/q/49897357
tags question: http://stackoverflow.com/q/49807541
tags question: http://stackoverflow.com/q/49812962
tags question: http://stackoverflow.com/q/49773253
tags question: http://stackoverflow.com/q/49849567
tags question: http://stackoverflow.com/q/49784795
tags question: http://stackoverflow.com/q/49904804
tags question: http://stackoverflow.com/q/49915328
tags question: http://stackoverflow.com/q/49904620
tags question: http://stackoverflow.com/q/49851179
tags question: http://stackoverflow.com/q/49829212
tags question: http://stackoverflow.com/q/49759078
tags question: http://stackoverflow.com/q/49762598
tags question: http://stackoverflow.com/q/49895398
tags question: http://stackoverflow.com/q/49877354
tags question: http://stackoverflow.com/q/49763292
tags question: http://stackoverflow.com/q/49783177
tags question: http://stackoverflow.com/q/49778446
tags question: http://stackoverflow.com/q/49772474
tags question: http://stackoverflow.com/q/49775314
tags question: http://stackoverflow.com/q/49808022
tags question: http://stackoverflow.com/q/49773300
tags question: http://stackoverflow.com/q/49902586
tags question: http://stackoverflow.com/q/49832618
tags question: http://stackoverflow.com/q/49912511
tags question: http://stackoverflow.com/q/49837092
tags question: http://stackoverflow.com/q/49767573
tags question: http://stackoverflow.com/q/49817574
tags question: http://stackoverflow.com/q/49827112
tags question: http://stackoverflow.com/q/49832606
tags question: http://stackoverflow.com/q/49826581
tags question: http://stackoverflow.com/q/49761879
tags question: http://stackoverflow.com/q/49790012
tags question: http://stackoverflow.com/q/49772684
tags question: http://stackoverflow.com/q/49790723
tags question: http://stackoverflow.com/q/49833183
tags question: http://stackoverflow.com/q/49861748
tags question: http://stackoverflow.com/q/49905484
tags question: http://stackoverflow.com/q/49836077
tags question: http://stackoverflow.com/q/49825870
tags question: http://stackoverflow.com/q/49821426
tags question: http://stackoverflow.com/q/49832735
tags question: http://stackoverflow.com/q/49823075
tags question: http://stackoverflow.com/q/49798116
tags question: http://stackoverflow.com/q/49864504
tags question: http://stackoverflow.com/q/49770344
tags question: http://stackoverflow.com/q/49899671
tags question: http://stackoverflow.com/q/49849433
tags question: http://stackoverflow.com/q/49831561
tags question: http://stackoverflow.com/q/49829928
tags question: http://stackoverflow.com/q/49805651
tags question: http://stackoverflow.com/q/49829210
tags question: http://stackoverflow.com/q/49784358
tags question: http://stackoverflow.com/q/49806893
tags question: http://stackoverflow.com/q/49861004
tags question: http://stackoverflow.com/q/49862247
tags question: http://stackoverflow.com/q/49879103
tags question: http://stackoverflow.com/q/49913996
tags question: http://stackoverflow.com/q/49766058
tags question: http://stackoverflow.com/q/49758348
tags question: http://stackoverflow.com/q/49873536
tags question: http://stackoverflow.com/q/49791282
tags question: http://stackoverflow.com/q/49833273
tags question: http://stackoverflow.com/q/49907266
tags question: http://stackoverflow.com/q/49835798
tags question: http://stackoverflow.com/q/49840767
tags question: http://stackoverflow.com/q/49874923
tags question: http://stackoverflow.com/q/49898084
tags question: http://stackoverflow.com/q/49793932
tags question: http://stackoverflow.com/q/49809879
tags question: http://stackoverflow.com/q/49771587
tags question: http://stackoverflow.com/q/49852738
tags question: http://stackoverflow.com/q/49781482
tags question: http://stackoverflow.com/q/49860092
tags question: http://stackoverflow.com/q/49886388

http://stackoverflow.com/comment/86671160
comment on: http://stackoverflow.com/q/49811960
type: QuestionComment
type: Comment
score: 0
has text: Also related: [Index entire array backwards in for loop](https://stackoverflow.com/q/42674533/364696) (which covers using `None` to explicitly request the "to end of sequence" slice behavior in the forward slice case, but using negative indices for the end of slice index).

http://stackoverflow.com/a/49809727
score: 0
has comment: http://stackoverflow.com/comment/86635167
type: Answer
has comment: http://stackoverflow.com/comment/86634509
has comment: http://stackoverflow.com/comment/86634853
has comment: http://stackoverflow.com/comment/86636847
answers question: http://stackoverflow.com/q/49808613
has body: From the error, it looks like the rdd is not RDD[String] but RDD[Tuple] and since you are trying to apply startswith which is a python string function, it fails. You can try something like this: test = rdd.filter(lambda line: line[0][0].startsWith("I")) The above will filter your RDD and return records whose first element of the tuple starts with I.

http://stackoverflow.com/a/49841058
score: 1
downvote count: 0
upvote count: 1
has body: You can use regex to implement a trivially extensible solution: import re a = "Hi thereu1hello ?u1Whatu2Goodu1Work worku2Stacku2" separators = ['u1', 'u2'] regex = r'(.*?)({})'.format('|'.join(re.escape(sep) for sep in separators)) result = {sep: [] for sep in separators} for match in re.finditer(regex, a, flags=re.S): text = match.group(1) sep = match.group(2) result[sep].append(text) print(result) # {'u1': ['Hi there', 'hello ?', 'Good'], # 'u2': ['What', 'Work work', 'Stack']} This constructs a regex out of the separators u1 and u2 like so: (.*?)(u1|u2) And then it iterates over all matches of this regex and appends them to the corresponding list.
type: Answer
answers question: http://stackoverflow.com/q/49840710

http://stackoverflow.com/a/49882699
has body: The below code will fetch a random post from the memes subreddit. Currently it picks a random submission from the top 10 posts from the hot section. import praw import random from discord.ext import commands bot = commands.Bot(description="test", command_prefix="!") reddit = praw.Reddit(client_id='CLIENT_ID HERE', client_secret='CLIENT_SECRET HERE', user_agent='USER_AGENT HERE') @bot.command() async def meme(): memes_submissions = reddit.subreddit('memes').hot() post_to_pick = random.randint(1, 10) for i in range(0, post_to_pick): submission = next(x for x in memes_submissions if not x.stickied) await bot.say(submission.url) bot.run('TOKEN')
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49881935
has comment: http://stackoverflow.com/comment/86785263
accepted answer of: http://stackoverflow.com/q/49881935
has comment: http://stackoverflow.com/comment/86784970
has comment: http://stackoverflow.com/comment/86823379
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/49889398
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/86795204
answer count: 2
has title: Plot stacked bar chart from pandas data frame
accepted answer: http://stackoverflow.com/a/49889590
tagged with: python
tagged with: plot
has comment: http://stackoverflow.com/comment/86795142
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49889632
possible better answer: http://stackoverflow.com/a/49889632
tagged with: pandas
has answer: http://stackoverflow.com/a/49889590
score: 1
tagged with: matplotlib
has body: I have dataframe: payout_df.head(10) What would be the easiest, smartest and fastest way to replicate the following excel plot? I've tried different approaches, but couldn't get everything into place. Thanks
tagged with: dataframe
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/86782478
has text: Could you explain what you *want* this code to do?
type: Comment
comment on: http://stackoverflow.com/q/49883227
type: QuestionComment
score: 4

http://stackoverflow.com/comment/86793658
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49888608
type: Comment
has text: I don't understand why it peaks at 150. I don't know how to anticipate this when automating signal processing.

http://stackoverflow.com/q/49880700
downvote count: 4
tagged with: openmp
tagged with: parallel-processing
has answer: http://stackoverflow.com/a/61243904
has answer: http://stackoverflow.com/a/60319491
has title: Tensorflow OMP: Error #15 when training
has answer: http://stackoverflow.com/a/49893712
has answer: http://stackoverflow.com/a/54914181
has comment: http://stackoverflow.com/comment/86801874
linked to: http://stackoverflow.com/q/53014306
tagged with: tensorflow
favorite count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/86800448
type: Question
has body: I am training my neural network using tensorflow on CentOS HPC. However I got this error at start of the training process: OMP: Error #15: Initializing libiomp5.so, but found libiomp5.so already initialized. OMP: Hint: This means that multiple copies of the OpenMP runtime have been linked into the program. That is dangerous, since it can degrade performance or cause incorrect results. The best thing to do is to ensure that only a single OpenMP runtime is linked into the process, e.g. by avoiding static linking of the OpenMP runtime in any library. As an unsafe, unsupported, undocumented workaround you can set the environment variable KMP_DUPLICATE_LIB_OK=TRUE to allow the program to continue to execute, but that may cause crashes or silently produce incorrect results. For more information, please see http://www.intel.com/software/products/support/. The code is for instance segmentation and it worked fine for many people, but failed in my case. Why it occurs? How to solve it?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86799732
tagged with: python
has comment: http://stackoverflow.com/comment/86777216
score: 4
answer count: 4

http://stackoverflow.com/a/49769015
downvote count: 1
has comment: http://stackoverflow.com/comment/86631332
accepted answer of: http://stackoverflow.com/q/49768770
has comment: http://stackoverflow.com/comment/99174596
upvote count: 453
has body: Upgrade pip as follows: curl https://bootstrap.pypa.io/get-pip.py | python Note: You may need to use sudo python above if not in a virtual environment. (Note that upgrading pip using pip i.e pip install --upgrade pip will also not upgrade it correctly. It's just a chicken-and-egg issue. pip won't work unless using TLS >= 1.2.) As mentioned in this detailed answer, this is due to the recent TLS deprecation for pip. Python.org sites have stopped support for TLS versions 1.0 and 1.1. From the Python status page: Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC For PyCharm (virtualenv) users: Run virtual environment with shell. (replace "./venv/bin/activate" to your own path) source ./venv/bin/activate Run upgrade curl https://bootstrap.pypa.io/get-pip.py | python Restart your PyCharm instance, and check your Python interpreter in Preference.
type: Answer
score: 452
has comment: http://stackoverflow.com/comment/138633486
answers question: http://stackoverflow.com/q/49768770
has comment: http://stackoverflow.com/comment/86627203
has comment: http://stackoverflow.com/comment/86632612
has comment: http://stackoverflow.com/comment/92018501
has comment: http://stackoverflow.com/comment/91824485
has comment: http://stackoverflow.com/comment/103499215
has comment: http://stackoverflow.com/comment/86813977
has comment: http://stackoverflow.com/comment/110999119
has comment: http://stackoverflow.com/comment/133767795
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/110821664
has comment: http://stackoverflow.com/comment/120524156

http://stackoverflow.com/q/49901015
score: 3
has body: I get a nested list as input. Simplified version is as under. myList=[[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9]]] I wish to unpack it into a simple list of lists. I can do like this-- simpleList=[] for i in myList: for j in i: simpleList.append(j) As desired, the simpleList is [[1, 2, 3], [4, 5, 6], [2, 3, 4], [3, 4, 5], [4, 6, 7], [5, 7, 9]] My question:- What I did was, maybe, a beginner's coding approach. Is there a more professional, efficient (and pythonic) approach to unpack this nested list? Thanks. EDIT:- My method doesn't work for deeply nested lists. e.g. [[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9]],[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9],[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9]]]] pl. refer to the comments to answers.
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/86817641
has answer: http://stackoverflow.com/a/49901466
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49901466
tagged with: list
downvote count: 2
answer count: 3
has title: How to unwrap deep list of lists in Python?
has answer: http://stackoverflow.com/a/49901080
has answer: http://stackoverflow.com/a/49901052
possible better answer: http://stackoverflow.com/a/49901052
has comment: http://stackoverflow.com/comment/86817586
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/952914

http://stackoverflow.com/q/49877436
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49878461
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49877660
has comment: http://stackoverflow.com/comment/86772637
downvote count: 0
has answer: http://stackoverflow.com/a/49877660
favorite count: 0
type: Question
tagged with: numpy
has body: I want to insert zeros in a numpy array but in a different way that the numpy.insert function works. The numpy.insert function inserts every element before the position of the given index without caring about the other elements included in the same insertion. That is, the indexs given to the function refer to positions before the insertion. I would like a function that considers the indices after the insertion. Let me give an example: If the input array is array(1, 2, 3, 4) and the indices are [2, 5], the output array should be array(1, 2, 0, 3, 4, 0). A non-vectorized way to do it would be: for index in indices: input_array = np.insert(input_array, index, 0) I am looking for a vectorized way to do this, but I cannot find it.
has title: Vectorized implementation of numpy alternative insert
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/86773147
tagged with: vectorization
possible better answer: http://stackoverflow.com/a/49878461
has comment: http://stackoverflow.com/comment/86772455

http://stackoverflow.com/q/49869485
score: 0
has comment: http://stackoverflow.com/comment/86755296
linked to: http://stackoverflow.com/q/4519127
has answer: http://stackoverflow.com/a/49869523
has title: How to call a function using relative path from other place?
tagged with: python
has body: I an writing a Python package. The index like bellow main.py pkg |--utils.py |--files |--1.txt |--2.txt I write a function to load the file 1.txt in the utils.py using relative path. And it works in the utils.py, but fail when I call the function in the main.py. I konw the reason is the relative path has changed. I want to know how to solve it with not change the relative path. Another problems is how to add the file to the python package when upload to the pipy.
type: Question
accepted answer: http://stackoverflow.com/a/49869523
answer count: 1
type: AnsweredQuestion

http://stackoverflow.com/q/49776192
tagged with: binning
has answer: http://stackoverflow.com/a/49776316
accepted answer: http://stackoverflow.com/a/49776316
has title: Python Binning code and taking average
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49776368
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has body: I am new to Python and am struggling with the following. I have the following dataframe: cat data 1 122.8099975 2 131.02 1 49.123999 2 122.5250015 3 40.86333217 2 61.40250025 2 122.5999985 3 35.02142771 3 246.320007 3 123.885002 3 61.942501 1 247.770004 1 123.885002 bins=array([ 0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260]) I want to create a new column by doing the following: For each category ("cat"), bin the data into bins and take the average of the count of items in each bin as illustrated by these spreadsheets: Then assign the average to the relevant category in a new column: Many thanks in advance.
possible better answer: http://stackoverflow.com/a/49776368
favorite count: 0
type: Question

http://stackoverflow.com/q/49904296
favorite count: 0
has body: I'm having a strange issue with the colorbar and a large clim range. My images/data span many orders of magnitude. When I have a range from 10^-9 to 1. There are no problems, and my colorbar has ticks and tick labels as normal. When my range extends to 10^-10 and below, the ticks and tick labels disappear. Is this a known issue? Please see some example code below. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib import colors fig = plt.figure(num=1, figsize=(10,7), dpi=240) fig.clf() ax = fig.add_subplot(111) img = ax.imshow( image, cmap='nipy_spectral', norm=colors.LogNorm(), clim=(10**-10,1) ) ax.set_xlabel('') ax.set_ylabel('') ax.set_title('') divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="3%", pad=0.1) fig.colorbar(img, cax=cax) fig.show() fig.savefig('filename.png', bbox_inches='tight') Also, this is the code block I normally use for generating figures, with obvious changes for subplots, etc. Is it overkill, or does it seem reasonable? Thank you!
type: Question
tagged with: numpy
tagged with: python-3.x
type: UnansweredQuestion
has title: Matplotlib colorbar ticks disappear with large range
downvote count: 0
tagged with: python
answer count: 0
tagged with: colorbar
score: 1
tagged with: matplotlib
upvote count: 1

http://stackoverflow.com/comment/87961764
has text: I want TC123 as hyperlink,how to do it??
comment on: http://stackoverflow.com/a/49841029
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86583795
type: QuestionComment
comment on: http://stackoverflow.com/q/49784102
has text: Since you want to programmatically interact with a server via a socket, you probably don't want netcat at all. Just [open the socket in Python](https://stackoverflow.com/q/68774/478288) and send/recv as needed.
score: 1
type: Comment

http://stackoverflow.com/comment/86598582
comment on: http://stackoverflow.com/q/49791853
has text: @Pop I set the batch_size to 20, and the shape of sparse labels is [20] which means the batch size is actually 20. so i got confused
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49843746
tagged with: python
score: -1
tagged with: flask
has body: I am trying to get Flask to check if my input is an integer and my form.validate_on_submit(): function is not working - the page just breaks when I type something in the field that is not an integer and gives me 'TypeError: 'NoneType' object cannot be interpreted as an integer' My main.py code is as follows: from wtforms import IntegerField from wtforms.validators import InputRequired from perfect_numbers import classify, listInRange num = 1 app = Flask(__name__) app.config['SECRET_KEY'] = 'DontTellAnyone' class PerfectForm(Form): inputNumber = IntegerField('input a number', validators=[InputRequired(message='Please input an integer')]) @app.route('/', methods=['GET', 'POST']) def index(): form = PerfectForm() Classify = classify(form.inputNumber.data) if form.validate_on_submit(): num = request.form['inputNumber'] return render_template('index.html', form=form, num=num, classify=Classify) return render_template('index.html', num=1, form=form, classify=Classify) if __name__ == '__main__': app.run(debug=True)
type: AnsweredQuestion
tagged with: validation
has title: Can't get Flask WTF to validate input properly
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49843799
tagged with: flask-wtforms
accepted answer: http://stackoverflow.com/a/49843799
upvote count: 0

http://stackoverflow.com/q/49826440
accepted answer: http://stackoverflow.com/a/49826695
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/49826469
possible better answer: http://stackoverflow.com/a/49826469
type: AnsweredQuestion
tagged with: python
tagged with: web-crawler
tagged with: urllib
type: Question
has comment: http://stackoverflow.com/comment/86668696
has body: I am building a web crawler and I encountered a snag. Basically, the crawler finds all the values for &lt; a href="..." > and then tries to systematically navigate to all of those relative links. For instance, if on the homepage of http://example.com there was the links "home.html" and "about.html" the crawler would move through and try to request the base domain + the newly found domain (ex. http://example.com/home.html, http://example.com/about.html). However, on my test site I have it setup where there is a &lt; a href="file.pdf" >. When the urlib function in python tries to request the .pdf file I get this error: Is there a way that I can build a try / except that ignores the URL if this happens? Here is the current relevant code that I have: def soupify(url): """ :param: URL string. :return: HTML BeautifulSoup object as html.parser Process: Requests website for HTML code. If it responds, converts the code into IO stream so that it can become a Soup object. """ # Header info so that the web server does not deny the request hdr = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'} req = urllib.request.Request(url, headers=hdr) page = urllib.request.urlopen(req) # This is to create in memory the HTML code of the page. file = io.TextIOWrapper(page, encoding='utf-8') fileContents = file.read() soupObject = soup(fileContents, "html.parser") return soupObject Then here is what happens when I try to actually access the URL after it has been soupified. url = baseDomain + queue[0] queueLength = len(queue) print("Queue:", queueLength) isError = False # Exception handling when attempting to make a soup object. try: fileContents = soupify(url) except urllib.error.HTTPError: # If the website returns an HTTP error, such as a 404 inaccessibleSites += 1 isError = True queue.pop(0) except urllib.error.URLError: # If the website does not exist or does not have a valid URL inaccessibleSites += 1 isError = True…
score: 0
has title: Python Urlib - Ignore Unicode Error
answer count: 2
has answer: http://stackoverflow.com/a/49826695

http://stackoverflow.com/q/49772474
answer count: 1
accepted answer: http://stackoverflow.com/a/49772614
has body: Hey folks here am facing issue while running Django project I installed Django-WYSIWYG-redactor added redactor into INSTALLED_APPS = ( ... 'redactor', ... ) Add url(r’^redactor/’, include(‘redactor.urls’)), to urls.py Add default config in settings.py # .... REDACTOR_OPTIONS = {'lang': 'en'} REDACTOR_UPLOAD = 'uploads/' # .... In models.py from django.db import models from redactor.fields import RedactorTextField class Entry(models.Model): title = models.CharField(max_length=250, verbose_name=u'Title') short_text = RedactorTextField(verbose_name=u'Text')
has comment: http://stackoverflow.com/comment/86560111
type: Question
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: ImportError: cannot import name 'RedactorTextField'
score: 0
has answer: http://stackoverflow.com/a/49772614

http://stackoverflow.com/q/49852061
tagged with: kaggle
tagged with: keras
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86728427
type: Question
score: 0
has body: I am trying to classify, Identify(location) and segmentation of the LAS data(Drone data)like buildings, trees and roads using https://github.com/ternaus/kaggle_dstl_submission. When i ran the building prediction code (python make_prediction_cropped_buildings.py)I am facing below issue: Using TensorFlow backend. architecture_128_50_buildings_3_.json Traceback (most recent call last): File "make_prediction_cropped_buildings.py", line 26, in &lt;module&gt; model = read_model() File "make_prediction_cropped_buildings.py", line 21, in read_model model = model_from_json(open(os.path.join('../src/cache', json_name)).read()) File "/home/darshan/anaconda2/lib/python2.7/site-packages/keras/models.py", line 214, in model_from_json return layer_from_config(config, custom_objects=custom_objects) File "/home/darshan/anaconda2/lib/python2.7/site-packages/keras/utils/layer_utils.py", line 44, in layer_from_config custom_objects=custom_objects) File "/home/darshan/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 2597, in from_config process_layer(layer_data) File "/home/darshan/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 2593, in process_layer layer(input_tensors) File "/home/darshan/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 1470, in __call__ node_indices, tensor_indices) File "/home/darshan/anaconda2/lib/python2.7/site-packages/keras/engine/topology.py", line 1380, in _arguments_validation 'Layer shapes: %s' % (input_shapes)) ValueError: "concat" mode can only merge layers with matching output shapes except for the concat axis. Layer shapes: [(None, 1024, 14, 7), (None, 256, 14, 14)]
tagged with: python
has comment: http://stackoverflow.com/comment/86762193
has comment: http://stackoverflow.com/comment/86769201
has comment: http://stackoverflow.com/comment/86769267
tagged with: image-segmentation
answer count: 0
type: UnansweredQuestion
has title: ValueError: "concat" mode can only merge layers with matching output shapes except for the concat axis

http://stackoverflow.com/q/49787924
answer count: 1
tagged with: machine-learning
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49921758
has body: I am trying to find out how to determine the value of clip_norm when using clip_by_norm or clip_by_global_norm with Tensorboard. In Tensorflow, we can use the optimizer to compute_gradients to obtain the gradient and add it to the tf.summary.histogram. In Tensorboard, we can observe the range of the gradient in the DISTRIBUTIONS tab. Then we can determine the clip_value range when using clip_by_value. On the other hand, how shall I calculate/display the norm or global norm in Tensorboard so that I can determine the value of clip_norm?
tagged with: tensorboard
tagged with: python
has title: Tensorflow: How to determine the value of clip_norm when using clip_by_norm or clip_by_global_norm?
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49921758
upvote count: 3

http://stackoverflow.com/comment/86686684
has text: There are no obvious mistakes in your code. We can't help you without a [mcve].
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49835791
score: 0

http://stackoverflow.com/a/49807803
score: 4
type: Answer
answers question: http://stackoverflow.com/q/49805747
upvote count: 4
has comment: http://stackoverflow.com/comment/86630652
has body: Fill your null value with empty list , then using transform df.at[df.list_value.isnull().nonzero()[0][0],'list_value']=[] df.groupby('study_id').list_value.transform(lambda x : [list(set(x.sum()))]) Out[160]: 0 [b, c, a] 1 [b, c, a] 2 [b, c, a] 3 [b, e, d, z, a] 4 [b, e, d, z, a] 5 [b, e, d, z, a] Name: list_value, dtype: object
downvote count: 0

http://stackoverflow.com/q/49859822
linked to: http://stackoverflow.com/q/17560498
score: 0
tagged with: server
has body: I am trying to start a small server on a remote machine via exec_command. The problem is that it always terminates the server when the channel object is destroyed. My current attempt looks kind of like this: ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname='10.0.0.1',username='username',password='pw') transport = ssh_client.get_transport() channel_server = transport.open_session() channel_server.exec_command('/home/server/streamtest') I also tried it with ssh_client.exec_command directly with the same results. Halp plz
tagged with: python
tagged with: paramiko
type: Question
has comment: http://stackoverflow.com/comment/86771507
answer count: 0
has title: Start server via exec_command (Paramiko)
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/17560498
has comment: http://stackoverflow.com/comment/86757005
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/49833183
score: 0
has answer: http://stackoverflow.com/a/49833241
has body: I'm trying to filter using some fields in an array like: qs = Model.objects.all() fields_list = ['a', 'b', 'c'] for field in fields_list: filter = {field: 20} qs.filter(**filter) return qs This piece of code, works in shell but not in runtime. What am I doing wrong?
has comment: http://stackoverflow.com/comment/86681601
type: Question
has comment: http://stackoverflow.com/comment/86681546
type: UnansweredQuestion
answer count: 1
tagged with: django
tagged with: python
has title: Django filter using **kwargs
has comment: http://stackoverflow.com/comment/86681552

http://stackoverflow.com/comment/86757515
has text: Can you please add expected output.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49871101

http://stackoverflow.com/a/49776743
has comment: http://stackoverflow.com/comment/86569554
accepted answer of: http://stackoverflow.com/q/49776386
has body: This is one way. import pandas as pd from io import StringIO mystr = StringIO("""Record Time Value1 Value2 Value3 Event 1 20 35 40 Event 2 48 43 56 Event 3 45 58 90 FFC 4 12 89 94 FFC 5 30 25 60 Event 6 99 45 13""") # replace mystr with 'file.csv' df = pd.read_csv(mystr, delim_whitespace=True) # get index of condition idx = df[df['Record'] == 'FFC'].index[0] # filter for appropriate indices res1 = df.loc[idx] res2 = df.loc[idx-2] To output a dataframe: print(res1.to_frame().T) # Record Time Value1 Value2 Value3 # 3 FFC 4 12 89 94
type: Answer
has comment: http://stackoverflow.com/comment/86572791
has comment: http://stackoverflow.com/comment/86572873
has comment: http://stackoverflow.com/comment/86569870
has comment: http://stackoverflow.com/comment/86569707
has comment: http://stackoverflow.com/comment/86569981
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86569827
answers question: http://stackoverflow.com/q/49776386
has comment: http://stackoverflow.com/comment/86570126

http://stackoverflow.com/q/49793767
tagged with: python
has answer: http://stackoverflow.com/a/49793907
answer count: 2
score: 1
tagged with: mysql-python
has title: how to install mysql-python on windows 10
downvote count: 0
linked to: http://stackoverflow.com/q/38059732
has body: I need to install mysqldb for python on windows 10, I tried the below way but I got same error: Setup script exited with error: command 'cl.exe' failed: No such file or directory pip install mysqlclinet, easy_instal mysql-python Please help! error: command 'cl.exe' failed: No such file or directory E:\Python\Django-PyCharm\DjangoPyCharmWeb&gt;easy_install mysqlclient Searching for mysqlclient Reading https://pypi.python.org/simple/mysqlclient/ Downloading https://pypi.python.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.1 2.tar.gz#md5=dbf1716e2c01966afec0198d75ce7e69 Best match: mysqlclient 1.3.12 Processing mysqlclient-1.3.12.tar.gz Writing C:\Users\Hoshmand\AppData\Local\Temp\easy_install-4ln2fjka\mysqlclient-1.3.12\setup.cfg Running mysqlclient-1.3.12\setup.py -q bdist_egg --dist-dir C:\Users\me\AppData\Local\Temp\easy_install-4ln2fjka\mysqlclien t-1.3.12\egg-dist-tmp-aeu8iq_w error: Setup script exited with error: command 'cl.exe' failed: No such file or directory E:\Python\Django-PyCharm\DjangoPyCharmWeb&gt; C:\Users\me\Downloads\mysqlclient-1.3.12&gt;python setup.py build running build running build_py creating build creating build\lib.win32-3.6 copying _mysql_exceptions.py -&gt; build\lib.win32-3.6 creating build\lib.win32-3.6\MySQLdb copying MySQLdb\__init__.py -&gt; build\lib.win32-3.6\MySQLdb copying MySQLdb\compat.py -&gt; build\lib.win32-3.6\MySQLdb copying MySQLdb\connections.py -&gt; build\lib.win32-3.6\MySQLdb copying MySQLdb\converters.py -&gt; build\lib.win32-3.6\MySQLdb copying MySQLdb\cursors.py -&gt; build\lib.win32-3.6\MySQLdb copying MySQLdb\release.py -&gt; build\lib.win32-3.6\MySQLdb copying MySQLdb\times.py -&gt; build\lib.win32-3.6\MySQLdb creating build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\__init__.py -&gt; build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -&gt; build\lib.win32-3.6\MySQLdb\constants copying MySQLdb\constants\CR.py -&gt; build\lib…
tagged with: mysql
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/21440230
has answer: http://stackoverflow.com/a/49793919
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86601982
duplicate of: http://stackoverflow.com/q/21440230
tagged with: pip
tagged with: django

http://stackoverflow.com/a/49875086
answers question: http://stackoverflow.com/q/49871480
type: Answer
has body: I solved the problem by moving the data_while_loop variable inside the while loop after the map['x'] = i command. This basically overwrites every time data_while_loop is called and the latest value of map variable is passed to livy code.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49871480
score: 0

http://stackoverflow.com/comment/86645383
has text: @Kanguros I have traced the error back to the flag `--restrict-modify root` (my devpi server is running in a docker container which uses that flag by default). Removing that flag lets me to creates indexes. I was under the impression that `restrict-modify` only applies to user management, not to index management.
comment on: http://stackoverflow.com/q/49798330
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/86784270
type: QuestionComment
comment on: http://stackoverflow.com/q/49847299
score: 0
has text: The thing you are clicking on is just a table header, not an actual link (odd they used headers but not my site). This means it has to be using JavaScript in some way to start the download. Try using a debug mode to step through your script and see if there are any js errors preventing the download from starting.
type: Comment

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

http://stackoverflow.com/comment/86564993
has text: what files are there in root folder ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49775020

http://stackoverflow.com/a/62230885
has body: def grid(row, col): x = ('+----' * col + '+') y = ('\n' +'| ' * (col+1)) return ((x + 4*y) +'\n')*row + x print(grid(3,2)) Result : +----+----+ | | | | | | | | | | | | +----+----+ | | | | | | | | | | | | +----+----+ | | | | | | | | | | | | +----+----+
score: 0
answers question: http://stackoverflow.com/q/49876793
type: Answer

http://stackoverflow.com/comment/86551089
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49767904
has text: @Rakesh, sorry I just updated the question, can't use pandas. Please use the test data for suggesting solution. thanks

http://stackoverflow.com/comment/110999119
type: AnswerComment
comment on: http://stackoverflow.com/a/49769015
has text: @2540625 try running https://bootstrap.pypa.io/get-pip.py in your browser - does it return the py file?
type: Comment
score: 0

http://stackoverflow.com/comment/86575219
type: AnswerComment
comment on: http://stackoverflow.com/a/49779467
score: 0
type: Comment
has text: when I apply this and add a print statement at the end it prints out everything, how do I have it isolated to just the station ids?

http://stackoverflow.com/comment/86723769
has text: when the server says 401 something with the authentication is wrong. Wrong credentials, wrong encryption, wrong authentication type (server-side expects other as client sends). without further details i guess nobody can help you because it's too vague.
comment on: http://stackoverflow.com/q/49854048
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49883476
possible better answer: http://stackoverflow.com/a/49883635
upvote count: 0
has comment: http://stackoverflow.com/comment/86782977
has comment: http://stackoverflow.com/comment/86782992
has answer: http://stackoverflow.com/a/49883635
has title: How to input a list in list in Python?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86782975
tagged with: arrays
has comment: http://stackoverflow.com/comment/86783008
tagged with: python
downvote count: 5
accepted answer: http://stackoverflow.com/a/49883647
has body: I want to create a list in Python. That list contains N lists. Here, N == int(input()). Say, I want to create a list which again contains N list. N is the number of people and that sub_list will contain the people's name and age. I want to keep the data in this format: Sub_list = [name, age]. I want this sub list to be a part of the main list. So, basically it should look like this: main_list = [[name, age], [name, age], [name, age]...N]. But, I want to input() the name and age and also keep the [name, age] as a sub-list being a part of main list. How do I do that? I'm really sorry for asking such a silly question. I'm new to Python and programming as a whole. I tried to solve this problem on my own for while. But couldn't. So, I've decided to share this silly problem in StackOverflow. Sorry for inconvenience :'(
has answer: http://stackoverflow.com/a/49883647
type: AnsweredQuestion
tagged with: list
score: -5
answer count: 2

http://stackoverflow.com/a/49780202
has comment: http://stackoverflow.com/comment/86595555
downvote count: 0
score: 3
upvote count: 3
type: Answer
has body: As @ebeneditos mentioned, you need to change your activation function in the last layer to something other than sigmoid. You can try changing it to linear. model.add(Dense(1, init='uniform', activation='linear')) You should also change your loss function to something like mean squared error, as your problem is more of a regression problem than a classification problem (binary_crossentropy is used as a loss function for binary classification problems) model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
answers question: http://stackoverflow.com/q/49779836

http://stackoverflow.com/a/49798150
accepted answer of: http://stackoverflow.com/q/49798023
type: Answer
answers question: http://stackoverflow.com/q/49798023
has body: Pass exclude_replies as a kwarg. tweets = api.user_timeline(screen_name=username, count=number_of_tweets, exclude_replies=True) See Twitters API documentation for a full list of kwargs you can pass.
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49888370
type: Answer
has comment: http://stackoverflow.com/comment/86813576
score: 2
answers question: http://stackoverflow.com/q/49887782
has body: The only data the that you can scrap with Beuatifulsoup or other http request library is that are available on start without Javascirpt in action. It is same as doingcurl $URL, and parsing data. One way to approch to this problem would be using selenium webdriver and program same actions as user would have performed on browser. More information can be found Introduction to Web Scraping using Selenium Send keys control + click in Selenium with Python bindings Webscraping with Selenium
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49887782

http://stackoverflow.com/a/49808439
type: Answer
answers question: http://stackoverflow.com/q/49805746
downvote count: 1
has body: If you are permitted to use a 3rd party library, this can be done with numpy.rotate and setting k=-1 [i.e. 90% clockwise]: import numpy as np print(np.array(grid)) [['.' '.' '.' '.' '.' '.'] ['.' 'O' 'O' '.' '.' '.'] ['O' 'O' 'O' 'O' '.' '.'] ['O' 'O' 'O' 'O' 'O' '.'] ['.' 'O' 'O' 'O' 'O' 'O'] ['O' 'O' 'O' 'O' 'O' '.'] ['O' 'O' 'O' 'O' '.' '.'] ['.' 'O' 'O' '.' '.' '.'] ['.' '.' '.' '.' '.' '.']] for x in np.rot90(np.array(grid), k=-1): print(''.join(x)) ..OO.OO.. .OOOOOOO. .OOOOOOO. ..OOOOO.. ...OOO... ....O....
score: -1
upvote count: 0

http://stackoverflow.com/comment/86710477
type: QuestionComment
comment on: http://stackoverflow.com/q/49847771
has text: Is the code in the `for` not indented or is it only like that here in the question? What i'm trying to say is make sure the indentation in the question matches your code exactly. Also that's not how you loop over objects in python.
score: 1
type: Comment

http://stackoverflow.com/q/49838695
answer count: 2
has comment: http://stackoverflow.com/comment/86692361
tagged with: syntax
has answer: http://stackoverflow.com/a/49838744
tagged with: indentation
has comment: http://stackoverflow.com/comment/86692371
linked to: http://stackoverflow.com/q/1528903
has answer: http://stackoverflow.com/a/49838717
type: Question
duplicate of: http://stackoverflow.com/q/1528903
type: UnansweredQuestion
tagged with: python
has body: I'm writing a basic webscraping code, which basically will get the date and title of a post and, if the date >= a date stored in a SQL db and the title != from a title also stored in the DB, then do some stuff. I'm getting a syntax error when executing it. Here's the code: for i in web_results: py_newsdate = datetime.strptime(i.find('div', attrs={'class': "infoItem"}).find_all('p')[0].getText()[6:], '%d/%m/%Y') py_newstitle = i.find('h3').find('a')['title'] if (py_newsdate < sql_latest[0][0] or py_newstitle == sql_latest[0][1]): else: py_newslink = i.find('h3').find('a')['href'] web_results_final.append([py_newsdate, py_newstitle, py_newslink]) print(web_results_final) And here's the error: File "searcher", line 37 else: ^ IndentationError: expected an indented block I know the blocks have to be properly idented, but I'm thinking the problem may be on this "empty" if. Thanks.
has title: Python If With no commands followed by a Else Syntax error
score: 0

http://stackoverflow.com/q/49804510
type: Question
accepted answer: http://stackoverflow.com/a/49805064
answer count: 2
tagged with: tkinter
has title: Variables for each item in a list
has comment: http://stackoverflow.com/comment/86624619
has body: I have a list of variables named Weapons and I need to make radio buttons for each item in that list, in a weapon switching system. (Using Tkinter) I tried doing something like this initially: for item in Weapons: x = Radiobutton(equipped, text=item['name'], variable=player['weapon'], value=item) x.pack() But this failed because all the radio buttons had the same value. I don't know how many buttons will be needed because it is relative depending on the number of variables inside Weapons. How can I do this?
tagged with: variables
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86624443
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86623714
has answer: http://stackoverflow.com/a/49805064
has answer: http://stackoverflow.com/a/49804605
possible better answer: http://stackoverflow.com/a/49804605

http://stackoverflow.com/comment/86799546
has text: Yes, but thats again a nesting. You are filling a multi-dimension array into a single dimension column of pandas. Scikit wont handle that.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49872386

http://stackoverflow.com/comment/86721795
type: Comment
comment on: http://stackoverflow.com/a/49853525
has text: Maybe [that](https://www.odoo.com/de_DE/forum/hilfe-1/question/press-a-button-and-download-a-file-how-93037) will help you.
score: 0
type: AnswerComment

http://stackoverflow.com/q/49824504
has answer: http://stackoverflow.com/a/49825122
has comment: http://stackoverflow.com/comment/86665060
type: Question
tagged with: linux
has comment: http://stackoverflow.com/comment/86665171
has comment: http://stackoverflow.com/comment/86665045
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86665681
has comment: http://stackoverflow.com/comment/86668291
tagged with: python
has comment: http://stackoverflow.com/comment/86665626
tagged with: css
score: 0
has title: python find_element_by_css_selector(value) returns None
has body: Below represents the element tag from where I got the element by its CSS selector "#xwt_widget_navigation__slidemenu__SlideOutNavigationButton_1" Topology Problem is when I do a topo = driver.find_element_by_css_selector("xwt_widget_navigation__slidemenu__SlideOutNavigationButton_1") topo.click() This returns a None, no error or any sort.Am running this on a Linux cmd line and as such using the pyvirtualdisplay. When I do a screenshot it doesn't show that anything happened but when I do a debug using the pdb.set_trace() to step through the code it works. I have looked at the examples on StackOverflow and elsewhere but I couldn't find anything similar or helpful. Can someone tell me what am doing wrong?
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/86665589
answer count: 1
tagged with: selenium

http://stackoverflow.com/comment/86787442
comment on: http://stackoverflow.com/a/49885668
score: 0
has text: but if you go to the rssfeed link, there is an <image> tag under channel/item.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49890790
tagged with: tkinter
has answer: http://stackoverflow.com/a/49890972
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86797289
downvote count: 0
tagged with: button
score: 2
has body: I have multiple buttons in tkinter window, but on a computer we only have one mouse pointer at one location at a time, how can I multi-press buttons simultaneously just like on a touch screen? Here is a sample code of what I am trying to do, #!/usr/bin/python import Tkinter as Tk def button_pressed_cb(event): print("You pressed " + event.widget['text']) def button_release_cb(event): print("You released " + event.widget['text']) root = Tk.Tk() button1 = Tk.Button(root, text="button1") button1.pack() button2 = Tk.Button(root, text="button2") button2.pack() button1.bind("&lt;ButtonPress&gt;", button_pressed_cb) button1.bind("&lt;ButtonRelease&gt;", button_release_cb) button2.bind("&lt;ButtonPress&gt;", button_pressed_cb) button2.bind("&lt;ButtonRelease&gt;", button_release_cb) root.mainloop() After executing this, I get a sample output of something like this, You pressed button1 You released button1 You pressed button2 You released button2 What I want to achieve is to be able to generate events which occur in this sequence, You pressed button1 You pressed button2 You released button2 You released button1 Does anybody know what's the best way to achieve this? Thank you so much.
has answer: http://stackoverflow.com/a/49920002
has comment: http://stackoverflow.com/comment/86805511
tagged with: python
has title: How to press more than one tkinter button simultaneously using python
favorite count: 0
type: Question
upvote count: 2
answer count: 2

http://stackoverflow.com/comment/86622033
type: Comment
has text: @ScottBoston Thank you man, I even did not aware I am close to Legendary badge
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49803211

http://stackoverflow.com/a/49796908
has comment: http://stackoverflow.com/comment/86730644
accepted answer of: http://stackoverflow.com/q/49790564
type: Answer
has body: What the error message is telling is that the symbol .env in the R package, when translated to a syntactically valid name in Python (here the translation will be _env), is conflicting with an attribute of the object ttr you are creating when calling importr. You can see that attribute for objects of class Package here: https://rpy2.github.io/doc/v2.9.x/html/_modules/rpy2/robjects/packages.html#Package How to use the parameter robject_translationsis documented: https://rpy2.github.io/doc/v2.9.x/html/robjects_rpackages.html#importing-r-packages
answers question: http://stackoverflow.com/q/49790564
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86714926
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49888234
type: AnsweredQuestion
tagged with: python-2.7
answer count: 3
has body: reposting this questions with specifics (because the last one was flagged down). I am working on parsing messy (tessearct-ocr) from archives cards to get atleast 50% of the info (date1). The data rows contain dates in different forms as per data sample below. Raw_Text 1 "15957-8 . 3n v g - vw, 1 ekresta . bowker, william e tley n0 .qu v- l. c. s. peteris, forestville, n. y. .mafae date1 june 17,1942 by davis, c. j6 l. g. b. jonnis, buffalo, n. y. ngsted decl 17, 1949.3y 7 davis, c. j. date3 by j date4 - by date5 by 6 -.5/, 7/19/l date6 17 jul 1916 salamanca. hf date7 31 dec 1986 buffalo, new york " 2 ".1o2o83n5ddn.. -i ekresta i bowles, albert edwin i made date1 june 9p1909 by parker, elm. date2 dec . 18 w date3 . by dep osed by date5 by date7mqm 9 ivvld wm 4144, mac, .75 076 eaqlwli " 3 "i naime bowles, charles edward made date1 may 31. 1892 by mclaren, wneoi date2 may 18. 1895 by mclaren, w.e. date3 . i by date4 may 10. 1908 by bip. of chicago. date5 by date7 " 4 "101 557 am l i ekrestaibowles, donald manson ..46 ohio trlnlty cathedral, cleveland, ohio made date1 6/19/76 by burt, ji. h. grace , cleveland, ohio date2 11 jun 77 by bp j h burt date3 . 1 .. by date4 by date5 bv m cuyahoga heights, ohio date6 4/29/27 date7 240000 " 5 "227354 101 575 m68, frederick augustus st. paujjs cathedral, buffalo, n.y. made date1 6/15/63 by scaife. l.i... st. thomas. modia, bath, n.y. date2 1/11/611 by scaife. l.eo date3 by date4 by date5 by bradford, n.y. i . 130m 6/1/18 date7 17 jun 1996 foratvme new york z4uc-xl " 6 "1 95812d ll. il ekresta bowles, harry oscar lmade date14 july 17, 190433, lepnard, w.a. date2 july 25 , 1905 by leonard, w.a. i date3 by date4 by date5 by g- m. /(,,/mr date7 jay /z/,. /357i l /mwi yk/maj. " 7 "5025 ,.. 2.57631 il . - . .. .1 i ekresta bowles , jedwiah hibbafd made deac0n 8., i5-0i1862i13y potter, iih. date2 10. 280 1864 1 biy stevens, w. b. date3 by date4 7 .30 l 1875 by date5 by date7 " 8 "30.611126 ekhq il ekresta bowles, ralph hart made date1 …
has answer: http://stackoverflow.com/a/49890710
possible better answer: http://stackoverflow.com/a/49900767
downvote count: 0
has title: Parse Different Date formats: Regex
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49900767
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49890710
has answer: http://stackoverflow.com/a/49888409
tagged with: python
tagged with: date
tagged with: regex
tagged with: date-parsing

http://stackoverflow.com/comment/86721671
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49853525
type: AnswerComment
has text: I tried both removing the key and making the `target` to `current`. But then after loading,no file is being produced. How to autodowload that file when I clicks on that button ?

http://stackoverflow.com/q/49766939
has answer: http://stackoverflow.com/a/49767845
has title: Creating Custom varbinds dictionary using pysnmp
has body: I am using sendVarbinds from pysnmp to send traps with custom MIBs e.g. def sendTrap(self, trapName, trapObjects): mibViewController = view.MibViewController(self.snmpEngine.getMibBuilder()) ntfOrg = ntforg.NotificationOriginator() ntfOrg.snmpContext = self.snmpContext ntfOrg.sendVarBinds( self.snmpEngine, 'my-notification', # notification targets None, '', # contextEngineId, contextName rfc1902.NotificationType( trapName, objects=trapObjects # &lt;-- how to construct this? ).resolveWithMib(mibViewController) ) The NotificationType requires a dictionary of varbinds , having object key value pair . I would like to populate the object dictionary key and value from a json object .Right now I am doing it like this for each trap. def function1(): trapName = rfc1902.ObjectIdentity('MY-MIB', 'ServerPart') trapObjects = { ('MY-MIB', 'ServerIP'): event.get_ServerIP(), ('MY-MIB', 'ServerPartName'): event.get_ServerPartName(), ('MY-MIB', 'ServerState'): event.get_ServerState() } def function2(): trapName = rfc1902.ObjectIdentity('MY-MIB', 'ServerMemory') trapObjects = { ('MY-MIB', 'ServerIP'): event.get_ServerIP(), ('MY-MIB', 'ServerMemoryAv'): event.get_ServerMemoryAv() } But I want to have a single function to create the traps without checking the varbinds and fill them using the JSON object? Say I run a loop on dictionary items(). My flow is like this. Client --- event JSON object ----> Trap daemon ---- traps -----> Manager This is an example of the JSON object which comes from client my_event('ServerPart', '10.22.1.1', '44', '1', host, port) my_event('ServerMemory', '10.22.1.1', '100MB', host, port) Is there any example which can be followed?
tagged with: pysnmp
has answer: http://stackoverflow.com/a/49767650
type: Question
has comment: http://stackoverflow.com/comment/86550501
tagged with: snmp
answer count: 2
has comment: http://stackoverflow.com/comment/86550007
type: UnansweredQuestion
tagged with: python
score: 0

http://stackoverflow.com/q/49883227
downvote count: 1
has comment: http://stackoverflow.com/comment/86791454
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49884637
has comment: http://stackoverflow.com/comment/86782478
tagged with: python
has comment: http://stackoverflow.com/comment/86782741
tagged with: yield
has comment: http://stackoverflow.com/comment/86784864
linked to: http://stackoverflow.com/q/42184576
has answer: http://stackoverflow.com/a/49884637
has body: Bumped into a behaviour I'm struggling to grasp without an assistance. Here's a recursive function: OPERATORS = ['+', '-', '*', '/'] def recursive(value, operands): if not operands: return value for operator in OPERATORS: new_value = str(eval(value + operator + operands[-1])) new_operands = operands[:-1] yield from recursive(new_value, new_operands) def countdown(value, operands): return next(i for i in recursive(value, operands) if i == '0') ans = countdown('5', ['1', '2', '3']) print(ans) return value raises StopIteration which is not handled by caller so exception is raised before anything returns. If return value is substituted by yield value; return like this: def recursive(value, operands): if not operands: yield value return for operator in OPERATORS: new_value = str(eval(value + operator + operands[-1])) new_operands = operands[:-1] yield from recursive(new_value, new_operands) or yield value; raise StopIteration or yield value; raise StopIteration(value) or loop is hidden under else clause then exception is handled by caller the way I expect and function eventually returns '0'. All of these also raise exception: raise StopIteration, both bare and with argument, yield; return value, and bare return. In short, caller breaks when StopIteration is raised and yield never returned. Why? PEP380 states that first StopIteration is handled in a different way then others. PEP479 says: Currently, StopIteration raised accidentally inside a generator function will be interpreted as the end of the iteration by the loop construct driving the generator. Apparently, except the first time. Still, the details of underlying implementation and exact reasoning behind it are unclear to me. Two more additional questions: what's the right way of writing this snippet? return (yield value)? is it a quirk, a feature, or something else? Edit: fixed mistakes in code Edit2: As far as I understand the execution flow in the first snippet is following: countdown creates generator from recurs…
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/231767
has title: yield/return from python generators
has comment: http://stackoverflow.com/comment/86782730
has comment: http://stackoverflow.com/comment/86783147
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/86798130
comment on: http://stackoverflow.com/q/49891116
type: QuestionComment
has text: @MarkRansom I think he's intentionally doing the product, not the zip.
score: 0
type: Comment

routes
type: Tag
tags question: http://stackoverflow.com/q/49837511
tag name: routes

http://stackoverflow.com/q/49854722
has answer: http://stackoverflow.com/a/49855653
tagged with: pandas
type: UnansweredQuestion
has body: I am working with pandas dataframes and I want to get the coincidences between 2 dataframes, df1 and df2. df1: +------------+-------+ | features | col2 | +------------+-------+ | [1.0, 2.0] | 2 | +------------+-------+ | [1.0, 3.0] | 1 | +------------+-------+ df2: +------------+-------+ | features | col2 | +------------+-------+ | [1.0, 2.0] | 2 | +------------+-------+ | [1.0, 4.0] | 5 | +------------+-------+ Column 'features' is of type DenseVector. One of the columns (named 'features') of both dataframes are of type DenseVector. I have the next code: s1 = pandas.merge(df1, df2, how='inner', on=['features']) I checked that both dataframes have a DenseVector element with the same values. For example: DenseVector([1.0, 2.0, 3.0]). But no coincidences are captured by s1. If I check the next code in which the DenseVector element of df1 is in df2, I get False when I should get True: df1.features[0] in df2.features If I apply the next code, I get True, because it compares all the elements of the vector: df1.features[0].all() in df2.features.all() How can I apply the inner join in order to get the vectors that coincide?
has title: Inner join between pandas dataframes does not work with comparing DenseVector types
answer count: 1
tagged with: inner-join
has comment: http://stackoverflow.com/comment/86724742
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86723956
has comment: http://stackoverflow.com/comment/86724117
type: Question
score: 0

http://stackoverflow.com/comment/86681885
type: Comment
comment on: http://stackoverflow.com/a/49833292
score: 0
type: AnswerComment
has text: Is this the only way to do it or could it be implemented into the code (I plan to extend the code to consider when x1 is negative and if so redo the x1 calculation until its value is positive)

http://stackoverflow.com/q/49824886
has body: I need my func to print out the following: apples Alice dogs oranges Bob cats cherries Carol moose banana David goose all items are aligned to the right and I have solution but it's kinda workaround, could you please help me to correct my solution? tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printData(lst): colWidths = [0] * len(tableData) for a in range(len(tableData)): colWidths[a] = len(max(tableData[a], key=len)) for i in range(len(lst[0])): output = '' for j in range(len(lst)): output += (str(lst[j][i])).rjust(colWidths[0]) print(output) print(printData(tableData)) apples Alice dogs oranges Bob cats cherries Carol moose banana David goose
tagged with: nested-lists
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49825070
tagged with: python
linked to: http://stackoverflow.com/q/8234445
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49824936
duplicate of: http://stackoverflow.com/q/8234445
has title: How to right-justify elements in a list?
type: Question

http://stackoverflow.com/q/49806340
score: 2
type: AnsweredQuestion
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/58551220
has answer: http://stackoverflow.com/a/76179811
downvote count: 0
has answer: http://stackoverflow.com/a/58551220
favorite count: 0
type: Question
tagged with: python-3.x
has title: Pythonically exporting digital certificate information from a file
possible better answer: http://stackoverflow.com/a/76179811
has body: It is possible to somehow 'pythonically' export a file's digital certificate's subject if the certificate itself is not installed on the workstation but is only used on that specific file? I need to somehow extract that information from a file and check if it's correct. Preferably using Python/CMD/PowerShell I'm currently using this python script (which I modified to run on Python 3.6): http://www.zedwood.com/article/python-openssl-x509-parse-certificate to parse a .cer file that I extract from the original executable file. I extract the certificate with this little tool I've found (which I also modified to work with Python 3): https://blog.didierstevens.com/programs/disitool/ and afterwards I convert it from a DER-encoded binary to a base-64 with the Windows certutil. The problem with the disitool script I use to extract the certificate from the file, though, is that it literally cuts the 'signature' bytearray from the executable itself using the pefile python module, which makes the extracted .cer file invalid, as per the python error that I keep getting when trying to load the certificate with the OpenSSL.crypto module: [('asn1 encoding routines', 'asn1_check_tlen', 'wrong tag'), ('asn1 encoding routines', 'asn1_item_embed_d2i', 'nested asn1 error'), ('asn1 encoding routines', 'asn1_template_noexp_d2i', 'nested asn1 error'), ('PEM routines', 'PEM_ASN1_read_bio', 'ASN1 lib')] But parsing a good extracted certificate (with the first script I posted above) works, as you can see here: TL:DR - I just need a way to export a certificate from a file, I guess. Also, if you've found my solution too complicated, if you have any idea how I could get that "Redmond" text from the certificate's Subject field, I'm very open to other ideas :)
tagged with: python

http://stackoverflow.com/comment/86955755
comment on: http://stackoverflow.com/q/49916290
has text: It's likely that `module_dir = os.path.dirname(sys.modules[__name__].__file__)` in combination with `os.path.join(module_dir, 'praw.ini')` does not result in a loadable file path. As a result, the system-level `praw.ini` file isn't loading which has the base settings. A simple solution would be to copy that file into the directory that you execute your program from, that should resolve your issues.
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49785681
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86693502
has answer: http://stackoverflow.com/a/49839312
tagged with: pyspark
has title: Best effort retries in PySpark
tagged with: python
has body: Let's say I have an RDD that I need to map over a task that can fail rdd = sc.parallelize([1,2,3]) rdd.map(a_task_that_can_fail) Is there a way to set spark to run the task in best efforts basis. My desired behaviour is: Retry the task 5 times, if fails after 5 times, return None, if succeeds then return the result
tagged with: apache-spark

http://stackoverflow.com/comment/86664682
type: AnswerComment
comment on: http://stackoverflow.com/a/49823374
score: 0
type: Comment
has text: This is the most efficient approach, by far. However, your translation table should replace each punctuation char by whitespace, instead of None, to correctly deal with cases like "foo:bar" (without space around ':')

http://stackoverflow.com/q/49871737
type: Question
upvote count: 4
tagged with: tf-idf
answer count: 2
accepted answer: http://stackoverflow.com/a/49876334
possible better answer: http://stackoverflow.com/a/49873882
has answer: http://stackoverflow.com/a/49876334
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/49873882
tagged with: nlp
linked to: http://stackoverflow.com/q/10554052
type: AnsweredQuestion
score: 3
tagged with: sentiment-analysis
has body: I am relatively new to NLP &amp; Sentiment analysis, but I am enrolled in a Machine Learning class and am creating a Sentiment Analysis NLP that will read a financial article and determine whether or not the overall sentiment is good or bad. Currently, I have a dataset of about 2000 articles. I know that I need to implement the TF-IDF vector method to cast all the instances in the dataset to the same vector space. Also, I know that TF-IDF requires a "Vocabulary" and the size of this "Vocabulary" is the length of the vector, each vector representing an article. My question is, how do I determine this vocabulary? One method I have found is to implement pre-processing (get rid of stop words, noisy words, punctuation, etc.) and then use ALL words in EVERY article in the training set. From here you can remove the words that have very few instances (unimportant words) and remove the words that have too many instances (non-distinguishing words). However, in my opinion, the "Vocabulary" is still going to be quite large, hence, the vector size is going to be very large. Overall, this approach seems logical, but processing heavy. I feel that initially creating a "Vocabulary" containing all words in every article is going to be HUGE. And then iterating through every article to see how many times the words in the "Vocabulary" have occurred is going to require a lot of processing power. If I am using NLTK and scikit-learn, do I have anything to worry about? If so, is there a better way to create the vocabulary?
has comment: http://stackoverflow.com/comment/86760935
downvote count: 1
has title: NLP Sentiment Analysis using TF-IDF Vector Size
favorite count: 0

http://stackoverflow.com/comment/86735676
has text: Ok. So I downloaded PyGithub but I can't found anywhere anything about even a directory.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49859752
type: Comment

http://stackoverflow.com/q/49788836
has answer: http://stackoverflow.com/a/49789175
has title: How to infer type from datetime string in Python
possible better answer: http://stackoverflow.com/a/49788943
tagged with: datetime
tagged with: python
tagged with: date
has answer: http://stackoverflow.com/a/49788943
type: AnsweredQuestion
has body: I have a table for which I want to infer custom types for each column. Given a string, I want to distinguish whether it is a date, a time or a timestamp. For instance, for the given list: input_list = [ "4th Sep 2013", "95-04-04 23:33:05", "May 5th 1999", "03:00:00", "10-01-22", "12-12-25 05:48:01.0010"] I want an output that tells me (a list of strings) output_types = [ "date", "timestamp", "date", "time", "date", "timestamp"] I have tried using datetime, but since I can't be sure of the input format (especially for dates) it is hard to infer automatically the input type.
answer count: 2
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: timestamp
accepted answer: http://stackoverflow.com/a/49789175
tagged with: time

http://stackoverflow.com/a/49889844
type: Answer
has body: Just use the map transformation. The function passed as parameter in the map operation accepts a dict, you can execute any logic and return an updated or new dict. See the example in: https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-crawler-pyspark-transforms-map.html
upvote count: 1
answers question: http://stackoverflow.com/q/49870228
downvote count: 0
score: 1

http://stackoverflow.com/comment/88646603
type: AnswerComment
score: 0
has text: I had a similar problem: The debugger was looking for the node `"RNN/basic_rnn_cell/.../Adagrad"` which was actually in another namespace at `"rnn/basic_rnn_cell/.../Adagrad"`. The namespace "RNN" was created by me, "rnn" was created by tensorflow. I renamed my namespace to "rnn" and it worked. So another problem with capital letters. Thanks for pointing in the right direction!
type: Comment
comment on: http://stackoverflow.com/a/49917773

http://stackoverflow.com/q/49813645
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/49816396
downvote count: 1
favorite count: 0
type: Question
has body: import pandas as pd li = [{"employee_id":1,"project_handled": "pas"},{"employee_id":1,"project_handled": "asap"},{"employee_id":2,"project_handled": "trimm"},{"employee_id":2,"project_handled": "fat"}] df = pd.DataFrame(li) df.set_index("employee_id",inplace=True) print(df) gives: project_handled employee_id 1 pas 1 asap 2 trimm 2 fat What I want is, index values shouldn't be repeated when printing: project_handled employee_id 1 pas asap 2 trimm fat I want to serialise this and share as excel using DataFrame.to_excel api. And the requirement is index shouldn't repeat itself in the employee_id column.
has title: pandas DataFrame print index value only once
has answer: http://stackoverflow.com/a/49813726
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
score: 2
answer count: 2

http://stackoverflow.com/comment/86792561
type: Comment
type: QuestionComment
has text: @Relequestual, [issue on GitHub](https://github.com/Julian/jsonschema/issues/398)
comment on: http://stackoverflow.com/q/49835647
score: 0

http://stackoverflow.com/a/49869718
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49869613
answers question: http://stackoverflow.com/q/49869613
has body: Your code has the following errors: Login_Dialog refers to a .py file, it is not a class so you can not inherit it. Qt Designer only provide a design class that serves to fill a widget, it is not a widget. PyQt recommends creating a new widget and using the class provided by Qt Designer to fill it out. reject is a QDialog method so you could connect it directly that closes the window without using close() With all the above, your code should be as follows: import sys from PyQt5 import QtCore, QtGui, QtWidgets from Login_Dialog import Ui_loginDialog class ui(QtWidgets.QDialog, Ui_loginDialog): def __init__(self): super(ui, self).__init__() self.setupUi(self) self.cancel_pushButton.clicked.connect(self.reject) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) w = ui() w.show() sys.exit(app.exec_())
type: Answer
has comment: http://stackoverflow.com/comment/86755192
has comment: http://stackoverflow.com/comment/86755231
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/86792253
comment on: http://stackoverflow.com/a/49887297
type: AnswerComment
has text: Thank you so much! This solved my problem. And thanks for the note about `id`.
type: Comment
score: 0

http://stackoverflow.com/comment/86784439
comment on: http://stackoverflow.com/q/49884072
type: Comment
type: QuestionComment
has text: @chrisz It can be any number. The main condition is that a number indicates all transactions that fall in one group
score: 0

http://stackoverflow.com/q/49843439
has comment: http://stackoverflow.com/comment/86701653
accepted answer: http://stackoverflow.com/a/49843569
has comment: http://stackoverflow.com/comment/86701552
type: AnsweredQuestion
score: 2
has title: Add multithreading or asynchronous to web scrape
tagged with: threadpool
has body: What is the best way to implement multithreading to make a web scrape faster? Would using Pool be a good solution - if so where in my code would I implement it? import requests from multiprocessing import Pool with open('testing.txt', 'w') as outfile: results = [] for number in (4,8,5,7,3,10): url = requests.get('https://www.google.com/' + str(number)) response =(url) results.append(response.text) print(results) outfile.write("\n".join(results))
tagged with: python
has answer: http://stackoverflow.com/a/49843569
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/86701535
tagged with: multithreading
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/86788067
score: 0
has text: OK, it's parsing Postgres `jsonb` fields. I can work around this by casting them to `varchar` in my select, but I'd still think there's discussion to be had about getting `to_csv` to format lists and dicts as JSON (if this discussion has been had, I'd be curious as to the reasons against that functionality).
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49884725

http://stackoverflow.com/comment/86755047
score: 0
has text: @eyllanesc you code does increase the size of the picture nicely but it also increases the size of the dots that I draw by painter. That is a big problem.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49869767

http://stackoverflow.com/a/49841595
has comment: http://stackoverflow.com/comment/86715474
has body: Well basically if there is a settings.py configuration that specify whether to send errors to Sentry, you could create a different one for test environment and turn off sentry logging. I currently use a separate test_settings.py file where I remove sentry (and related) from the INSTALLED_APPS. It works well enough for us.
type: Answer
answers question: http://stackoverflow.com/q/49771711
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49771711
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49854326
upvote count: 2
has comment: http://stackoverflow.com/comment/86724126
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86723925
score: 2
accepted answer of: http://stackoverflow.com/q/49854221
has body: If you look at the implementation of getlist, you can see that it creates a new list each time it is called. Modifying the list won't alter the query dict. You can use setlist to set the key to the updated list. copy_GET = QueryDict('a=1&amp;a=2&amp;a=3', mutable=True) l = copy_GET.getlist('a') l.append(u'4') copy_GET.setlist('a', l)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49854221

http://stackoverflow.com/comment/86783558
type: AnswerComment
comment on: http://stackoverflow.com/a/49867240
score: 0
has text: When integrating your suggestion into my code (shown above) all that is shown in the .csv after conversion from .xlsx is a column of 4 dates. The .xlsx files has multiple columns with different data sets and dates, along with a header. My original code was able to convert everything over, even the dates, but with the trailing 0:00 which I don't want. Your code works, but it removes all my other data. Any suggestions. Thanks. @jpp
type: Comment

http://stackoverflow.com/a/49790059
accepted answer of: http://stackoverflow.com/q/49789827
type: Answer
has body: You have to use setScale(). Also when you use addPixmap() this returns the created QGraphicsPixmapItem. In addition, the scaling is a transformation so it has a transformation origin, by default it is (0, 0), but in this case a better option would be to place it in the center of the image. from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * class MyGraphicsView(QGraphicsView): def __init__(self): super(MyGraphicsView, self).__init__() scene = QGraphicsScene(self) self.m = QPixmap("exit.png") self.item = scene.addPixmap(self.m) self.item.setTransformOriginPoint(self.item.boundingRect().center()) self.setScene(scene) self.setCacheMode(QGraphicsView.CacheBackground) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) @pyqtSlot() def scale_pixmap(self): self.item.setScale(2*self.item.scale()) class Example(QMainWindow): def __init__(self): super(Example, self).__init__() centralWidget = QWidget() self.setCentralWidget(centralWidget) lay = QVBoxLayout(centralWidget) gv = MyGraphicsView() button = QPushButton("scale") lay.addWidget(gv) lay.addWidget(button) button.clicked.connect(gv.scale_pixmap) if __name__ == '__main__': import sys app = QApplication(sys.argv) w = Example() w.show() sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/86596466
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49789827
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/49820952
accepted answer of: http://stackoverflow.com/q/49820811
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49820811
has body: A fully-connected layer is a math operation that transforms an input tensor into an output tensor. The output tensor contains the values returned by the layer's activation function, which operates on the sum of the weighted values in the layer's input tensor. When you execute sess.run(fc_3), TensorFlow performs the transformations for the three layers and gives you the output tensor produced by the third layer.
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/49905997
has comment: http://stackoverflow.com/comment/86848561
has body: You can use tf.logging module like this: import numpy as np import tensorflow as tf old_v = tf.logging.get_verbosity() tf.logging.set_verbosity(tf.logging.ERROR) from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) train_data = mnist.train.images # Returns np.array train_labels = np.asarray(mnist.train.labels, dtype=np.int32) eval_data = mnist.test.images # Returns np.array eval_labels = np.asarray(mnist.test.labels, dtype=np.int32) tf.logging.set_verbosity(old_v)
has comment: http://stackoverflow.com/comment/86848153
has comment: http://stackoverflow.com/comment/86847834
type: Answer
score: 13
has comment: http://stackoverflow.com/comment/86868987
downvote count: 4
accepted answer of: http://stackoverflow.com/q/49901806
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49901806
upvote count: 17

http://stackoverflow.com/q/49816671
score: 1
tagged with: math
tagged with: probability
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49827079
favorite count: 0
type: Question
tagged with: python-3.x
has body: I made a function to evaluate the following problem experimentally, taken from a A Primer for the Mathematics of Financial Engineering. Problem: Let X be the number of times you must flip a fair coin until it lands heads. What are E[X] (expected value) and var(X) (variance)? Following the textbook solution, the following code yields the correct answer: from sympy import * k = symbols('k') Expected_Value = summation(k/2**k, (k, 1, oo)) # Both solutions work Variance = summation(k**2/2**k, (k, 1, oo)) - Expected_Value**2 To validate this answer, I decided to have a go at making a function to simulate this experiment. The following code is what I came up with. def coin_toss(toss, probability=[0.5, 0.5]): """Computes expected value and variance for coin toss experiment""" flips = [] # Collects total number of throws until heads appear per experiment. for _ in range(toss): # Simulate n flips number_flips=[] # Number of flips until heads is tossed while sum(number_flips) == 0: # Continue simulation while Tails are thrown number_flips.append(np.random.choice(2, p=probability)) # Append result to number_flips flips.append(len(number_flips)) #Append number of flips until lands heads to flips Expected_Value, Variance = np.mean(flips), np.var(flips) print('E[X]: {}'.format(Expected_Value), '\nvar[X]: {}'.format(Variance)) # Return expected value The run time if I simulate 1e6 experiments, using the following code is approximately 35.9 seconds. from timeit import Timer t1 = Timer("""coin_toss(1000000)""", """from __main__ import coin_toss""") print(t1.timeit(1)) In the interest of developing my understanding of Python, is this a particularly efficient/pythonic way of approaching a problem like this? How can I utilise existing libraries to improve efficiency/flow execution?
tagged with: python
has answer: http://stackoverflow.com/a/49827079
upvote count: 2
type: AnsweredQuestion
has title: Iteration performance
tagged with: coin-flipping

http://stackoverflow.com/comment/86664622
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49824349
has text: Hey sorry, I actually changed my question a bit. I want to enforce using "choices", which I didn't initially mention - any ideas on how to have that work?

http://stackoverflow.com/comment/86806117
score: 0
comment on: http://stackoverflow.com/q/49895321
type: Comment
has text: or `years = [y for y in words if y.isdigit() and int(y) in range(2000,2020)]`
type: QuestionComment

http://stackoverflow.com/a/49836544
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49834197
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49834197
has body: To find the minimum cost of 5 you must consider movement along the streets and avenues in all 4 possible directions: """ ave_crossing[i][j] is the cost of crossing from avenue i to avenue i+1 (or vice versa) on street j street_crossing[i][j] is the cost of crossing from street j to street j+1 (or vice versa) on avenue i """ def initialize(): f = open("test.txt", "r") streets = int(f.readline().strip()) aves = int(f.readline().strip()) ave_crossing = [] for x in range(streets + 1): ave_crossing.append([int(x) for x in f.readline().strip().split(" ")]) ave_crossing = rotate(ave_crossing) street_crossing = [] for y in range(aves + 1): street_crossing.append([int(x) for x in f.readline().strip().split(" ")]) return ave_crossing, street_crossing def printArray(arr): for x in arr: print(x) def rotate(arr): return list(zip(*arr)) def findPath(ave_crossing, street_crossing): num_aves, num_streets = len(street_crossing), len(ave_crossing[0]) dynArray = [[(ave + street) for street in range(num_streets)] for ave in range(num_aves)] printArray(dynArray) print("------------") queue = [(ave, street) for ave in range(num_aves) for street in range(num_streets)] for ave, street in queue: costs = [] # consider the cost of all ways of arriving at (ave, street) if (street &gt; 0): # start at (ave, street-1) and go to (ave, street) costs.append(dynArray[ave][street - 1] + street_crossing[ave][street - 1]) if (street &lt; num_streets - 1): # start at (ave, street+1) and go to (ave, street) costs.append(dynArray[ave][street + 1] + street_crossing[ave][street]) if (ave &gt; 0): # start at (ave-1, street) and go to (ave, street) costs.append(dynArray[ave - 1][street] + ave_crossing[ave - 1][street]) if (ave &lt; num_aves - 1): # start at (ave+1, street) and go to (ave, street) costs.append(dynArray[ave + 1][street] + ave_crossing[ave][street]) min_cost = min(costs, default=0) if (dynArray[ave][street] &gt; min_cost): dynArray[ave][street] = min_cost # propagate the change in dynArray by rec…

http://stackoverflow.com/comment/87003463
comment on: http://stackoverflow.com/a/49953725
has text: Try with `cp1252` as the encoding while opening the file
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49809084
score: 1
downvote count: 1
tagged with: google-cloud-dataproc
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49816016
accepted answer: http://stackoverflow.com/a/49812019
tagged with: python
tagged with: google-cloud-dataflow
has body: I have around 20TB of time series data stored in big query. The current pipeline I have is: raw data in big query => joins in big query to create more big query datasets => store them in buckets Then I download a subset of the files in the bucket: Work on interpolation/resampling of data using Python/SFrame, because some of the time series data have missing times and they are not evenly sampled. However, it takes a long time on a local PC, and I'm guessing it will take days to go through that 20TB of data. Since the data are already in buckets, I'm wondering what would the best Google tools for interpolation and resampling? After resampling and interpolation I might use Facebook's Prophet or Auto ARIMA to create some forecasts. But that would be done locally. There's a few services from Google that seems are like good options. Cloud DataFlow: I have no experience in Apache Beam, but it looks like the Python API with Apache Beam have missing functions compared to the Java version? I know how to write Java, but I'd like to use one programming language for this task. Cloud DataProc: I know how to write PySpark, but I don't really need any real time processing or stream processing, however spark has time series interpolation, so this might be the only option? Cloud Dataprep: Looks like a GUI for cleaning data, but it's in beta. Not sure if it can do time series resampling/interpolation. Does anyone have any idea which might best fit my use case? Thanks
has title: Google Cloud - What products for time series data cleaning?
upvote count: 2
possible better answer: http://stackoverflow.com/a/49816016
answer count: 2
tagged with: apache-spark
tagged with: google-cloud-platform
has answer: http://stackoverflow.com/a/49812019

http://stackoverflow.com/q/49784792
upvote count: 1
score: 1
answer count: 1
has title: Trying to replicate small C code in Python
has comment: http://stackoverflow.com/comment/86584998
has comment: http://stackoverflow.com/comment/86585076
has body: I'm trying to replicate some C code in python. Here is the C code. #include &lt;math.h&gt; double AttackerSuccessProbability(double q, int z) { double p = 1.0 - q; double lambda = z * (q / p); double sum = 1.0; int i, k; for (k = 0; k &lt;= z; k++) { double poisson = exp(-lambda); for (i = 1; i &lt;= k; i++) poisson *= lambda / i; sum -= poisson * (1 - pow(q / p, z - k)); } return sum; } The C code is just modelling this equation, taken from Bitcoin's whitepaper Here is my attempt in python. def BitcoinAttackerSuccessProbablity(q, z): # probablity of honest finding the next node is 1 - probablity the attacker will find the next p = 1 - q # lambda is equal to the number of blocks times by the division of attacker and honest finding the next block lam = z * (q / p) sum = 1.0 i = 1 k = 0 while k &lt;= z: poisson = math.exp(-1 * lam) while i &lt;= k: poisson = poisson * (lam / i) i = i + 1 sum = sum - (poisson * (1 - ((q / p) ** (z - k)))) k = k + 1 print(sum) for x in range(0,11): BitcoinAttackerSuccessProbablity(0.1, x) The results from the C code are. (q and z are inputs while P is an output.) q=0.1 z=0 P=1.0000000 z=1 P=0.2045873 z=2 P=0.0509779 z=3 P=0.0131722 z=4 P=0.0034552 z=5 P=0.0009137 z=6 P=0.0002428 z=7 P=0.0000647 z=8 P=0.0000173 z=9 P=0.0000046 z=10 P=0.0000012 I am trying to replicate these results accurately in python by converting the C code. My first 3 results (z=0,-3) are correct, however, the remaining results are incorrect. When I changed my while loop to the equivalent in C only the first two results where correct. The results from my Python code 1.0 0.20458727394278242 0.05097789283933862 -0.057596282822218514 -0.1508215598462347 -0.22737700216279746 -0.28610012088884856 -0.3272432217416562 -0.3519591169464781 -0.36186779773540745 -0.35878211836275675 I think it's something simple on how loops are handled between languages. Any help would be much appreciated edit: Here is the first attempt def BitcoinAttackerSuccessProbablity(q, z): # probablity …
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86585151
has answer: http://stackoverflow.com/a/49784877
accepted answer: http://stackoverflow.com/a/49784877
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/86686860
comment on: http://stackoverflow.com/q/49835797
score: 0
type: Comment
has text: The python stack trace shows the exact line with the problem. Even if the example is kinda big, it lets us find the bad line and look nearby for the problem. So post the full error!
type: QuestionComment

http://stackoverflow.com/comment/86717330
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49851349
has text: Try `r'(?:(?<=[.!?])|(?<=[.!?]"))\s+'`

http://stackoverflow.com/a/49855687
downvote count: 0
has comment: http://stackoverflow.com/comment/86731605
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86740793
has comment: http://stackoverflow.com/comment/86725994
has comment: http://stackoverflow.com/comment/86730880
has body: def initiate_connection(self): """ Builds the connection between the client and server Runs through a loop which means it can try to connect again and again after failure """ print("Initiating Connection...") # Opens a socket and connects to the client server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((self.ip, self.port)) server_socket.listen(1) client_socket, address = server_socket.accept() # Entering a loop in order to be able to keep getting requests while True: print("Destination Address: " + str(address)) request = self.get_request(client_socket) print(str(request)) # Checks weither whether the request contains a string (url) if request: request = ROOT_PATH + os.path.sep + \ request.replace("/", os.path.sep) response = self.send_response(request) print("trying to send response to client") try: client_socket.send(response) except: print("An error has occurred while sending the response to\ the client") # In case the request is invalid or empty else: if request == 0: try: client_socket.send(self.internal_server_error.encode()) except: print("An error has occurred while sending the response\to the client") break else: break # Closing connection client_socket.close() print("Closing connection...") try: client_socket, address = server_socket.accept() except: print("An error has occurred when trying to initiate connection") break Try this for initiate_connection function. You were closing client connection right after you accept it and then trying to read from it.
type: Answer
accepted answer of: http://stackoverflow.com/q/49854824
has comment: http://stackoverflow.com/comment/86756190
answers question: http://stackoverflow.com/q/49854824

http://stackoverflow.com/comment/86744806
has text: @Chandan did you wait after you added the localhost uri to the google settings? it takes some time before it is processed by google.
comment on: http://stackoverflow.com/a/49861538
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49783902
linked to: http://stackoverflow.com/q/394809
score: 6
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/394809
has title: Python ternary execution order
possible better answer: http://stackoverflow.com/a/49783960
accepted answer: http://stackoverflow.com/a/49783972
downvote count: 1
has answer: http://stackoverflow.com/a/49783972
has body: In python, if I use a ternary operator: x = a if &lt;condition&gt; else b Is a executed even if condition is false? Or does condition evaluate first and then goes to either a or b depending on the result?
has answer: http://stackoverflow.com/a/49783960
favorite count: 0
has comment: http://stackoverflow.com/comment/86583282
type: Question
answer count: 2
tagged with: python
upvote count: 7

http://stackoverflow.com/comment/86746796
has text: I made an edit based on what you and others have suggested, I still get an incorrect output
comment on: http://stackoverflow.com/a/49865728
type: Comment
score: 0
type: AnswerComment

raspberry-pi
tags question: http://stackoverflow.com/q/49813003
type: Tag
tags question: http://stackoverflow.com/q/49800452
tags question: http://stackoverflow.com/q/49878789
tags question: http://stackoverflow.com/q/49802679
tags question: http://stackoverflow.com/q/49787761
tags question: http://stackoverflow.com/q/49858937
tags question: http://stackoverflow.com/q/49787275
tags question: http://stackoverflow.com/q/49796818
tags question: http://stackoverflow.com/q/49855638
tags question: http://stackoverflow.com/q/49830413
tag name: raspberry-pi
tags question: http://stackoverflow.com/q/49784551
tags question: http://stackoverflow.com/q/49874904
tags question: http://stackoverflow.com/q/49842901
tags question: http://stackoverflow.com/q/49803018
tags question: http://stackoverflow.com/q/49833654
tags question: http://stackoverflow.com/q/49766192

http://stackoverflow.com/q/49902780
score: 0
has comment: http://stackoverflow.com/comment/86834252
has body: Using Keras DL library with Tensorflow backend, I'm trying to implement a batch and validation generator for sentiment analysis with the built-in IMDB dataset. The dataset contains 25000 training samples and 25000 testing samples. Because setting a cut-off for number of words per sample yields a fairly low accuracy, I'm trying to batch the training and testing samples so that the memory load isn't terrible. Current code: from __future__ import print_function from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Embedding, Dropout from keras.layers import LSTM, TimeDistributed from keras.datasets import imdb from keras.callbacks import EarlyStopping, ModelCheckpoint import numpy as np max_features = 20000 def generate_batch(batchsize): ''' ''' (x_train, y_train), (_,_) = imdb.load_data() for i in range(0, len(x_train), batchsize): x_batch = x_train[i:(i+batchsize)] y_batch = y_train[i:(i+batchsize)] x_batch = sequence.pad_sequences(x_train, maxlen=None) yield(x_batch, y_batch) def generate_val(valsize): ''' ''' (_,_), (x_test, y_test) = imdb.load_data() for i in range(0, len(x_test), valsize): x_val = x_test[i:(i+valsize)] y_val = y_test[i:(i+valsize)] x_val = sequence.pad_sequences(x_test, maxlen=None) yield(x_val, y_val) print('Build model...') primary_model = Sequential() primary_model.add(Embedding(input_dim = max_features, output_dim = max_features, trainable=False, weights=[(np.eye(max_features,max_features))], mask_zero=True)) primary_model.add(TimeDistributed(Dense(150, use_bias=False))) primary_model.add(LSTM(128)) primary_model.add(Dense(2, activation='softmax')) primary_model.summary() primary_model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) print('Train...') filepath = "primeweights-{epoch:02d}-{val_acc:.2f}.hdf5" checkpoint = ModelCheckpoint(filepath, verbose=1, save_best_only=True) early_stopping_monitor = EarlyStopping(patience=2) primary_model.fit_gener…
answer count: 1
has title: Keras TF: ValueError: Input arrays should have the same number of samples as target arrays
tagged with: keras
tagged with: tensorflow
type: Question
tagged with: imdb
tagged with: python
accepted answer: http://stackoverflow.com/a/49913578
tagged with: generator
has answer: http://stackoverflow.com/a/49913578
type: AnsweredQuestion

http://stackoverflow.com/a/49807188
answers question: http://stackoverflow.com/q/49807032
has comment: http://stackoverflow.com/comment/86630049
has comment: http://stackoverflow.com/comment/86629778
has comment: http://stackoverflow.com/comment/86629467
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Replace the line with this: if health &lt; 100 and health &gt;= 10: (you need a value on each side of a comparison)
accepted answer of: http://stackoverflow.com/q/49807032
upvote count: 1

http://stackoverflow.com/comment/86781521
has text: Have you successfully tested running exec_command() with a simple Python file (e.g., a file that doesn't import any modules)?
score: 0
comment on: http://stackoverflow.com/q/49882737
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49783145
has comment: http://stackoverflow.com/comment/86581574
has body: stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} def displayInventory(inventory): print("Inventory:") item_total = 0 for k, v in inventory.items(): print(str(v) + " " + k) item_total += v print("Total number of items: " + str(item_total) + '\n') displayInventory(stuff) dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = {'gold coin': 42, 'rope': 1} def addToInventory(ram, addedItems): for itemindex in addedItems: if itemindex not in ram: ram[itemindex] = 0 ram[itemindex] = ram[itemindex] + 1 dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] inv = addToInventory(inv, dragonLoot) displayInventory(inv) when I do this it returns an error like this ... Inventory: 1 rope 6 torch 1 dagger 12 arrow Total number of items: 62 Inventory: Traceback (most recent call last): File "python", line 33, in &lt;module&gt; File "python", line 8, in displayInventory AttributeError: 'NoneType' object has no attribute 'items' this doesn't make sense, considering the fact that when you change the inv to 'abc' or anything other than inv the error goes away and the code runs smoothly.
has title: when adding items into a dictionary from an array I get an error?? PYTHON 3.x
answer count: 1
has answer: http://stackoverflow.com/a/49783313
has comment: http://stackoverflow.com/comment/86581604
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: for-loop
type: UnansweredQuestion
score: -4
tagged with: arrays
downvote count: 5
upvote count: 1
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/49800525
has comment: http://stackoverflow.com/comment/86615886
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86615883
accepted answer: http://stackoverflow.com/a/49800936
has comment: http://stackoverflow.com/comment/86616293
has answer: http://stackoverflow.com/a/49800936
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86616071
favorite count: 0
type: AnsweredQuestion
has title: Loop and write to a CSV file?
score: 1
has body: I am trying to loop through a XML file, and parse out the elements that I need. I can print to the console window just fine, but the results are too large, and fill the entire console before before it ends. So, I am trying to dump everything to a CSV file. Now, it seems like I get only one single character per row in the CSV when the script finishes. My code must be close, but obviously something is wrong. import xml.etree.ElementTree as ET import csv tree = ET.parse('C:\\path\\Recon.xml') root = tree.getroot() with open('C:\\path\\data.csv', 'w') as f: for neighbor in root.iter('inputColumn'): print(neighbor.attrib) writer = csv.writer(f) writer.writerows(neighbor.attrib) I am using 3.6.3! Just posting the final version of my code here.... import xml.etree.ElementTree as ET import csv tree = ET.parse('C:\\path\\Recon.xml') root = tree.getroot() with open('C:\\path\\data.csv', 'w') as f: writer = csv.writer(f) for neighbor in root.iter('inputColumn'): print(neighbor.attrib) writer.writerow(neighbor.attrib) This is so, so, so simple. After working with Python for a few years, and (basically) hating it, I am really starting to love it now!!

http://stackoverflow.com/a/49916748
has comment: http://stackoverflow.com/comment/86849440
answers question: http://stackoverflow.com/q/49916412
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86848979
has comment: http://stackoverflow.com/comment/86848942
score: 5
has body: This is one way. Note, as demonstrated below, you do not need to use nested dictionaries or a defaultdict for your initial step. from collections import defaultdict d1 = {} d2 = {} d1['id001'] = ['author1', 'author2'] d1['id002'] = ['author3'] d1['id003'] = ['author1', 'author4'] d2['id001'] = ['term1', 'term2'] d2['id002'] = ['term2', 'term3'] d2['id003'] = ['term4'] res = defaultdict(list) for ids in set(d1) &amp; set(d2): for v in d1[ids]: res[v].extend(d2[ids]) res = {k: sorted(v) for k, v in res.items()} # {'author1': ['term1', 'term2', 'term4'], # 'author2': ['term1', 'term2'], # 'author3': ['term2', 'term3'], # 'author4': ['term4']}
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/49916412
has comment: http://stackoverflow.com/comment/86849325

http://stackoverflow.com/a/53205990
has body: For Python version 2.7 @Anthony solution works perfect, by changing python3 to python as follows: sudo python -m pip uninstall pip &amp;&amp; sudo apt install python-pip --reinstall
type: Answer
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49836676

http://stackoverflow.com/comment/86643598
score: 0
has text: Thanks for the answer. The SQL will work only if my MYSQL server is running on the same server as the script. But, my MYSQL DB is a cloud-managed one like of AWS. There this SQL won't do the work. What are your suggestions?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49814081

http://stackoverflow.com/comment/86755940
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49867759
score: 0
has text: What information does `/var/log/cloud-init-output.log` contain?

http://stackoverflow.com/a/49772507
answers question: http://stackoverflow.com/q/49771589
has body: One way you can do it is through the Integrated Terminal. Here is the guide to open/use it: https://code.visualstudio.com/docs/editor/integrated-terminal After that, type python3 or python since it is depending on what version you are using. Then, copy and paste the fraction of code you want to run into the terminal. It now has the same functionality as the console in Spyder. Hope this helps.
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/49791845
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49792193
score: 0
has title: Check type of a database field - python
has comment: http://stackoverflow.com/comment/86598772
has answer: http://stackoverflow.com/a/49792381
type: Question
tagged with: python-3.x
answer count: 2
tagged with: casting
has comment: http://stackoverflow.com/comment/86598828
type: UnansweredQuestion
tagged with: django
upvote count: 1
has body: I've a Django model which contains settings, so each element of the model is a setting and the possible fields are setting_name, setting_value, setting_type and so on. For example, if I have a setting named version where the possible values are integers (like 1,2,3), the fields in the database are the following: setting_name = "version" setting_value = "2" setting_type = "int" What I need to do is check if the value and the type of the settings are consistency between them. With integers fields is not a problem because I'm able to cast the value to Int in order to check that. But what about float and str? In the first case (Float) I don't want the automatically conversion in case the field contains an int (i.e "5" -> 5.0) For the string, instead, the "cast approach" is not possible, because the field is always a string from database. Any suggestions? I'm using Python 3.5 and Django 1.11 Thank you in advance
tagged with: python

http://stackoverflow.com/comment/86681196
comment on: http://stackoverflow.com/q/49832548
score: 0
type: QuestionComment
has text: Okay, so i was able to fill all the blank cells with 0 and changed to pd.read_csv but i received the same error
type: Comment

selenium
tags question: http://stackoverflow.com/q/49866879
tags question: http://stackoverflow.com/q/49810087
tags question: http://stackoverflow.com/q/49844650
tags question: http://stackoverflow.com/q/49786276
tags question: http://stackoverflow.com/q/49796818
tags question: http://stackoverflow.com/q/49851889
tags question: http://stackoverflow.com/q/49863598
tags question: http://stackoverflow.com/q/49891815
tags question: http://stackoverflow.com/q/49891688
tags question: http://stackoverflow.com/q/49853252
tags question: http://stackoverflow.com/q/49905530
tags question: http://stackoverflow.com/q/49848571
tags question: http://stackoverflow.com/q/49816140
tags question: http://stackoverflow.com/q/49809492
tags question: http://stackoverflow.com/q/49765956
tags question: http://stackoverflow.com/q/49838284
tags question: http://stackoverflow.com/q/49904109
tags question: http://stackoverflow.com/q/49788994
tags question: http://stackoverflow.com/q/49889898
tags question: http://stackoverflow.com/q/49872426
tags question: http://stackoverflow.com/q/49826277
tags question: http://stackoverflow.com/q/49859370
tags question: http://stackoverflow.com/q/49908601
tags question: http://stackoverflow.com/q/49814645
tags question: http://stackoverflow.com/q/49906237
tags question: http://stackoverflow.com/q/49829466
tags question: http://stackoverflow.com/q/49883992
tags question: http://stackoverflow.com/q/49819853
tags question: http://stackoverflow.com/q/49912262
tags question: http://stackoverflow.com/q/49786487
tags question: http://stackoverflow.com/q/49869496
tags question: http://stackoverflow.com/q/49799160
tags question: http://stackoverflow.com/q/49764995
tags question: http://stackoverflow.com/q/49782514
tags question: http://stackoverflow.com/q/49812468
tags question: http://stackoverflow.com/q/49885701
tags question: http://stackoverflow.com/q/49816948
tags question: http://stackoverflow.com/q/49846350
tags question: http://stackoverflow.com/q/49890227
tags question: http://stackoverflow.com/q/49792722
tags question: http://stackoverflow.com/q/49765233
tags question: http://stackoverflow.com/q/49764902
tags question: http://stackoverflow.com/q/49855782
tags question: http://stackoverflow.com/q/49871680
tags question: http://stackoverflow.com/q/49880846
tags question: http://stackoverflow.com/q/49766461
tags question: http://stackoverflow.com/q/49760096
tags question: http://stackoverflow.com/q/49885773
tags question: http://stackoverflow.com/q/49806074
tags question: http://stackoverflow.com/q/49847029
tags question: http://stackoverflow.com/q/49834241
tags question: http://stackoverflow.com/q/49847299
tags question: http://stackoverflow.com/q/49898398
tags question: http://stackoverflow.com/q/49894823
tags question: http://stackoverflow.com/q/49846883
tags question: http://stackoverflow.com/q/49837963
tags question: http://stackoverflow.com/q/49786254
tags question: http://stackoverflow.com/q/49787327
tags question: http://stackoverflow.com/q/49848175
type: Tag
tags question: http://stackoverflow.com/q/49872824
tags question: http://stackoverflow.com/q/49762733
tags question: http://stackoverflow.com/q/49897030
tags question: http://stackoverflow.com/q/49833458
tags question: http://stackoverflow.com/q/49812866
tags question: http://stackoverflow.com/q/49801117
tag name: selenium
tags question: http://stackoverflow.com/q/49796431
tags question: http://stackoverflow.com/q/49823526
tags question: http://stackoverflow.com/q/49905232
tags question: http://stackoverflow.com/q/49778017
tags question: http://stackoverflow.com/q/49912393
tags question: http://stackoverflow.com/q/49900117
tags question: http://stackoverflow.com/q/49893655
tags question: http://stackoverflow.com/q/49775502
tags question: http://stackoverflow.com/q/49867912
tags question: http://stackoverflow.com/q/49907654
tags question: http://stackoverflow.com/q/49783884
tags question: http://stackoverflow.com/q/49824504
tags question: http://stackoverflow.com/q/49899423

http://stackoverflow.com/q/49874999
has comment: http://stackoverflow.com/comment/86765681
has comment: http://stackoverflow.com/comment/86765650
duplicate of: http://stackoverflow.com/q/240178
score: 0
has body: m,n=input().split( ) a=[[0]*int(n)]*int(m) for i in range(0,int(m)): s=input().split() for j in range(0,int(n)): a[i][j]=int(s[j]) print(a) I wanted to input this info for creating a 2D list: 3 4 11 12 13 14 21 22 23 24 31 32 33 34 however, the result is: 31 32 33 34 31 32 33 34 31 32 33 34
has comment: http://stackoverflow.com/comment/86765558
has comment: http://stackoverflow.com/comment/86765450
has comment: http://stackoverflow.com/comment/86765744
tagged with: python
has comment: http://stackoverflow.com/comment/86804085
has title: Why this 2D list input take the last input as the elements in all of the rows?
type: Question
linked to: http://stackoverflow.com/q/240178
tagged with: list
answer count: 0
type: UnansweredQuestion

onclick
tags question: http://stackoverflow.com/q/49838179
tag name: onclick
type: Tag

http://stackoverflow.com/comment/86542898
has text: A `Selector` isn't a string, it's a thing you can use to select substrings out of the raw data. So I'm not sure what you want `re.findall(…, sel)` to do. If you want to select the entire input, you can do that via `sel.extract()`, but that's kind of pointless; it's easier to just pass the whole string than to select the whole string and pass the result. If you want it to do something different, you need to explain what you actually want to do.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49763597

http://stackoverflow.com/a/49806536
score: 3
accepted answer of: http://stackoverflow.com/q/49805647
answers question: http://stackoverflow.com/q/49805647
has body: The function scipy.cluster.vq.vq does what you want. Here's a modified version of your code that demonstrates vq: import numpy as np from scipy.cluster.vq import vq import matplotlib.pyplot as plt # `points1` is the set A described in the question. points1 = np.array([(x, y) for x in np.linspace(-1,1,3) for y in np.linspace(-1,1,3)]) # `points2` is the set B. In this example, there are 5 points in B. N = 5 np.random.seed(1357924) points2 = 2*np.random.rand(N, 2) - 1 # For each point in points1, find the closest point in points2: code, dist = vq(points1, points2) plt.plot(points1[:,0], points1[:,1], 'b*') plt.plot(points2[:,0], points2[:,1], 'rh') for i, j in enumerate(code): plt.plot([points1[i,0], points2[j,0]], [points1[i,1], points2[j,1]], 'k', alpha=0.4) plt.grid(True, alpha=0.25) plt.axis('equal') plt.show() The script produces the following plot:
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3

http://stackoverflow.com/comment/86840116
score: 0
has text: Fair enough. You got me there.
type: Comment
comment on: http://stackoverflow.com/q/49912069
type: QuestionComment

http://stackoverflow.com/comment/86719876
score: 0
comment on: http://stackoverflow.com/a/49842849
type: Comment
has text: Its very similar to what I did in my offered solution and still requires code duplication. I actually managed to design a solution with zero code duplication and a strict object oriented approach ill post it later and would be glad if you could look at it.
type: AnswerComment

http://stackoverflow.com/comment/86701403
comment on: http://stackoverflow.com/q/49842999
score: 0
has text: Sorry, I can't understand: what you mean by "not putting them in there"? Putting who and where?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86654394
score: 0
has text: i tried passing [(xmin,ymi),(xmax,ymax)] but didnt work either
type: Comment
comment on: http://stackoverflow.com/a/49819639
type: AnswerComment

http://stackoverflow.com/a/49834955
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49834916
downvote count: 0
has comment: http://stackoverflow.com/comment/86808187
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49834916
has comment: http://stackoverflow.com/comment/86810461
has comment: http://stackoverflow.com/comment/86685050
has comment: http://stackoverflow.com/comment/86737533
type: Answer
has body: You can use pandas.concat to concatenate dataframes: import pandas as pd urls = ['http://www.url1.com', 'http://www.url2.com', 'http://www.url3.com'] df = pd.concat([pd.concat(pd.read_html(url, header=0), axis=0) for url in urls], axis=0) df.to_csv('file.csv') Explanation pd.concat concatenates a list of dataframes. pd.read_html returns a list of dataframes. Therefore, to concatenates a list of lists of dataframes, i.e. a list of pd.read_html output, you need to use nested pd.concat.
has comment: http://stackoverflow.com/comment/86738676

http://stackoverflow.com/comment/86753736
type: AnswerComment
comment on: http://stackoverflow.com/a/49869132
has text: @RexRichards the NULL here should be a string with the sql statement, not a variable, so it should be like: `"INSERT INTO BREAD (BID, BName, BCal, BPrice) VALUES (NULL, :BName,:BCal,:BPrice)", {'Name', 'Price', 'Calories'}`.
type: Comment
score: 0

http://stackoverflow.com/comment/86549127
has text: Thanks, I tried rgb_transform = np.concatenate([R,G,B], axis=0, out=None) and turns out working. But my problem is not address, I want to merge, not concantenate.
comment on: http://stackoverflow.com/a/49766758
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86741820
type: Comment
has text: I just tried to show you an example how you can pass a variable to html template.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49863024

http://stackoverflow.com/a/49850122
downvote count: 0
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49850047
has body: Qt does not allow the GUI to be updated from another thread directly, a possible solution is to use signals but for this we need a class that inherits QObject, on the other hand it is not recommended to modify the class generated by Qt Designer, that class only serves to fill in the widget So you could take advantage of creating a class that inherits from the widget, and since it is a widget also inherits from QObject, in that class we will create a signal, and connect that signal to the setText() method of the button. class Ui_Form(object): def setupUi(self, Form): # Code has been shortened self.Button.setFont(font) self.Button.setCursor(QtGui.QCursor(QtCore.Qt.ForbiddenCursor)) self.Button.setObjectName("Button") class Form(QtWidgets.QWidget, Ui_Form): someSignal = QtCore.pyqtSignal(str) def __init__(self, *args, **kwargs): QtWidgets.QWidget.__init__(self, *args, **kwargs) self.setupUi(self) t = threading.Thread(target=self.tryingMethod) self.someSignal.connect(self.Button.setText) t.start() def tryingMethod(self): self.someSignal.emit("TESTING") ##This doesn't work. while True: message = self.clientSocket.receive() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) w = Form() w.show() sys.exit(app.exec_())
answers question: http://stackoverflow.com/q/49850047
type: AcceptedAnswer

http://stackoverflow.com/a/49846439
has comment: http://stackoverflow.com/comment/86707893
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86708268
answers question: http://stackoverflow.com/q/49846374
has comment: http://stackoverflow.com/comment/86707989
has comment: http://stackoverflow.com/comment/86708379
has comment: http://stackoverflow.com/comment/86708289
has comment: http://stackoverflow.com/comment/86707900
has comment: http://stackoverflow.com/comment/86708454
has body: Simply place the \r at the end of your write statement like so: sys.stdout.write( "{:2d} seconds remaining to read last {:2d} minutes of data and perform prediction .....\r".format(remaining, time_to_go_back_mns)) New data will then overwrite the line, you can use flush() to clear the line before writing to it again: sys.stdout.flush() Make sure that on the terminator side of things your profile settings are clean. Be sure to check out the compatibility tab as it mentions weird application behaviour. note that carriage return stops functioning if the terminal size is too small. It will only return to the first character of the LAST line Original answer \r actually means "carriage return" whereas \n is a line feed. In Linux (Unix) you'd usually use either a \n or \r\n. So if your goal is to go to a new line you should use \n instead. The reason it might work in the "terminal" (whichever one that might be) is because some terminals (notably gnome's terminal) catches the \r and treats it as a \r\n.
type: Answer

http://stackoverflow.com/comment/86679512
has text: Yes such a condition will always be possible, and the ordering in the sub-lists must be same as the original list.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49832087

http://stackoverflow.com/comment/86813934
score: 1
has text: +1, Performance note: `at` and `iat` (both very much underused) are *much* more efficient than `.loc` based equivalents to access scalars.
type: Comment
comment on: http://stackoverflow.com/a/49898417
type: AnswerComment

http://stackoverflow.com/comment/86661922
comment on: http://stackoverflow.com/a/49823060
has text: Note, that unlike Javascript Python isn't created with asynchronicity in mind. In Python if you do something asynchronous you'll need to do it explicitly: explicitly to define asynchronous functions in particular. Common function can't just become asynchronous without efforts. That's a reason why you'll need thread to run synchronous function asynchronously.
type: AnswerComment
score: 7
type: Comment

http://stackoverflow.com/q/49778740
has title: How to arrange return content in pywin32
score: 1
tagged with: pywin32
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86574752
upvote count: 1
has comment: http://stackoverflow.com/comment/86575430
favorite count: 0
accepted answer: http://stackoverflow.com/a/49817997
type: Question
has body: I have few lines of code to send job to my printer using pywin32 but when i send this command the content for the new line it doesn't appear on it row on the paper (newline) after printing but continue to follows the first row the content. When i print this to the terminal it print like what i desire but not when i send the job to the printer. Have been searching on this site on how am going to arrange my content when sending it printed but to no avail. import win32con import win32print import win32ui def text(): rows = (("PETER PAUL", "MALE", "100000"), ("MARGARET ", "FEMALE", "1000"), ("MICHAEL JORDAN", "MALE", "1"),("AGNES", "FEMALE", "200")) return '\r\n'.join('{:20} {:8} {}'.format(*row) for row in rows) print(text()) def printer(): dc = win32ui.CreateDC() printername = win32print.GetDefaultPrinter() dc.CreatePrinterDC(printername) dc.SetMapMode(win32con.MM_TWIPS) scale_factor = 20 dc.StartDoc('Win32print ') pen = win32ui.CreatePen(0, int(scale_factor), 0) dc.SelectObject(pen) font = win32ui.CreateFont({ "name": "Lucida Console", "height": int(scale_factor * 10), "weight": 400, }) dc.SelectObject(font) dc.TextOut(scale_factor * 72, -1 * scale_factor * 72, text()) dc.EndDoc() printer()
has comment: http://stackoverflow.com/comment/86575230
has comment: http://stackoverflow.com/comment/87798262
tagged with: python
has comment: http://stackoverflow.com/comment/86573591
has comment: http://stackoverflow.com/comment/86573988
has answer: http://stackoverflow.com/a/49817997
type: AnsweredQuestion
tagged with: printing

http://stackoverflow.com/q/49789902
answer count: 3
has answer: http://stackoverflow.com/a/49790164
accepted answer: http://stackoverflow.com/a/49790296
tagged with: filehandler
has comment: http://stackoverflow.com/comment/86595113
has answer: http://stackoverflow.com/a/49790296
type: Question
has title: In Python, how to use a file for writing bytes in it and reading as text
has comment: http://stackoverflow.com/comment/86594814
tagged with: python
has comment: http://stackoverflow.com/comment/86595130
has body: I would like to save bytes to a file and then read that file as a text. Can I do it with one with? What should I use, wb, r or wbr? myBytesVar = b'line1\nline2' with open('myFile.txt', 'wb') as fw: fw.write(myBytesVar) with open('myFile.txt', 'r') as fr: myVar = fr.read() print(myVar)
possible better answer: http://stackoverflow.com/a/49790064
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86595195
score: 0
has answer: http://stackoverflow.com/a/49790064

http://stackoverflow.com/comment/86759286
has text: WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element_by_id("TribID"))) ,Got error Message: no such element: Unable to locate element:
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49778379

http://stackoverflow.com/comment/86573243
has text: Why making sure that each argument is a 2-character string? If the two arguments form a valid input for base-16 conversion everything is fine, if not, there will be an exception. Why ask for permission? Or do you have data-sanitation requirements for this function?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49778642

http://stackoverflow.com/comment/86634342
comment on: http://stackoverflow.com/a/49809706
has text: They all are. The list duplication and list mutation ones are the most Idiomatic, I think.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/a/49844354
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49843113
answers question: http://stackoverflow.com/q/49843113
type: AcceptedAnswer
downvote count: 0
has body: Your CNN expects a shape of (num_samples, 20, 20, 1), while your data is in the format (num_samples, 20, 20). Since you only have 1 channel you can just reshape the data to (4000, 20, 20, 1) inputData = inputData.reshape(-1, 20, 20, 1) If you want to do the reshaping inside of the model you can just add a Reshape layer. As your first layer: model.add(Reshape(input_shape = (20, 20), target_shape=(20, 20, 1)))
has comment: http://stackoverflow.com/comment/86709042
score: 3
has comment: http://stackoverflow.com/comment/86709180

matplotlib
tags question: http://stackoverflow.com/q/49764349
tags question: http://stackoverflow.com/q/49778904
tags question: http://stackoverflow.com/q/49834883
tags question: http://stackoverflow.com/q/49854212
tags question: http://stackoverflow.com/q/49829976
tags question: http://stackoverflow.com/q/49796147
tags question: http://stackoverflow.com/q/49878731
tags question: http://stackoverflow.com/q/49780449
tags question: http://stackoverflow.com/q/49847428
tags question: http://stackoverflow.com/q/49807252
tags question: http://stackoverflow.com/q/49864298
tags question: http://stackoverflow.com/q/49765894
tags question: http://stackoverflow.com/q/49846231
tags question: http://stackoverflow.com/q/49866446
tags question: http://stackoverflow.com/q/49894161
tags question: http://stackoverflow.com/q/49848933
tags question: http://stackoverflow.com/q/49808155
tags question: http://stackoverflow.com/q/49786173
tags question: http://stackoverflow.com/q/49913851
tags question: http://stackoverflow.com/q/49842999
tags question: http://stackoverflow.com/q/49848692
tags question: http://stackoverflow.com/q/49812981
tags question: http://stackoverflow.com/q/49783682
tags question: http://stackoverflow.com/q/49813234
tags question: http://stackoverflow.com/q/49793366
tags question: http://stackoverflow.com/q/49807524
tags question: http://stackoverflow.com/q/49858909
tags question: http://stackoverflow.com/q/49781127
tags question: http://stackoverflow.com/q/49910393
tags question: http://stackoverflow.com/q/49851280
tags question: http://stackoverflow.com/q/49781927
tags question: http://stackoverflow.com/q/49791084
tags question: http://stackoverflow.com/q/49760712
tags question: http://stackoverflow.com/q/49861721
tags question: http://stackoverflow.com/q/49896569
tags question: http://stackoverflow.com/q/49902236
tags question: http://stackoverflow.com/q/49896450
tags question: http://stackoverflow.com/q/49768866
tags question: http://stackoverflow.com/q/49805975
tags question: http://stackoverflow.com/q/49879478
tags question: http://stackoverflow.com/q/49886163
tags question: http://stackoverflow.com/q/49831285
tags question: http://stackoverflow.com/q/49760882
tags question: http://stackoverflow.com/q/49882783
tags question: http://stackoverflow.com/q/49814331
tags question: http://stackoverflow.com/q/49802970
tags question: http://stackoverflow.com/q/49848575
tags question: http://stackoverflow.com/q/49880314
tags question: http://stackoverflow.com/q/49910164
tags question: http://stackoverflow.com/q/49912119
tags question: http://stackoverflow.com/q/49790898
tags question: http://stackoverflow.com/q/49810048
tags question: http://stackoverflow.com/q/49803366
tags question: http://stackoverflow.com/q/49763203
tags question: http://stackoverflow.com/q/49784614
tags question: http://stackoverflow.com/q/49867708
tags question: http://stackoverflow.com/q/49769895
tags question: http://stackoverflow.com/q/49894533
tags question: http://stackoverflow.com/q/49791848
tag name: matplotlib
tags question: http://stackoverflow.com/q/49763220
tags question: http://stackoverflow.com/q/49889398
tags question: http://stackoverflow.com/q/49893460
tags question: http://stackoverflow.com/q/49899790
tags question: http://stackoverflow.com/q/49810123
tags question: http://stackoverflow.com/q/49786670
tags question: http://stackoverflow.com/q/49764125
tags question: http://stackoverflow.com/q/49796314
tags question: http://stackoverflow.com/q/49866506
tags question: http://stackoverflow.com/q/49914268
tags question: http://stackoverflow.com/q/49786631
tags question: http://stackoverflow.com/q/49796886
tags question: http://stackoverflow.com/q/49908014
tags question: http://stackoverflow.com/q/49862326
tags question: http://stackoverflow.com/q/49881668
tags question: http://stackoverflow.com/q/49777898
tags question: http://stackoverflow.com/q/49857233
tags question: http://stackoverflow.com/q/49777758
tags question: http://stackoverflow.com/q/49847771
tags question: http://stackoverflow.com/q/49826404

http://stackoverflow.com/a/49845822
type: Answer
has body: x = ['0\t*', '0\t *', '0\t *', '1\t *', '2\t *', '3\t *'] y = [i for i in x if i.startswith('0\t')] y ['0\t*', '0\t *', '0\t *'] Do you mean something like this above?
has comment: http://stackoverflow.com/comment/86706575
score: 0
answers question: http://stackoverflow.com/q/49845754

http://stackoverflow.com/comment/87261527
type: Comment
type: QuestionComment
has text: Hi, I see you're new to SO. If you feel an answer solved the problem, please [mark it as 'accepted’](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) by clicking the green check mark. This helps keep the focus on older SO which still don't have answers.
comment on: http://stackoverflow.com/q/49901566
score: 0

http://stackoverflow.com/a/49905875
has body: You can check the workbook collection with import xlwings as xw xw.books and check if your fullname is already open using something like: if myworkbook in [i.fullname for i in xw.books]: ...
score: 5
accepted answer of: http://stackoverflow.com/q/49883687
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49883687
has comment: http://stackoverflow.com/comment/86865524
has comment: http://stackoverflow.com/comment/86865288
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86807582
comment on: http://stackoverflow.com/q/49894823
score: 0
has text: A user interacts with the button in the shadow DOM. To get it with a CSS selector: `* /deep/ #details-button`. To get all the attributes: `return [].map.call(arguments[0].attributes, function(e){ return {name: e.name, value: e.value}})`.
type: Comment
type: QuestionComment

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

http://stackoverflow.com/q/49815517
tagged with: python
has comment: http://stackoverflow.com/comment/86645403
favorite count: 0
has title: Python ta-lib - Order of time series
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has body: Stupid question when doing indicators in python based on a "series" of data. Example ATR,SMA etc what should the ORDER of the series be ? Latest data first or latest data last ?
score: 2
tagged with: ta-lib

http://stackoverflow.com/comment/86710333
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49847677
type: QuestionComment
has text: If you hadn't cut off the digits with `%.1f`, you would have seen that your numbers aren't integers.

http://stackoverflow.com/comment/86567268
type: QuestionComment
comment on: http://stackoverflow.com/q/49772895
type: Comment
score: 0
has text: @Roelant I am using pygrib module :)

http://stackoverflow.com/q/49795985
has title: Import with Two Files and both need the import
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86607002
tagged with: import
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49796298
has comment: http://stackoverflow.com/comment/86606483
has comment: http://stackoverflow.com/comment/86606699
has comment: http://stackoverflow.com/comment/86606557
tagged with: python
has comment: http://stackoverflow.com/comment/86606253
has body: I have two py files and have simplified my problem of just a few lines. One: from Two import PrintTwo class PrintOne(object): print('HelloOne') Two: from One import PrintOne class PrintTwo(object): print('HelloTwo') This brings up this message: cannot import name 'PrintTwo' as expected. But my problem is I need to use some functions of these classes in both files. I cant find a solution for that, how is the correct workflow for a case like this? Kind regards
tagged with: class
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49796298

http://stackoverflow.com/comment/117515515
type: AnswerComment
has text: @LeeNeverGup, thank you! I've updated the link in the answer)
comment on: http://stackoverflow.com/a/49841366
score: 1
type: Comment

http://stackoverflow.com/a/49866831
type: Answer
has body: Try something like this: The use of array in this situation is good option. In your question the json format is wrong. Therefore you are facing the issue. [{ "question": "I'm so fast you can't see me, though everyone else can see straight through me. I don't stop until the day you die. What am I?", "answer": ["The blink of an eye", "Blink of an eye", "Eye blink"] }]
answers question: http://stackoverflow.com/q/49866771
score: 0

debugging
tags question: http://stackoverflow.com/q/49894724
tags question: http://stackoverflow.com/q/49763672
tags question: http://stackoverflow.com/q/49786002
tag name: debugging
tags question: http://stackoverflow.com/q/49785461
tags question: http://stackoverflow.com/q/49874921
tags question: http://stackoverflow.com/q/49771589
type: Tag
tags question: http://stackoverflow.com/q/49766058
tags question: http://stackoverflow.com/q/49842641

http://stackoverflow.com/a/68106158
has comment: http://stackoverflow.com/comment/126903367
type: Answer
score: -1
upvote count: 0
has body: Use the driver path instead of the driver name. In your example take the full /opt/microsoft/msodbcsql/lib64/libmsodbcsql-13.1.so.9.1
downvote count: 1
answers question: http://stackoverflow.com/q/49806070

http://stackoverflow.com/a/49853341
has body: I'd recommend scraping all the items, and then filtering them in a custom pipeline. You would simply get the stock data in open_spider(), and filter out the items you don't need in process_item().
score: 0
accepted answer of: http://stackoverflow.com/q/49850523
type: Answer
answers question: http://stackoverflow.com/q/49850523
type: AcceptedAnswer

http://stackoverflow.com/q/49791036
has comment: http://stackoverflow.com/comment/86607309
score: 0
has answer: http://stackoverflow.com/a/50433992
has body: I installed latest apache-airflow(1.9.0) with celery(4.1.0)executor. Here is my settings from airflow.cfg: broker_url = sqla+mysql://username:password@host:3306/dbname Taken from http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#module-sqlalchemy.dialects.mysql.pymysql. Tried to run airflow worker got TypeError: Invalid argument(s) 'visibility_timeout' sent to create engine(), using configuration MySQLDialect_mysqldb/QueuePool/Engine. Please check that the keyword arguments are appropriate for this combination of components. Note that I did not send any explicit arguments to create engine(). This is the screenshot of my error. Any help from experts would be appreciated.
has comment: http://stackoverflow.com/comment/86606641
tagged with: sqlalchemy
tagged with: celery
type: Question
answer count: 2
has title: TypeError: Invalid argument(s) 'visibility_timeout' sent to create engine()
type: UnansweredQuestion
tagged with: airflow
tagged with: python
has answer: http://stackoverflow.com/a/49866652

http://stackoverflow.com/q/49908354
score: -1
possible better answer: http://stackoverflow.com/a/49908455
has answer: http://stackoverflow.com/a/49908455
has comment: http://stackoverflow.com/comment/86832650
has comment: http://stackoverflow.com/comment/86833282
type: AnsweredQuestion
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/86832808
has comment: http://stackoverflow.com/comment/86833270
accepted answer: http://stackoverflow.com/a/49908832
has comment: http://stackoverflow.com/comment/86833171
upvote count: 0
has comment: http://stackoverflow.com/comment/86833148
has body: I wrote the following code, after printing about 10 outputs it gets error return 1/sqrt(Om*(1+z)**3+omg0*(1+z)**6+(1-Om-omg0)) ValueError: math domain error the three first functions are correct and work well in other programs please do not be sensitive about their structures, I think the problem is in for-loop and choosing some values which cannot satisfy the condition of sqrt. Could I add some lines to tell Python avoid numbers which lead to math domain error? If yes, How should I do that? I mean passing the step which leads to negative value under sqrt? Cov is a 31*31 mtrix, xx[n] is a list of 31 numbers. def ant(z,Om,w): return 1/sqrt(Om*(1+z)**3+w*(1+z)**6+(1-Om-w)) def dl(n,Om,w,M): q=quad(ant,0,xx[n],args=(Om,w))[0] h=5*log10((1+xx[n])*q) fn=(yy[n]-M-h) return fn def c(Om,w,M): f_list = [] for i in range(31): # the value '2' reflects matrix size f_list.append(dl(i,Om,w,M)) A=[f_list] B=[[f] for f in f_list] C=np.dot(A,Cov) D=np.dot(C,B) F=np.linalg.det(D)*0.000001 return F N=100 for i in range (1,N): R3=np.random.uniform(0,1) Omn[i]=Omo[i-1]+0.05*np.random.normal() wn[i]=wo[i-1]+0.05*np.random.normal() Mn[i]=Mo[i-1]+0.1*np.random.normal() L=exp(-0.5*(c(Omn[i],wn[i],Mn[i])-c(Omo[i-1],wo[i-1],Mo[i-1]))) if L&gt;R3: wo[i]=wn[i] else: wo[i]=wo[i-1] print(wo[i]) The output is: 0.12059556415714912 0.16292726528216397 0.16644447885609648 0.1067588804671105 0.0321446951572128 0.0321446951572128 0.013169965429457382 Traceback (most recent call last): ...... return 1/sqrt(Om*(1+z)**3+omg0*(1+z)**6+(1-Om-omg0)) ValueError: math domain error
has answer: http://stackoverflow.com/a/49908832
has title: How to avoid math domain error when we have sqrt
has comment: http://stackoverflow.com/comment/86832641
has comment: http://stackoverflow.com/comment/86832683
has comment: http://stackoverflow.com/comment/86833126
downvote count: 1
tagged with: sqrt
has comment: http://stackoverflow.com/comment/86832668
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86832852
has comment: http://stackoverflow.com/comment/86832706
linked to: http://stackoverflow.com/q/33684948
tagged with: math
tagged with: python
has comment: http://stackoverflow.com/comment/86833060

http://stackoverflow.com/q/49882804
answer count: 1
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49882916
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Append Lists or Array from .csv into template .csv
has body: This seems relatively straightforward, but as a relatively new user to Python I could use some direction. I am looking to import a .csv file and either make lists or arrays using numpy of the columns in that .csv file. I then want to take those lists or arrays and append them to the columns of a template .csv file. Once appended I would like to save it as an .xlsx. I imagine that I will need to use both pandas and numpy (if using arrays). Example Imported .csv (headers in row 1) Date,Test#,Type 04/12/18,432,D 04/13/18,300,N 04/15/18,433,D Template (headers are in row 4) (Some Formatted Labeling text in row 1 and 2)(Cells in column 2 are formatted to populate column 4 and cells in column 3 are formatted to populate column 5.) Results of Tests G Inc. Date,Test Number,Type,Content,Curve Append and save to xlsx I am not necessarily looking for someone to write this out, more so direct me so that I can learn to write this on my own.
score: 0
tagged with: pandas
tagged with: xlsxwriter

http://stackoverflow.com/q/49833237
has answer: http://stackoverflow.com/a/49833365
has comment: http://stackoverflow.com/comment/86681662
has comment: http://stackoverflow.com/comment/86681743
type: Question
tagged with: python-3.x
has title: Python error for my table
has comment: http://stackoverflow.com/comment/86681655
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49833365
type: AnsweredQuestion
score: 0
has body: t={"Items":[{"AssetId":1609391663,"Name":"Green Checkered Lamp shade","AbsoluteUrl":"https://www.roblox.com/catalog/1609391663/Green-Checkered-Lamp-shade","Price":20,"BestPrice":null,"Remaining":null,"HasSecondaryInfo":false,"NoPriceText":null,"IsFree":false,"Creator":null,"AssetRestrictionIcon":{"TooltipText":null,"CssTag":null,"LoadAssetRestrictionIconCss":true,"HasTooltip":false},"AssetStatusIcon":{"CssTag":"sale","DisplayText":"New","ShowTimerIcon":true},"Thumbnail":{"Final":true,"Url":"https://t0.rbxcdn.com/9fbc2414f0f615cd69ac5b8438861eaa","RetryUrl":"","IsApproved":true}},{"AssetId":1587175771,"Name":"Overseer Wings of Terror","AbsoluteUrl":"https://www.roblox.com/catalog/1587175771/Overseer-Wings-of-Terror","Price":20000,"BestPrice":null,"Remaining":275,"HasSecondaryInfo":true,"NoPriceText":null,"IsFree":false,"Creator":null,"AssetRestrictionIcon":{"TooltipText":"Serialized limited release, resellable.","CssTag":"limited-unique","LoadAssetRestrictionIconCss":true,"HasTooltip":false},"AssetStatusIcon":null,"Thumbnail":{"Final":true,"Url":"https://t7.rbxcdn.com/f6de30365dbad45c10685044d46bdffa","RetryUrl":"","IsApproved":true}}, for i in range(5): itm = t["Items"][i]["AssetId"] if not ListedItems.get(itm): if t["Items"][i]["AssetStatusIcon"]: ListedItems[t["Items"][i]["AssetId"]] = True msg = "@everyone\n\n-----New Item!-----\n" + t["Items"][i]["AbsoluteUrl"] On the line where itm = t["Items"][i]["AssetId"] is where I get the error? I'm not sure why since I'm fairly new to using python. The error is list index out of range
has comment: http://stackoverflow.com/comment/86681667

http://stackoverflow.com/comment/86744330
has text: @fferri @Charles Duffy I have updated my question with the output of `ulimit -a`.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49863492
type: QuestionComment

http://stackoverflow.com/comment/86825444
type: Comment
has text: Brilliant! Thanks a lot. This works for me. Sorry for the newbie question.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49904741

teradata
type: Tag
tag name: teradata
tags question: http://stackoverflow.com/q/49878839
tags question: http://stackoverflow.com/q/49902843
tags question: http://stackoverflow.com/q/49861161

http://stackoverflow.com/q/49880760
tagged with: amazon-s3
has title: Scaling Django File Uploading
tagged with: python
score: 2
upvote count: 2
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: django
tagged with: file-upload
tagged with: amazon-web-services
favorite count: 0
type: Question
has body: I have recently created a Inline form Set to manage files uploading. My objective is hosting my files on AWS. I have a model House. The model has a related Model HouseDocument where files related to a house are stored. HouseDocument has House as a ForeigKey. This is the view : def manage_files(request, house_slug): house = House.objects.get(slug=house_slug) HouseDocumentInlineFormSet = inlineformset_factory(House, HouseDocument, fields=('document',)) if request.method == "POST": formset = BookInlineFormSet(request.POST, request.FILES, instance=house) if formset.is_valid(): formset.save() return HttpResponseRedirect(house.get_absolute_url()) else: formset = BookInlineFormSet(instance=author) return render(request, 'manage_books.html', {'formset': formset}) I'm not seeking a code example. I seek advice on how big web applications handle file uploading when they have a lot of concurrent users ? Any useful documentation ? Does Django IO blocking makes file upload complicated ?

http://stackoverflow.com/comment/86741670
comment on: http://stackoverflow.com/a/49863024
type: AnswerComment
score: 0
type: Comment
has text: @BhushanBabar the ideea is I was trying exactly how Masud Rumir did on his example and is not working is not appearing the data but more even none errors ...

http://stackoverflow.com/a/49899405
has body: It is the train score of the prediction model on all folds excluding the one you are testing on. In your case, it is the score over the 9 folds you trained the model on.
downvote count: 0
answers question: http://stackoverflow.com/q/49899298
has comment: http://stackoverflow.com/comment/86816697
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86820732
score: 4
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49899298

http://stackoverflow.com/a/49775162
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49775067
score: 3
answers question: http://stackoverflow.com/q/49775067
has comment: http://stackoverflow.com/comment/86565584
type: Answer
has comment: http://stackoverflow.com/comment/86566029
has body: The loop is only running once because return is executed during the first iteration of the loop therefore you're only getting the first result. You can get the ping result and append that to a list then once the loop is complete you can just return that list. def ping(ip): param = '-c 1' command = ['ping', param, ip] num = 0 output = [] while (num &lt; 6): output.append(subprocess.check_output(command)) num += 1 return output // or return "\n".join(output)
has comment: http://stackoverflow.com/comment/86565922
upvote count: 3

http://stackoverflow.com/q/49851333
score: 2
has comment: http://stackoverflow.com/comment/86717371
has comment: http://stackoverflow.com/comment/86718473
tagged with: mathematical-optimization
has comment: http://stackoverflow.com/comment/86717717
has comment: http://stackoverflow.com/comment/86717832
has comment: http://stackoverflow.com/comment/86718066
has comment: http://stackoverflow.com/comment/86717259
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86720388
tagged with: bayesian
tagged with: python
has body: Does any one have an idea as to why the following code not produce the same global maxima value on multiple runs? import sys from numpy import sin sys.path.append("./") from bayes_opt import BayesianOptimization bo = BayesianOptimization(lambda x, y: ((((sin(((x-8)**2+y**2)**0.5))/((((x-8)**2+y**2)**0.5)))+0.8*((sin(((x+8)**2+y**2)**0.5))/(((x+8)**2+y**2)**0.5)))), {"x": (-20,20), "y": (-20, 20)}) #bo.explore({'x': [7,7.1,7.2,7.3,7.4,7.5,7.6,7.7,7.8,7.9,8], 'y': [-0.5,-0.4,-0.3,-0.2,-0.1,0,0.1,0.2,0.3,0.4,0.5]}) gp_params = {"alpha": 1e-5, "n_restarts_optimizer": 2} bo.maximize(init_points=5, n_iter=25, acq="ucb", kappa=10, **gp_params) # The output values can be accessed with self.res print(bo.res['max']) I have tried playing the values in the .maximize function but achieved no success. Is there anyway by which I can make this return the same correct value on multiple runs?
has title: Bayesian Optimization

http://stackoverflow.com/q/49848688
score: 1
upvote count: 1
downvote count: 0
tagged with: string
has title: How to append strings to a list in a dictionary
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49848887
possible better answer: http://stackoverflow.com/a/49848887
has answer: http://stackoverflow.com/a/49905449
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49848697
accepted answer: http://stackoverflow.com/a/49848697
tagged with: append
has body: I have some trouble trying to append in a dictionary, I really dont know how to use it, because every time I try to run my code, Its says "'str' object has no attribute 'append'"... I have something like this... oscars= { 'Best movie': ['The shape of water','Lady Bird','Dunkirk'], 'Best actress':['Meryl Streep','Frances McDormand'], 'Best actor': ['Gary Oldman','Denzel Washington'] } so I want to make a new category, and then I want to make a cycle where the user can enter as many nominees as he want... newcategory=input("Enter new category: ") nominees=input("Enter a nominee: ") oscars[newcategory]=nominees addnewnominees= str(input("Do you want to enter more nominees: (yes/no):")) while addnewnominees!= "No": nominees=input("Enter new nominee: ") oscars[newcategory].append(nominees) addnewnominees= str(input("Do you want to enter more nominees: (yes/no):")) Anyone knows how to use the append in dictionaries?
type: AnsweredQuestion
tagged with: list
answer count: 3

http://stackoverflow.com/comment/86766219
score: 0
type: Comment
has text: the Y values are acceleration measurements expressed in ms2.
type: QuestionComment
comment on: http://stackoverflow.com/q/49865057

http://stackoverflow.com/comment/86710046
comment on: http://stackoverflow.com/q/49847548
has text: What about [`numpy.mean`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html)?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86746635
score: 0
comment on: http://stackoverflow.com/q/49865334
has text: @JoshAdel Does it support array creation in the ```nopython``` mode? I thought that's why we needed loop-jitting.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86742836
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49863765
has text: I already linked you to the page for the Firebase Admin SDK. Start there.
type: Comment

http://stackoverflow.com/comment/86834252
has text: This is from a typo in your code: `x_batch = sequence.pad_sequences(x_train, maxlen=None)` gives you the whole padded `x_train` which will be 25000 samples. You might want `x_batch = sequence.pad_sequences(x_batch, maxlen=None)`
score: 0
comment on: http://stackoverflow.com/q/49902780
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86788652
type: Comment
type: QuestionComment
has text: test_x is a dataframe. and test_y is a series. That might be my problem. I just changed test_x to float64 with the one hot encoder. I'll try to run it again.
score: 0
comment on: http://stackoverflow.com/q/49885598

http://stackoverflow.com/q/49816000
has answer: http://stackoverflow.com/a/49816509
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/49816509
answer count: 1
has body: I'm trying to replicate the plot in this SKLearn example code with my own model. I don't quite understand what the following lines do, and how to modify them to my own model: # plot the line, the samples, and the nearest vectors to the plane xx, yy = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50)) Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) #this line created a runtime error with my own input Z = Z.reshape(xx.shape) What does meshgrid do (I've checked the official description but I couldn't understand it - can you explain with layman's terms)? OK it creates a coordinate matrix, but why do we need that? How do I need to set it up for my own data? If I only change the input in this code, it crashes with IndexError: list index out of range (line marked above).
has comment: http://stackoverflow.com/comment/86646849
favorite count: 0
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/86647073
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: 0
has title: What does meshgrid do in this plot?

http://stackoverflow.com/a/49845963
has comment: http://stackoverflow.com/comment/86707491
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49845754
has body: One way to do it is to convert them to binary and map to string you need. data = [('0', 1), ('0', 2), ('0', 3), ('1', 4), ('2', 5), ('3', 6), ('3', 7), ('3', 8), ('2', 9), ('1', 10), ('0', 11), ('-1', 12), ('-2', 13), ('-3', 14), ('-3', 15), ('-3', 16), ('-2', 17), ('-1', 18), ('0', 19), ('0', 20), ('0', 21)] output = {} for (k,v) in data: if k not in output: output[k] = 0 output[k] = 2**v | output[k] # map to binary space. for k in output: tmp = bin(output[k])[2:][::-1] #cut binary prefix and reverse it. stared = tmp.replace('1', '*').replace('0',' ') print('%s\t%s' % (k,stared)) Result: 0 *** * *** 1 * * 2 * * 3 *** -1 * * -2 * * -3 *** Explain: Ok. The first for-loop. Basically, I changed each number to a power of two. I did that because of the property of binary string can be used to represent each position of '*' or ' '. ('0',1) --&gt; ('0',2) # 01 ('0',2) --&gt; ('0',4) # 001 ('0',3) --&gt; ('0',8) # 0001 ('1',4) --&gt; ('1',16) ... so on Now observe that if we combine 01, 001, 0001 using logical 'or'(|) operator we will get pretty much ('0', 0111) as a result. The raw result of the first loop will be: {'0': 3672078, '1': 1040, '2': 544, '3': 448, '-1': 266240, '-2': 139264, '-3': 114688} The numbers are pretty scary but don't let a representation fool you. It arranges nice and meaningful under the binary form. e.g. '0': 3672078 is '0': 0b1110000000100000001110 which matches what is needed(in reversed order). The second loop is mere to convert that into a binary representation. bin is a python builtin function to turn decimal number to a binary string. e.g. bin(2) --&gt; 0b01. Now, we don't need the 0b prefix so we cut it by [:2] operator. It will returns string skipped first two chars. After that, [::-1] operator has added to reverse the binary string because the original form has the most significant to the right(the bit with the highest value) Then, in the last step, we replace '1' with '*' and '0' with ' ' and format it properly.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49845754
upvote count: 1

http://stackoverflow.com/a/49896647
accepted answer of: http://stackoverflow.com/q/49890287
type: Answer
type: AcceptedAnswer
has body: I've finally found the answer to this phenomenon. The python program is using OpenCV 3.4, while the Java bindings of my C# program is using the older OpenCV 3.1 . The FindContours method may be found in both versions, but apparently returns different values.
answers question: http://stackoverflow.com/q/49890287
score: 0

http://stackoverflow.com/a/49914866
score: 0
answers question: http://stackoverflow.com/q/49914779
type: Answer
has body: you have two options: Wrapping with single quotes: '"' Escaping with backslash: "\""

http://stackoverflow.com/q/49782598
tagged with: dictionary
type: Question
answer count: 2
tagged with: items
has title: Progress bar with tqdm while iterating over the items in a python dictionary
downvote count: 0
possible better answer: http://stackoverflow.com/a/67007675
accepted answer: http://stackoverflow.com/a/49783226
tagged with: tqdm
has answer: http://stackoverflow.com/a/67007675
score: 16
tagged with: iteration
upvote count: 16
has answer: http://stackoverflow.com/a/49783226
favorite count: 0
type: AnsweredQuestion
has body: If I'm trying to get a progress bar while iterating over a dict, how can I do this with tqdm? I'm using Python 2.7. This works great with lists: for i in tdqm(l, len(l): &lt;do stuff&gt; But fails over dicts: for k, v in tqdm(d.items(), len(d)): &lt;do stuff&gt; What's the proper way to do this with dicts? Here's a real example: d = {'k1':1, 'k2':2} for k, v in tqdm(d.items(), len(d)): print 'foo' a = 1 + 100 print 'bar' I get: ------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-30-7e4ce2b85414&gt; in &lt;module&gt;() 1 d = {'k1':1, 'k2':2} ----&gt; 2 for k, v in tqdm(d.items(), len(d)): 3 print 'oasdlkfj' 4 a = 1 + 100 5 print 'y' /home/monica/anaconda2/envs/pytorch_p27/lib/python2.7/site-packages/tqdm/_tqdm.pyc in __init__(self, iterable, desc, total, leave, file, ncols, mininterval, maxinterval, miniters, ascii, disable, unit, unit_scale, dynamic_ncols, smoothing, bar_format, initial, position, postfix, unit_divisor, gui, **kwargs) 810 if self.pos: 811 self.moveto(self.pos) --&gt; 812 self.sp(self.__repr__(elapsed=0)) 813 if self.pos: 814 self.moveto(-self.pos) /home/monica/anaconda2/envs/pytorch_p27/lib/python2.7/site-packages/tqdm/_tqdm.pyc in __repr__(self, elapsed) 842 self.desc, self.ascii, self.unit, 843 self.unit_scale, 1 / self.avg_time if self.avg_time else None, --&gt; 844 self.bar_format, self.postfix, self.unit_divisor) 845 846 def __lt__(self, other): /home/monica/anaconda2/envs/pytorch_p27/lib/python2.7/site-packages/tqdm/_tqdm.pyc in format_meter(n, total, elapsed, ncols, prefix, ascii, unit, unit_scale, rate, bar_format, postfix, unit_divisor) 288 if prefix: 289 # old prefix setup work around --&gt; 290 bool_prefix_colon_already = (prefix[-2:] == ": ") 291 l_bar = prefix if bool_prefix_colon_already else prefix + ": " 292 else: TypeError: 'int' object has no attribute '__getitem__'
tagged with: python

http://stackoverflow.com/q/49847748
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86710816
type: Question
linked to: http://stackoverflow.com/q/4663306
tagged with: python
type: UnansweredQuestion
has body: with a given text of: Daily, John 10.0 9.5 8.0 10.0 9.5 10.0 9.0 85.0 92.0 81.0 I am given this information on an imported .txt file and need to open and read the file and then write and save a new text file, which i know how to do, where I am stuck on is how i would manipulate each line of the read text separately, as the first line (the name) needs to be saved, but second line needs to be calculated into a quiz average amount and then the 3rd line a homework average and the fourth line an exam average and then all of them weighted separately and saved next to the saved name of the student. note: after the fourth line starts a new student with the same information. edit: i guess the simplest way to do this would be to have a for loop that read 4 lines of text at a time and worked each of those lines seperately then read another four lines. Is there any way to read in sets of lines instead of one line at a time?
answer count: 1
linked to: http://stackoverflow.com/q/5832856
score: -1
has title: How to seperate lines in text for different uses
downvote count: 2
has comment: http://stackoverflow.com/comment/86710547
upvote count: 1
has answer: http://stackoverflow.com/a/49847761

http://stackoverflow.com/a/49763114
downvote count: 0
has comment: http://stackoverflow.com/comment/86542036
has comment: http://stackoverflow.com/comment/86541838
has comment: http://stackoverflow.com/comment/86541890
has body: Prepend your regex with .* or use a negative lookahead: between(?!.*between\b)\s+(.+?)\s+and\s+(.+?)\s+as Live demo
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86542145
type: Answer
accepted answer of: http://stackoverflow.com/q/49762904
has comment: http://stackoverflow.com/comment/86541893
has comment: http://stackoverflow.com/comment/86541843
answers question: http://stackoverflow.com/q/49762904
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86541866
has comment: http://stackoverflow.com/comment/86541977

http://stackoverflow.com/q/49811384
favorite count: 0
has answer: http://stackoverflow.com/a/49811551
tagged with: python
has comment: http://stackoverflow.com/comment/86637244
type: Question
tagged with: python-3.x
downvote count: 4
upvote count: 0
type: UnansweredQuestion
score: -4
has comment: http://stackoverflow.com/comment/86637463
answer count: 1
has title: Importing specific data in Python from multiple files?
has body: I am a beginner in python and need a bit of help in importing data from multiple files? There are 24 files for each day (hourly) and each file (a dictionary) has 26 elements. I need to import two sets of data (time vs frequency) in Python. Will really appreciate any help. Thanks

http://stackoverflow.com/a/49817850
has comment: http://stackoverflow.com/comment/86714163
has comment: http://stackoverflow.com/comment/86701303
type: Answer
accepted answer of: http://stackoverflow.com/q/49817811
answers question: http://stackoverflow.com/q/49817811
has comment: http://stackoverflow.com/comment/86714193
score: 12
has comment: http://stackoverflow.com/comment/86700755
upvote count: 12
downvote count: 0
has comment: http://stackoverflow.com/comment/86714565
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86714508
has body: Use dictionary comprehension with concat: df = pd.concat({k: pd.Series(v) for k, v in data.items()}).reset_index() df.columns = list('xyz') print (df) x y z 0 1 a 10 1 1 b 30 2 2 a 20 3 2 b 60 For better performance use list compehension with sorting: L = sorted([(k,k1,v1) for k,v in data.items() for k1,v1 in v.items()], key=lambda x: (x[0], x[1])) print (L) [('1', 'a', 10), ('1', 'b', 30), ('2', 'a', 20), ('2', 'b', 60)] df = pd.DataFrame(L, columns=list('xyz')) print (df) x y z 0 1 a 10 1 1 b 30 2 2 a 20 3 2 b 60 Timings: In [34]: %timeit jez1(data) 16.8 ms ± 403 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [35]: %timeit jez(data) 1.96 s ± 90.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [37]: %timeit jp(data) 43 ms ± 353 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) Same code as @jp: data = {str(k): {'a': 10, 'b': 30} for k in range(10000)} def jp(data): return pd.melt(pd.DataFrame.from_dict(data, orient='index').reset_index().rename(columns={'index': 'x'}), id_vars=['x'], value_vars=['a', 'b'], var_name='y', value_name='z')\ .sort_values(['x', 'y']).reset_index(drop=True) def jez(data): df = pd.concat({k: pd.Series(v) for k, v in data.items()}).reset_index() df.columns = list('xyz') return df def jez1(data): L = sorted([(k,k1,v1) for k,v in data.items() for k1,v1 in v.items()], key=lambda x: (x[0], x[1])) df = pd.DataFrame(L, columns=list('xyz')) return df assert (jez1(data).values == jez(data).values).all()
has comment: http://stackoverflow.com/comment/86715583

http://stackoverflow.com/q/49840572
has title: how to return the result from subprocess.popen form the following code
score: 0
has body: import sys import os import subprocess import inspect def run_process(cmd_args): with subprocess.popen(cmd_args) as p: return (p.communicate()) res = run_process(cmd_args); if 'with' in inspect.getsource(run_process): print("'with' used in 'run_process' function definition.\n") if 'popen' in inspect.getsource(run_process): print("'popen' used in 'run_process' function definition.\n") print('process output : %s\n' % (res.decode("utf-8"))) f.close() i get an error at res.decode saying none type has no attribute decode. could some one suggest how to handle run_process function?
answer count: 0
has comment: http://stackoverflow.com/comment/86717023
has comment: http://stackoverflow.com/comment/86696701
has comment: http://stackoverflow.com/comment/86731562
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86695791
tagged with: python
linked to: http://stackoverflow.com/q/27904943
has comment: http://stackoverflow.com/comment/86717381

http://stackoverflow.com/comment/86788570
comment on: http://stackoverflow.com/a/49885761
score: 0
type: Comment
has text: It looks like request already giving you a python dict inside a list. So there's no need to use json.loads. I will update the answer
type: AnswerComment

http://stackoverflow.com/a/49901258
has comment: http://stackoverflow.com/comment/93142104
has comment: http://stackoverflow.com/comment/93106307
answers question: http://stackoverflow.com/q/49839924
has body: I've seen some people using the sys module in their lambda function's code to add the subdirectory, vendored in this case, to their python path... I'm not a fan of that as a solution because it would mean needing to do that for every single lambda function and add the need for extra boiler plate code. The solution I ended up using is to modify the PYTHONPATH runtime environment variable to include my subdirectories. For example, in my serverless.yml I have: provider: environment: PYTHONPATH: '/var/task/vendored:/var/runtime' By setting this as an environment variable at this level it will apply to every lambda function you are deploying in your serverless.yml -- you could also specify it at a per lambda function level if for some reason you didn't want it applied to all of them. I wasn't sure how to self reference the existing value of PYTHONPATH to ensure I wasn't incorrectly overwriting it while in the process of adding my custom path "/var/task/vendored"... would love to know if anyone else has.
type: Answer
has comment: http://stackoverflow.com/comment/86829635
downvote count: 0
has comment: http://stackoverflow.com/comment/94912658
type: AcceptedAnswer
upvote count: 11
score: 11
accepted answer of: http://stackoverflow.com/q/49839924

http://stackoverflow.com/a/49879576
has comment: http://stackoverflow.com/comment/106067695
answers question: http://stackoverflow.com/q/49801891
has body: I have the same problem. I am importing keras as follows from tensorflow import keras from keras.models import Sequential model = Sequential() etc. then it fails on this line: estimator_model = keras.estimator.model_to_estimator(keras_model=kerasModel()) error: /usr/local/lib/python2.7/dist-packages/tensorflow/python/keras/_impl/keras/estimator.pyc in model_to_estimator(keras_model, keras_model_path, custom_objects, model_dir, config) 476 477 keras_weights = keras_model.get_weights() --&gt; 478 if keras_model._is_graph_network: 479 # TODO(yifeif): move checkpoint initialization to scaffold.init_fn 480 _save_first_checkpoint(keras_model, AttributeError: 'Sequential' object has no attribute '_is_graph_network' I am using tensorflow 1.7 I found a solution by explicitly specifying the layers of my model: def kerasModel(): # Define the model model = keras.models.Sequential() #model = Sequential() # input: 100x100 images with 3 channels -&gt; (100, 100, 3) tensors. # this applies 32 convolution filters of size 3x3 each. model.add(keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3), name="data2d")) model.add(keras.layers.Conv2D(32, (3, 3), activation='relu')) model.add(keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(keras.layers.Dropout(0.25)) model.add(keras.layers.Conv2D(64, (3, 3), activation='relu')) model.add(keras.layers.Conv2D(64, (3, 3), activation='relu')) model.add(keras.layers.MaxPooling2D(pool_size=(2, 2))) model.add(keras.layers.Dropout(0.25)) model.add(keras.layers.Flatten()) model.add(keras.layers.Dense(256, activation='relu')) model.add(keras.layers.Dropout(0.5)) model.add(keras.layers.Dense(10, activation='softmax', name='labels')) # Compile the model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model i.e. by putting keras.layers. in each of the lines as above. Previously I had relied on the imports: #from keras.models import Sequential #from keras.layers import Dense, Dropout…
type: Answer
score: 0

http://stackoverflow.com/a/49856868
upvote count: 1
answers question: http://stackoverflow.com/q/49856675
has body: Use write with \n to write content to each line. Ex: with open('Rapport.txt', mode="w") as output: for i in data: output.write("{0} \n".format(str(i)))
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/86728334
downvote count: 0

http://stackoverflow.com/q/49780694
upvote count: 4
has body: I need to connect to Oracle via OCM a non OCM connection looks to be simple conn_str = 'user/password@host:port/service_name' # oracle connection self.con = cx_Oracle.connect(conn_str) same can be translated to this when using tnsnames.ora db_alias = (DESCRIPTION= ) (ADDRESS= (PROTOCOL=TCP)(HOST=DatabaseHost)(PORT=DatabasePort) ) (CONNECT_DATA= (SERVICE_NAME=DatabaseService) ) ) when we connect to OCM using tnsnames.ora, the following is added db_alias = (DESCRIPTION= ***(SOURCE_ROUTE=YES) (ADDRESS= (PROTOCOL=TCP) (HOST=ConnectionManagerHost)(PORT=ConnectionManagerPort)*** ) (ADDRESS= (PROTOCOL=TCP)(HOST=DatabaseHost)(PORT=DatabasePort) ) (CONNECT_DATA= (SERVICE_NAME=DatabaseService) ) ) how do we do the same in python with cx_Oracle?
tagged with: cx-oracle
answer count: 2
has answer: http://stackoverflow.com/a/49785532
downvote count: 0
tagged with: python
type: UnansweredQuestion
favorite count: 0
score: 4
type: Question
has title: cx_Oracle connect to Oracle Connection Manager without tnsnames.ora file
has answer: http://stackoverflow.com/a/50283728

http://stackoverflow.com/comment/86852596
score: 0
type: Comment
has text: In this example the functions are hard-coded. Would it be an option to use "eval" to even not have the "self.MoveAbsolute" but instead specify "self."+string = ....?
type: AnswerComment
comment on: http://stackoverflow.com/a/49916511

http://stackoverflow.com/q/49847622
favorite count: 0
type: Question
has body: I am trying to parse a string looking for a valid date format within it. I would use dateutil or datetime libraries, however, they don't support scanning of whole strings (eg "2003-03-29 George M. Holmes Convention Center, Appalachian State University, Boone, NC" won't parse as it is not all related to a date). The problem is that the string could be in virtually any date format, my goal is to identify and capture it in a group. So: "2003-03-29 George M. Holmes Convention Center, Appalachian State University, Boone, NC" ->"2003-03-29" "DMB Warfield Theatre, San Francisco, CA 5/10/1995" -> "5/10/1995" "''Love You'' (1977)" -> 1977 "DMB Warfield Theatre, San Francisco, CA" does not match Please keep in mind that the date/year could be anywhere in the string and it could also have days, be in mm/dd/yyyy, dd/mm/yyyy, or "MONTH DAY, YEAR" etc. If there is a library that could do this, I would be very grateful if someone could point it out.
upvote count: 0
type: UnansweredQuestion
has title: Python regex to match any date format
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49847646
answer count: 1
downvote count: 1
tagged with: regex

http://stackoverflow.com/comment/86740825
score: 0
has text: @usr2564301 If you google for the title because you're in the need for it, this answer won't help you, unless you have the same constraints as the OP. Yet I wouldn't downvote this answer, it's good to have it in this context.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49861970

http://stackoverflow.com/comment/86758432
type: QuestionComment
comment on: http://stackoverflow.com/q/49870998
has text: OK, so now we need the answer of the two other questions: API and data format. And some code I have tried...
score: 0
type: Comment

http://stackoverflow.com/a/49939966
type: Answer
has body: First of all, note that register is deprecated and not necessary anymore. When trying to register a package on PyPI, you should get a message: Server response (410): This API is no longer supported, instead simply upload the file. Just skip the register step and proceed with the uploading. distutils/setuptools Create a file $HOME/.pypirc with the contents: [distutils] index-servers = pypi [pypi] username: &lt;username&gt; password: &lt;password&gt; and repeat the upload: $ python setup.py sdist upload Thing is, the distutils' upload subcommand doesn't provide an option to enter the credentials from command line, instead completely relying on the .pypirc file. twine If storing credentials in plain text format is not your thing, twine provides a possibility of entering credentials from command line. This is also the officially recommended tool for uploading packages. Install twine: $ pip install twine Build the package: $ python setup.py clean sdist Upload: $ twine upload dist/* The tool will ask you for the username and password. twine also lets you provide the credentials in environment variables: $ TWINE_USERNAME=me TWINE_PASSWORD=passwd twine upload dist/* or via keyring.
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/49787860
upvote count: 5

http://stackoverflow.com/comment/86742444
has text: @CL. I saw in your linked page that the nested SELECT will be flattened to finally a single SELECT, right, but what is the conclusion of this flattening about GordThompson's answer given here? (Thanks in advance, as I'm not SQL expert, I don't want to draw wrong conclusions).
type: Comment
comment on: http://stackoverflow.com/a/49861759
type: AnswerComment
score: 0

http://stackoverflow.com/q/49867759
tagged with: bash
answer count: 0
has body: I am trying to execute a shell script that initiates a python script by passing a shell script as UserData to ec2 instance when its launched (python SDK). The target python script I am trying to run, needs to be run as a user (not root) with all the user environment variables. The bash script that runs this target python script is as follows: #!/usr/bin/env bash source /home/ubuntu/.bashrc source /opt/ros/kinetic/setup.bash source /home/ubuntu/kartographer/install_isolated/setup.bash source /home/ubuntu/catkin_ws/devel/setup.bash /home/ubuntu/takecontrolofEC2.py $1 $2 The bash script that I pass along with the ec2 creation is as follows: #!/usr/bin/env bash echo "Start processing the data" &gt; /home/ubuntu/process.log whoami &gt;&gt; /home/ubuntu/process.log sudo -H -u ubuntu bash -c "/home/ubuntu/runpostprocessingscript.sh s3://mapping/unprocessed_data/tax/2016-02-11/ s3://processed-data/test/tax/ &gt;&gt; /home/ubuntu/process.log" The o/p of process.log is Start processing the data root I do not understand why my last command doesn't get executed. The same command works when I run it from the terminal as root. i.e. sudo su &lt;last command&gt; I am quite not sure where I am going wrong. Anything helps. Thanks FYI: The python script takes long time (2-3 hrs) to finish processing the data. Note: This works when I use SSH / paramiko. But my intention is to have the ec2 instance completely enclosed (without ssh interface) as the data needed is on s3.
tagged with: amazon-ec2
type: Question
has comment: http://stackoverflow.com/comment/86755940
type: UnansweredQuestion
tagged with: python
tagged with: boto3
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/86751181
has comment: http://stackoverflow.com/comment/86791385
score: 0
has title: Bash script doesnt run when passed as UserData to ec2 instance

http://stackoverflow.com/a/49897064
has body: It's because Flask initialize twice on debug mode. Short answers: app.run(debug=True, use_reloader=False) Full answers here: How to stop Flask from initialising twice in Debug Mode?
type: Answer
answers question: http://stackoverflow.com/q/49896915
has comment: http://stackoverflow.com/comment/86809759
upvote count: 2
score: 1
downvote count: 1

http://stackoverflow.com/comment/86580693
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49782603
has text: Sorry what I meant by main being well understood is that, often, function names can be ambiguous, and a docstring can help clarify the coder's intention. That aspect is not needed

http://stackoverflow.com/q/49790708
has comment: http://stackoverflow.com/comment/86596471
has title: urlparse() query string missing
has comment: http://stackoverflow.com/comment/86596433
downvote count: 1
favorite count: 0
tagged with: urlparse
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/86596607
has body: I have two systems: First one work as intended: &gt;&gt;&gt; urlparse.urlparse('foo://bar/?blu=1') ParseResult(scheme='foo', netloc='bar', path='/', params='', query='blu=1', fragment='') # sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0) The second one does it different: &gt;&gt;&gt; urlparse.urlparse('foo://bar/?blu=1') ParseResult(scheme='foo', netloc='bar', path='/?blu=1', params='', query='', fragment='') #sys.version_info(major=2, minor=7, micro=3, releaselevel='final', serial=0) What's wrong here? Both use Python 2.7.
has comment: http://stackoverflow.com/comment/86596869
accepted answer: http://stackoverflow.com/a/49791124
tagged with: python
has comment: http://stackoverflow.com/comment/86596313
has answer: http://stackoverflow.com/a/49791124
has comment: http://stackoverflow.com/comment/86596347
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/86645455
answer count: 1

dictionary
tags question: http://stackoverflow.com/q/49779515
tags question: http://stackoverflow.com/q/49862319
tags question: http://stackoverflow.com/q/49830145
tags question: http://stackoverflow.com/q/49827567
tags question: http://stackoverflow.com/q/49881570
tags question: http://stackoverflow.com/q/49887681
tags question: http://stackoverflow.com/q/49881114
tags question: http://stackoverflow.com/q/49896007
tags question: http://stackoverflow.com/q/49853354
tags question: http://stackoverflow.com/q/49765408
tags question: http://stackoverflow.com/q/49800659
tags question: http://stackoverflow.com/q/49885287
tags question: http://stackoverflow.com/q/49871041
tags question: http://stackoverflow.com/q/49831993
tags question: http://stackoverflow.com/q/49888416
tags question: http://stackoverflow.com/q/49853012
tags question: http://stackoverflow.com/q/49769437
tags question: http://stackoverflow.com/q/49857856
tags question: http://stackoverflow.com/q/49774480
tags question: http://stackoverflow.com/q/49860217
tags question: http://stackoverflow.com/q/49904181
tags question: http://stackoverflow.com/q/49772143
tags question: http://stackoverflow.com/q/49804815
tags question: http://stackoverflow.com/q/49854734
tags question: http://stackoverflow.com/q/49911196
tags question: http://stackoverflow.com/q/49816307
tags question: http://stackoverflow.com/q/49832673
tags question: http://stackoverflow.com/q/49871071
tags question: http://stackoverflow.com/q/49845715
tags question: http://stackoverflow.com/q/49763560
tags question: http://stackoverflow.com/q/49832076
tags question: http://stackoverflow.com/q/49866765
tags question: http://stackoverflow.com/q/49866204
tags question: http://stackoverflow.com/q/49760763
tags question: http://stackoverflow.com/q/49815631
tags question: http://stackoverflow.com/q/49764144
tags question: http://stackoverflow.com/q/49823714
tags question: http://stackoverflow.com/q/49808989
tags question: http://stackoverflow.com/q/49824908
tags question: http://stackoverflow.com/q/49912743
tags question: http://stackoverflow.com/q/49864512
tags question: http://stackoverflow.com/q/49848563
tags question: http://stackoverflow.com/q/49827169
tags question: http://stackoverflow.com/q/49897986
tags question: http://stackoverflow.com/q/49801029
tags question: http://stackoverflow.com/q/49890328
tags question: http://stackoverflow.com/q/49868611
tags question: http://stackoverflow.com/q/49827330
tags question: http://stackoverflow.com/q/49832914
tags question: http://stackoverflow.com/q/49801377
tags question: http://stackoverflow.com/q/49861820
tags question: http://stackoverflow.com/q/49824498
tags question: http://stackoverflow.com/q/49857765
tags question: http://stackoverflow.com/q/49909176
tags question: http://stackoverflow.com/q/49800012
tags question: http://stackoverflow.com/q/49763507
tags question: http://stackoverflow.com/q/49904121
tags question: http://stackoverflow.com/q/49825817
tags question: http://stackoverflow.com/q/49807856
tags question: http://stackoverflow.com/q/49838110
tags question: http://stackoverflow.com/q/49889225
tags question: http://stackoverflow.com/q/49895760
tags question: http://stackoverflow.com/q/49781559
tags question: http://stackoverflow.com/q/49859984
tags question: http://stackoverflow.com/q/49815235
tags question: http://stackoverflow.com/q/49779890
tags question: http://stackoverflow.com/q/49798372
tags question: http://stackoverflow.com/q/49771030
tags question: http://stackoverflow.com/q/49764572
tags question: http://stackoverflow.com/q/49884359
tags question: http://stackoverflow.com/q/49821763
tags question: http://stackoverflow.com/q/49769428
tags question: http://stackoverflow.com/q/49832618
tags question: http://stackoverflow.com/q/49848978
tags question: http://stackoverflow.com/q/49810960
tags question: http://stackoverflow.com/q/49866677
tags question: http://stackoverflow.com/q/49763476
tags question: http://stackoverflow.com/q/49786428
tags question: http://stackoverflow.com/q/49777533
tags question: http://stackoverflow.com/q/49866771

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/49878985
tag name: decision-tree
tags question: http://stackoverflow.com/q/49856936

http://stackoverflow.com/q/49886924
type: Question
has answer: http://stackoverflow.com/a/49888983
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86790338
answer count: 1
tagged with: python
has body: I am trying to save the output of a groupby operation into a csv file through Pandas. My groupby operation is a combination of grouping by a variable 'ID' and summing the values, and then resampling these summed up values by a timeframe, for example, by week. The commands look like tdGroupedWeek = (taxiData.groupby(['Taxi ID', pd.Grouper(freq='W', key='Trip End Timestamp')]) ['Trip Total'] .sum() .unstack(fill_value=0)) tdGroupedWeek.to_csv('week.csv', sep='\t', date_format='%Y-%m-%d %H:%M:%S') Before saving, the dataframe looks like this: Trip End Timestamp 2013-01-06 00:00:00 2013-01-13 00:00:00 2013-01-20 00:00:00 2013-01-27 00:00:00 2013-02-03 00:00:00 2013-02-10 00:00:00 Taxi ID A 0.0 0.0 0.00 0.00 0.0 0.00 B 0.0 0.0 0.00 0.00 0.0 0.00 C 0.0 0.0 0.00 0.00 0.0 0.00 D 0.0 0.0 1181.28 458.46 0.0 687.57 E 0.0 0.0 0.00 0.00 0.0 0.00 But when I re-open this csv, the dataframe seems to lose that extra identifier that names the column indices as 'Trip End Timestamp', and I am also having trouble converting the column names into datetime objects again because they're converted to strings. Now, the dataframe looks like: Taxi ID 2013-01-06 00:00:00 2013-01-13 00:00:00 2013-01-20 00:00:00 2013-01-27 00:00:00 2013-02-03 00:00:00 2013-02-10 00:00:00 0 A 0.0 0.0 0.00 0.00 0.0 0.00 1 B 0.0 0.0 0.00 0.00 0.0 0.00 2 C 0.0 0.0 0.00 0.00 0.0 0.00 3 D 0.0 0.0 1181.28 458.46 0.0 687.57 4 E 0.0 0.0 0.00 0.00 0.0 0.00 Is there a way to preserve that detail while writing the csv; or is there a way to Convert certain column names to datetime objects? Accessing specific indices as df.columns[i] and applying to_datetime doesn't work, as it returns "Index does not support mutable operations". Rename the header row as "Trip End Timestamp" again?
has title: Pandas: Saving 'groupby' output to csv, details about column indices and datetime format lost
has comment: http://stackoverflow.com/comment/86791420
has comment: http://stackoverflow.com/comment/86793974
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe

http://stackoverflow.com/comment/86714024
score: 0
comment on: http://stackoverflow.com/q/49848500
type: QuestionComment
type: Comment
has text: @RJHunter, got it. Thanks a lot!

http://stackoverflow.com/q/49841793
score: -1
has title: Increasing GitHub's X-Ratelimit-limit from 60 to 5000
type: Question
upvote count: 0
tagged with: api
type: UnansweredQuestion
answer count: 1
tagged with: github
has body: I'm trying to get bitcoin GitHub API using URLs with Python. There are numerous pages, but I can only access 60 pages in an hour so need to repeat it again and again. Is there any way to increase "X-RateLimit-Limit: 60" to 5000 (or else)? This is my Python code: import urllib.request import json import datetime import codecs #~287page f=codecs.open("pull6.txt","w","utf-8") #url = https://api.github.com/repos/bitcoin/bitcoin/pulls?state=closed&amp;labels=bug&amp;page=287 for x in range (1,60): #have to change this rate every one hour url='https://api.github.com/repos/bitcoin/bitcoin/pulls?state=closed&amp;labels=bug&amp;page==%s' %x u = urllib.request.urlopen(url) data = u.read() j = json.loads(data) #print(j[0]['labels'][0]['id']) i=0 for item in j: f.write("%s\n" %j[i]) i+=1 f.write("\n") x+=1 f.close() and this is what I get from using curl ocktokit in Git bash: If you know any command, URL or any other way to extend xratelimit please let me know.
favorite count: 0
has answer: http://stackoverflow.com/a/49843227
tagged with: bitcoin
downvote count: 1
tagged with: python

http://stackoverflow.com/comment/86670523
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49827487
has text: That's an elegant and simple way to solve the problem. The issue I run into (which could definitely still incorporate this idea) is that I don't know how long the files will be, and I'd like the length of the generated files to be dynamic.

http://stackoverflow.com/comment/86858526
type: Comment
has text: It seems like it is a better idea to use apache, thank you!
type: AnswerComment
comment on: http://stackoverflow.com/a/49885844
score: 0

http://stackoverflow.com/comment/102865499
type: Comment
score: 0
type: AnswerComment
has text: i've updated the comment to be more of a solution :)
comment on: http://stackoverflow.com/a/58189451

http://stackoverflow.com/a/49851897
score: 0
answers question: http://stackoverflow.com/q/49847548
type: Answer
has body: If you convert your attribute to a numpy array you can do that. This would look neater if you made attribution an array in your class. I don't know if you can do that, so my example does not. import numpy as np class C: def __init__(self, attribution): self.attribution = attribution a=C([[2,1],[4,6]]) b=C([[4,3],[8,8]]) print(a.attribution) print(b.attribution) a_array = np.array(a.attribution) b_array = np.array(b.attribution) print((a_array + b_array)/2) print(np.mean([a_array, b_array], axis=0)) print((a_array + b_array)//2) # preserve int I have done it a few different ways. You can add and divide by 2, or you can use numpy.mean. output [[2, 1], [4, 6]] [[4, 3], [8, 8]] [[3. 2.] [6. 7.]] [[3. 2.] [6. 7.]] [[3 2] [6 7]]

http://stackoverflow.com/a/49837476
has comment: http://stackoverflow.com/comment/103660516
answers question: http://stackoverflow.com/q/49837474
has comment: http://stackoverflow.com/comment/122896928
has body: I found some information on the web (like in this blog post) while I was coming up with the answer for this question, but it was all at least somewhat wrong and/or out of date. Here's a complete set of working instructions: Install the Termux app. Open Termux, then enter/run the following commands in the prompt: $ apt install clang python fftw libzmq freetype libpng pkg-config libcrypt $ LDFLAGS="-lm -lcompiler_rt" pip install jupyter Optionally, you can install some other useful packages that mesh well with Jupyter: $ LDFLAGS="-lm -lcompiler_rt" pip install numpy matplotlib Finally, test the notebook out by running: $ jupyter notebook When you run jupyter notebook, a notebook server starts up and dumps some information to stdout. When you see the line: Copy/paste this URL into your browser when you connect for the first time, to login with a token: copy the following URL, paste it into the browser on your device, and then hit go. You should end up with something that looks like this: I tested these instructions out a Nexus 7 2013 (wifi) running stock Android 6.0.1 (Marshmallow). Update: &lt;foo&gt;-dev packages dropped in Termux As @OmPS pointed out in the comments, Termux dropped all of it's &lt;foo&gt;-dev packages. I've updated step 2. above to match, but I haven't tested it out since I no longer have access to my android device. If someone could please test the current version of the instructions above and then post their experience in the comments, that would be very helpful.
has comment: http://stackoverflow.com/comment/119795384
has comment: http://stackoverflow.com/comment/136352393
type: Answer
has comment: http://stackoverflow.com/comment/105396508
has comment: http://stackoverflow.com/comment/101312596
has comment: http://stackoverflow.com/comment/96294979
has comment: http://stackoverflow.com/comment/122896910
accepted answer of: http://stackoverflow.com/q/49837474
score: 45
has comment: http://stackoverflow.com/comment/105441895
has comment: http://stackoverflow.com/comment/96295614
type: AcceptedAnswer
downvote count: 0
upvote count: 45

http://stackoverflow.com/q/49868003
has answer: http://stackoverflow.com/a/49882713
tagged with: python
tagged with: bokeh
type: AnsweredQuestion
has body: I want to make a multi-level dropdown menu, something like the one in this XKCD: Is there some way to have subcategories fold out like that using the Bokeh Dropdown menu? My question is distinct from Bokeh or HoloViews multiple depended dropdowns because I want a single dropdown with multiple levels, not N separate, inter-dependent dropdown menus. I also don't intend to put this Dropdown in a notebook.
score: 0
answer count: 1
tagged with: drop-down-menu
linked to: http://stackoverflow.com/q/47010764
type: Question
accepted answer: http://stackoverflow.com/a/49882713
has title: Bokeh Multi-level dropdown menu

http://stackoverflow.com/q/49907361
has answer: http://stackoverflow.com/a/49907895
tagged with: http://stackoverflow.com/tag/csv
score: 1
has title: Concatenate csv files in python by ascending order of filenames
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/86830966
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has body: I need to concatenate csv files with same column headers in python. The csv files with the following filenames should concatenate in order as shown below(ascending order of filename): AB201602.csv AB201603.csv AB201604.csv AB201605.csv AB201606.csv AB201607.csv AB201608.csv AB201610.csv AB201612.csv I would like to keep the column headers only from first file. Any idea? I tried to use the below code and it combined the csv file by random filenames and truncated half of the column header name. thanks csvfiles = glob.glob('/home/c/*.csv') wf = csv.writer(open('/home/c/output.csv','wb'),delimiter = ',') for files in csvfiles: rd = csv.reader(open(files,'r'),delimiter = ',') rd.next() for row in rd: print(row) wf.writerow(row)

http://stackoverflow.com/comment/86624288
comment on: http://stackoverflow.com/q/49804746
score: 1
type: Comment
type: QuestionComment
has text: `if` is not `elif`.

http://stackoverflow.com/comment/86657134
has text: I'm trying to take the contents of 'out.txt' and append it to the end of 'fixed_inv.txt' in the form of a new file, 'concat.txt' based on a shared path. My code runs, but the new file has a few lines that are messed up with the error mentioned above.
score: 0
comment on: http://stackoverflow.com/q/49820587
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86713638
type: AnswerComment
comment on: http://stackoverflow.com/a/49849505
has text: Thank you sooooo much. I added what you mentioned, but I got this error. `The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.` The file path is correct 100% but the file is not in the static file, should I put it there ?
type: Comment
score: 0

http://stackoverflow.com/comment/86757432
has text: it stores the value returned by lambda function which is my_dict[k] i.e value of the dictionary corresonding to key k
comment on: http://stackoverflow.com/q/49871071
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86708076
type: QuestionComment
has text: That sounds like an _awful_ user experience. I'd file a bug report w/ MS (if you have the means to do so). As far as how you can know, definitively, whether something is a module or not ... well ... you can't. You can open a shell somewhere and try to import every variable name you want to create before you use it in your code, but that's a horrible strategy.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49845682

http://stackoverflow.com/comment/86753386
has text: Welcome to SO. Unfortunately this isn't a discussion forum or tutorial service. Please take the time to read [ask] and the other links found on that page. Invest some time working your way through [the Tutorial](https://docs.python.org/3/tutorial/index.html), practicing the examples. It will give you an introduction to the tools Python has to offer and you may even start to get ideas for solving your problem.
type: Comment
comment on: http://stackoverflow.com/q/49868980
score: 0
type: QuestionComment

http://stackoverflow.com/q/49867345
has answer: http://stackoverflow.com/a/49867408
upvote count: 3
type: UnansweredQuestion
tagged with: python
downvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/4485779
score: 2
has title: How to deal with INF values when computting the average of values of a list in Python?
has answer: http://stackoverflow.com/a/49867397
answer count: 3
has body: I've a list "L" which contains a huge amount of float elements. My goal is to compute the average of "L". I tried to use sum(L)/len(L), np.mean(L), ..., but it always gives 'inf' as a result, since sum(L) also return 'inf'. I pretty sure that this is memmory issue and python as a limit to store certain values. I would like to know what are the best practices to deal with this issue? Can 'inf' result be detected in runtime and through an if statment, compute average in a diferent way (like susbeting the main list into small ones and compute the averages bewtween them)?
has answer: http://stackoverflow.com/a/49867439
type: Question
linked to: http://stackoverflow.com/q/4485779

http://stackoverflow.com/comment/86755097
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49869880
has text: Before that, lets start with [How To Ask](https://stackoverflow.com/help/how-to-ask).
score: 0

http://stackoverflow.com/comment/86891225
has text: the link mentions to check the "common tools for Visual C++" during Visual Studio install to avoid the .bat error. I already have Visual Studio 15 installed and don't remember If I checked that option. Regardless, I managed to run another setup script and got the following issues: error: Microsoft Visual C++ 14.0 is required. This already comes with the Visual Studio 15 so that was suprising. I then went ahead and updated by setuptools library. Got around the previous error but got an error about it not recognising my path. It wants C:\\Program Files\\Mircosoft SDKs\\Windows\\v8.1\\lib'.
comment on: http://stackoverflow.com/q/49837155
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86765582
comment on: http://stackoverflow.com/q/49874923
score: 1
type: Comment
type: QuestionComment
has text: why dont give a dummy specific time at creation for simplification

branch
tag name: branch
tags question: http://stackoverflow.com/q/49890196
type: Tag

http://stackoverflow.com/q/49915003
tagged with: python
tagged with: django-filter
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49916240
has answer: http://stackoverflow.com/a/49916240
answer count: 1
has comment: http://stackoverflow.com/comment/86847200
has body: First of all, I'm beginner in Django-filter if you could offer best solution, I'll be glad to hear it. I need to filter QuerySet by ForignKeys' fields. And exactly author and worker. Model.py class Object(models.Model): class Meta: abstract = True author = models.ForeignKey('Users.User', on_delete=models.CASCADE) class Task(Object): priority_choices = ( ('high', 'Высокий'), ('middle', 'Стандартный'), ('low', 'Низкий'), ) status_choices = ( ('open', 'Открыта'), ('done', 'Выполнена'), ('close', 'Закрыта'), ) name = models.CharField(max_length=140) description = models.TextField() end_date = models.DateField() worker = models.ForeignKey('Users.User', on_delete=models.CASCADE, related_name='worker_set') priority = models.CharField(max_length=15, choices=priority_choices) status = models.CharField(max_length=15, choices=status_choices) Filters.py class TaskFilter(filters.FilterSet): my_tasks = filters.BooleanFilter( label="Мои задачи", method='my_task_filter', widget=forms.CheckboxInput() ) tasks_for_me = filters.BooleanFilter( label="Задачи для меня", method='tasks_for_me_filter', widget=forms.CheckboxInput() ) commented_tasks = filters.BooleanFilter( label="Я комментировал", method='commented_tasks_filter', widget=forms.CheckboxInput()) class Meta: model = Task fields = ['my_tasks', 'tasks_for_me', 'commented_tasks'] def my_task_filter(self, queryset, name, value): print(1, self, queryset, name, value) return queryset.filter(author_id=self.request.user.id) def tasks_for_me_filter(self, queryset, name, value): print(2, self, queryset, name, value) return queryset.filter(worker_id=self.request.user.id) def commented_tasks_filter(self, queryset, name, value): print(3, self, queryset, name, value) return queryset.filter(comment__author_id=self.request.user.id) According to prints in filters.py I get: 1 &lt;TaskManager.filters.TaskFilter object at 0x7f87290dea90&gt; &lt;QuerySet [&lt;Task: Task object&gt;, &lt;Task: Task object&gt;, &lt;Task: Task object&gt;]&gt; my_tasks F…
type: Question
has title: django-filter custom filter not get queryset
has comment: http://stackoverflow.com/comment/86846776
tagged with: django

http://stackoverflow.com/a/49788995
answers question: http://stackoverflow.com/q/49788231
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49788231
has body: Assuming that you are passing dates in "YYYY-MM-DD" format and DAY_DESC is date type, you could use date literals, which are ANSI standard and avoid TO_DATE SELECT substr(PLACEMENT_DESC, 1, INSTR(PLACEMENT_DESC, '.', 1) - 1) AS "'Placement#'" ,SUM(VIEWS) AS "'Delivered_Impresion'" ,SUM(CLICKS) AS "'Clicks'" ,SUM(CONVERSIONS) AS "'Conversion'" FROM TFR_REP.DAILY_SALES_MV WHERE IO_ID = {} AND DAY_DESC BETWEEN DATE '{}' AND DATE '{}' GROUP BY PLACEMENT_ID ,PLACEMENT_DESC ORDER BY PLACEMENT_ID; The table has a date column in "MM/DD/YYYY" format Date datatypes don't have any formats in database. It is just the display that varies according to you session parameters. However, If you mean DAY_DESC is of string (CHAR/VARCHAR2)type, you could use it after converting it as:- TO_DATE(DAY_DESC,'MM/DD/YYYY') BETWEEN DATE '{}' AND DATE '{}' Please avoid storing dates as character strings in databases.

http://stackoverflow.com/comment/86568441
comment on: http://stackoverflow.com/a/49764797
type: Comment
has text: @spider22 Is there a specific pattern to their placement?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86757101
comment on: http://stackoverflow.com/q/49870499
type: Comment
has text: Using `self.textBrowser.setFontPointSize(20)` https://imgur.com/a/4SAAX
score: 0
type: QuestionComment

http://stackoverflow.com/q/49870036
tagged with: pickle
tagged with: security
type: AnsweredQuestion
score: 0
tagged with: python
has title: Serialization not working with cPickle
type: Question
accepted answer: http://stackoverflow.com/a/49915081
linked to: http://stackoverflow.com/q/19855156
has answer: http://stackoverflow.com/a/49915081
answer count: 1
has body: Im trying to perform a cPickle deserialization for a CTF. Im working on an exploit for a deserialization vuln, trying to generate a python class that will run a command on a server when deserialized, following this example: https://lincolnloop.com/blog/playing-pickle-security/ import os import cPickle # Exploit that we want the target to unpickle class Exploit(object): def __reduce__(self): return (os.system, ('ls',)) shellcode = cPickle.dumps(Exploit()) print shellcode The thing is that the server I'm trying to exploit doesn't have the "os" or the "subprocess" modules included, so I'm not able to run shell commands. I'm trying to read local files with objects generated with the following code: class Exploit(object): def __reduce__(self): data = open("/etc/passwd", "rb").read() return data shellcode = cPickle.dumps(Exploit()) print shellcode but when i try to run it to generate the payload, it tries to read my local /etc/passwd file and fails with the error message: shellcode = cPickle.dumps(Exploit()) cPickle.PicklingError: Can't pickle &lt;main.Exploit object at 0x7f14ef4b39d0>: attribute lookup main.root:x:0:0:root:/root:/b in/sh (/etc/passwd continues) When I run the first example, it generates the following pickle succesfully (and doesnt try to do an ls on my machine): cposix system p1 (S'ls' p2 tp3 Rp4 . So why is it not working with my code?

http://stackoverflow.com/comment/131894806
has text: I actually had to set `MAGICK_HOME` to this path (note `Cellar` instead of `bin`), unfortunately with a specific version number: `export MAGICK_HOME=/opt/homebrew/Cellar/imagemagick/7.1.0-53`
type: Comment
comment on: http://stackoverflow.com/a/72396291
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86554109
has text: Excellent analysis.
comment on: http://stackoverflow.com/a/49766715
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49859885
tagged with: anaconda
linked to: http://stackoverflow.com/q/48077745
tagged with: python
has title: Cannot start Jupyter Notebook in Anaconda Prompt (error: async)
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/86734751
type: Question
has body: For the past three months since the initial installation, I've been opening jupyter notebook by going into Anaconda Prompt and simply typing "jupyter notebook"; however, starting from this afternoon I've been getting the error message below. Starting jupyter notebook in my windows start menu doesn't work either, and I can't get Anaconda Navigator to start either. I've also tried uninstalling and re-installing all Anaconda and Python related programs, but it still shows the same error message below (base) C:\Users\jieming&gt;jupyter notebook Traceback (most recent call last): File "C:\Users\jieming\Anaconda3\lib\asyncio\__init__.py", line 16, in &lt;module&gt; from . import _overlapped ImportError: cannot import name '_overlapped' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\jieming\Anaconda3\Scripts\jupyter-notebook-script.py", line 6, in &lt;module&gt; from notebook.notebookapp import main File "C:\Users\jieming\Anaconda3\lib\site-packages\notebook\notebookapp.py", line 38, in &lt;module&gt; from jinja2 import Environment, FileSystemLoader File "C:\Users\jieming\Anaconda3\lib\site-packages\jinja2\__init__.py", line 82, in &lt;module&gt; _patch_async() File "C:\Users\jieming\Anaconda3\lib\site-packages\jinja2\__init__.py", line 78, in _patch_async from jinja2.asyncsupport import patch_all File "C:\Users\jieming\Anaconda3\lib\site-packages\jinja2\asyncsupport.py", line 13, in &lt;module&gt; import asyncio File "C:\Users\jieming\Anaconda3\lib\asyncio\__init__.py", line 18, in &lt;module&gt; import _overlapped # Will also be exported. OSError: [WinError 10107] 系统调用失败 (roughly translates into: failure to call the relevant system)。
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86771664
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86768754
tagged with: initialization
tagged with: startup

http://stackoverflow.com/comment/86704925
comment on: http://stackoverflow.com/q/49845034
score: 0
has text: Can you *show us* your desired output for, say, 20 rows?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86544623
type: Comment
comment on: http://stackoverflow.com/q/49764485
type: QuestionComment
score: 2
has text: It is, in fact, a duplicate of late binding question. You can force early binding by something like this: `B = [lambda element=element: element for element in A]`.

http://stackoverflow.com/comment/86584928
type: AnswerComment
comment on: http://stackoverflow.com/a/49784543
has text: I segmented the `conv2d_transpose` operation into 10 separate ops but Tensorflow apparently also has a 2GB graph size limit. Therefore performing these operations isn't possible with the library in its current state. :( Thanks again for the help! For future readers, it's possible to implement the FCN-8 network with 1000 classes, but size limits make it impossible to do this in TF with FCN-16 and FCN-32.
type: Comment
score: 0

http://stackoverflow.com/q/49788584
type: Question
has comment: http://stackoverflow.com/comment/86595661
tagged with: graph
accepted answer: http://stackoverflow.com/a/49790072
tagged with: python
has comment: http://stackoverflow.com/comment/86594860
has answer: http://stackoverflow.com/a/49790072
has title: Not able to read .txt file in iGraph python
tagged with: igraph
type: AnsweredQuestion
score: 0
answer count: 1
has body: I'm trying to read a text file containing space separated columns using python's python-igraph library. I'm following the documentation but still getting the following error. Traceback (most recent call last): File "C:/Users/Lucy/PycharmProjects/CS286Project/dataClean.py", line 3, in &lt;module&gt; read_graph= Graph.Read_Ncol('1.txt', directed=True) NameError: name 'Graph' is not defined Python code.. import igraph read_graph = Graph.Read_Ncol('1.txt', directed=True) .txt file 72QMMSWgOns boBreak 755 Comedy 35 604 3.91 11 3 hQ-xsBZ_Nqo vVa0VC9o3MQ sagopakajmerat 728 Film &amp; Animation 192 266 4 4 4 bnC17Mr010k Since the spacing between coloums is uneven, is that what is causing this error? Edit 1: After using the solution provided by @Gwendal Grelier I get the following error read_graph = igraph.Graph.Read_Ncol('1.txt', directed=True) igraph._igraph.InternalError: Error at src\foreign.c:243: Parse error in NCOL file, line 1 (syntax error, unexpected ALNUM, expecting NEWLINE), Parse error

http://stackoverflow.com/q/49819718
tagged with: subprocess
has comment: http://stackoverflow.com/comment/86654472
has body: I want to write a program in Python which starts a docker, executes some commands inside the docker and returns the output. This is, something I would do in a shell like : docker run --rm -i -it name_docker_image echo "Input for programm" | script.sh Output of the script I am trying to do it with a code like: process = subprocess.Popen("sudo docker run --rm -i -it syntaxnet",stdout=subprocess.PIPE, shell=True) process.communicate("echo \""+ sentence + "\" | work/demo.sh") out = process.stdout.read() retyurned_value= out.splitlines() But it gives me an error message: "the input device is not a TTY". How can I fix it?
has title: Docker and Python
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86654481
tagged with: docker
score: 0
has comment: http://stackoverflow.com/comment/86654519

http://stackoverflow.com/a/49837452
has body: If you know your colors before-hand, you could use masking with DataFrame.where and str.join to get this done. v = pd.DataFrame( np.repeat('red;', 'blue;', len(df), axis=0), columns=df.columns, index=df.index ) df['msg'] = v.where(df.applymap(len) &gt; 0, '').agg(''.join, axis=1) df A B msg 0 x x red;blue; 1 x blue; 2 x red; 3
has comment: http://stackoverflow.com/comment/86690316
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49837404
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86690327
answers question: http://stackoverflow.com/q/49837404
has comment: http://stackoverflow.com/comment/86690868
type: Answer
score: 4

http://stackoverflow.com/q/49836236
tagged with: python
has answer: http://stackoverflow.com/a/50493040
has comment: http://stackoverflow.com/comment/86687649
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has title: beautifulsoup tags with embedded id="x" python
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/86687967
has comment: http://stackoverflow.com/comment/86688007
has body: I have xml that I am trying to extract from that looks like this: <transactionCoding> 4 S 0 <footnoteId id="F1"/> I can get all of the values of each tag except the footnoteid, whhich comes back as none. I have tried every function of footnoteid.string, gettext getattr,etc but nothing works. I need to get the value F1 out of the tag, but I can't figure out how here's the code: import os from bs4 import BeautifulSoup def parse_xml_string(fls): temp = fls.find_next("value") t = temp.text print (t) return (t) if __name__ == '__main__': nonderivtxn = soup.find_all("nonderivativetransaction") nd = [[] for _ in range(len(nonderivtxn))] for index in range(len(nonderivtxn)): coding = nonderivtxn[index]. find("transactioncoding") tformtype = coding.transactionformtype.text tcode = coding.transactioncode.text swapinvolved = coding.equityswapinvolved.text footnote= coding.footnoteid.gettext() print (tcode,swapinvolved,footnote.content,tformtype)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86714427

http://stackoverflow.com/comment/86589399
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49786822
has text: What if I have more than two data frames? will merge work?

http://stackoverflow.com/comment/138308545
type: Comment
has text: Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?**
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/78446587

http://stackoverflow.com/comment/86783807
score: 0
comment on: http://stackoverflow.com/a/49872273
type: Comment
type: AnswerComment
has text: Looks like it's not supported. ODBC connections is better variant for multiple caches.

http://stackoverflow.com/q/49841113
has answer: http://stackoverflow.com/a/50282548
has comment: http://stackoverflow.com/comment/86727945
answer count: 1
has comment: http://stackoverflow.com/comment/86754880
type: Question
has comment: http://stackoverflow.com/comment/86732946
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86697683
tagged with: python
has body: I need assistance in making a code that will overlay image on image and text on images in JES. I am unable to start due to limited knowledge of Overlaying images on images, text on images, scaling text and image up or down and transparency levels. If anyone will assist me it would be nice. Thanks def scale(picture,factor): newHeight = int(factor*getHeight(picture))+1 newWidth = int(factor*getWidth(picture))+1 returnPic = makeEmptyPicture(int(newWidth),int(newHeight)) sx = 0 for tx in range(0,newWidth): sy = 0 for ty in range(0,newHeight): if (int(sx) &lt; getWidth(picture)) and (int(sy) &lt; getHeight(picture)): sp = getPixel(picture,int(sx),int(sy)) tp = getPixel(returnPic,tx,ty) setColor(tp,getColor(sp)) sy = sy + (1/factor) sx = sx + (1/factor) show(returnPic) def grayScaleNew(): picture = makePicture("forbidden-city.jpg") for px in getPixels(picture): newRed = getRed(px) * 0.2121 newGreen = getGreen(px) * 0.7152 newBlue = getBlue(px) * 0.0722 luminance = newRed + newGreen + newBlue setColor(px,makeColor(luminance,luminance,luminance)) def testTransparentOverlay(): # This function reads in two pictures and produces a new picture that # is made by copying picture 1 and then overlaying picture 2 on top # of picture 1. (It is placed in the centre of the image) # This requires the width and height of picture 2 to be less than # the width and height of picture 2 (so it fits). So it checks # that the size of each image is correct before creating the new picture. # 1. Get the two pictures and show them file = pickAFile() picture1 = makePicture(file) file = pickAFile() picture2 = makePicture(file) show(picture1) show(picture2) #2. Test the size of the pictures - picture 2 needs to fit inside # picture 1 (so check width and height) if getWidth(picture2) &gt; getWidth(picture1): errorMessageWidth = "ERROR: The width of picture2 is greater than picture1" print(errorMessageWidth) elif getHeight(picture2) &gt; getHeight(picture1): errorMessageWidth = "ERROR: The width of pict…
has title: Code for overlaying image on image and text on images in JES
score: 0

http://stackoverflow.com/comment/86705564
type: Comment
type: QuestionComment
has text: ok thanks. now i want a new image in the same place
score: 0
comment on: http://stackoverflow.com/q/49845169

coordinates
tags question: http://stackoverflow.com/q/49845034
tag name: coordinates
tags question: http://stackoverflow.com/q/49812913
tags question: http://stackoverflow.com/q/49853567
tags question: http://stackoverflow.com/q/49887957
tags question: http://stackoverflow.com/q/49869750
type: Tag
tags question: http://stackoverflow.com/q/49839185
tags question: http://stackoverflow.com/q/49811583

http://stackoverflow.com/comment/86795775
has text: Thank you, I think my code autocompletion is stupid.
score: 0
comment on: http://stackoverflow.com/a/49889837
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49767233
has title: TensorFlow: Error on reading image files from folder "Can not squeeze dim[1]"
tagged with: python
has answer: http://stackoverflow.com/a/49870394
tagged with: deep-learning
score: 0
has body: I have a folder with two pictures and a csv with filenames and labels that I've put into two arrays: filenames: array(['pic1.jpg', 'pic2.jpg'], dtype=object); labels_i: array([0, 1]) I created a train Input Funktion def train_input_fn(filenames, labels_i): filenames2 = tf.constant(filenames) labels2 = tf.constant(labels_i, dtype=tf.int64) dataset = tf.data.Dataset.from_tensor_slices((filenames2, labels2)) def _parse(filename, label): image_string = tf.read_file(PATH+"data/"+filename) image_decoded = tf.image.decode_jpeg(image_string) image_resized = tf.image.resize_images(image_decoded, [28, 28]) return image_resized, label dataset = dataset.map(_parse) iterator = dataset.make_one_shot_iterator() features, labels = iterator.get_next() return features, labels My Model is basically the same as the MNIST Tutorial, I've only modified the input layer to shape [-1, 28, 28, 3] instead of [-1, 28, 28, 1] because of RGB pictures. def my_model(features, labels, mode, params): # Input Layer input_layer = tf.reshape(features, [-1, 28, 28, 3]) # Convolutional Layer #1 conv1 = tf.layers.conv2d( inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) # Pooling Layer #1 pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) # Convolutional Layer #2 and Pooling Layer #2 conv2 = tf.layers.conv2d( inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) # Dense Layer pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu) dropout = tf.layers.dropout( inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN) # Logits Layer logits = tf.layers.dense(inputs=dropout, units=2) # Compute predictions. predicted_classes = tf.argmax(logits, 1) if mode == tf.estimator.ModeKeys.PREDICT: predictions = { 'class_ids': predicted_classes[:, tf.newaxis], 'probabilit…
has comment: http://stackoverflow.com/comment/86581647
answer count: 1
has comment: http://stackoverflow.com/comment/86679687
tagged with: tensorflow
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/49830746
has comment: http://stackoverflow.com/comment/86678153
has comment: http://stackoverflow.com/comment/86676949
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: The function is spellchecker but you tried to import spellChecker.
has comment: http://stackoverflow.com/comment/86677622
accepted answer of: http://stackoverflow.com/q/49830724
has comment: http://stackoverflow.com/comment/86678171
has comment: http://stackoverflow.com/comment/86676752
answers question: http://stackoverflow.com/q/49830724
score: 1
type: Answer

http://stackoverflow.com/comment/86572869
score: 0
type: AnswerComment
has text: @Kenstars so when it's in the inner loop it should be openfile = open(database, i, filename, 'w'). How does it know to go to the folder I just made on my desktop?
comment on: http://stackoverflow.com/a/49778519
type: Comment

http://stackoverflow.com/q/49785536
has answer: http://stackoverflow.com/a/71713998
tagged with: python
has answer: http://stackoverflow.com/a/58303321
type: Question
has comment: http://stackoverflow.com/comment/86586571
score: 41
has body: I cannot seem to get the value of learning rate. What I get is below. I've tried the model for 200 epochs and want to see/change the learning rate. Is this not the correct way? &gt;&gt;&gt; print(ig_cnn_model.optimizer.lr) &lt;tf.Variable 'lr_6:0' shape=() dtype=float32_ref&gt;
has answer: http://stackoverflow.com/a/65023649
upvote count: 41
accepted answer: http://stackoverflow.com/a/49785582
downvote count: 0
answer count: 7
tagged with: neural-network
has comment: http://stackoverflow.com/comment/86586632
has answer: http://stackoverflow.com/a/49785582
tagged with: machine-learning
has title: Get learning rate of keras model
has answer: http://stackoverflow.com/a/57778151
tagged with: keras
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49793497
possible better answer: http://stackoverflow.com/a/57778151
has answer: http://stackoverflow.com/a/57317040

http://stackoverflow.com/comment/86537939
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/168676/discussion-between-m-sanders-and-wen).
type: AnswerComment
comment on: http://stackoverflow.com/a/49758277
score: 0

http://stackoverflow.com/q/49845551
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I want to know how to make it so the loading cursor will show up if you are hovering over any part of the window, I know how to do it for just one widget (&lt;Widget&gt;(cursor="watch")) but I do not know how to apply it to the whole window it tried to do it like Tk(cursor="watch") but it will just give me and error that says that it doesn't take that argument. Can someone please tell me how to do that. Thanks in advance Python 3
tagged with: python
has title: Apply tkinter cursor onto the entire window
type: AnsweredQuestion
tagged with: tkinter
upvote count: 2
score: 1
accepted answer: http://stackoverflow.com/a/49848146
answer count: 1
has answer: http://stackoverflow.com/a/49848146

http://stackoverflow.com/comment/86765017
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49868096
has text: Thanks. I have not come across a list of layers not supported by UFF. But the work around using maximum operation worked great!

http://stackoverflow.com/comment/94990165
type: AnswerComment
comment on: http://stackoverflow.com/a/49985041
score: 0
has text: I did some testing and I have come to the conclusion that my cursor file was bad, thanks for the help
type: Comment

http://stackoverflow.com/comment/86670872
type: QuestionComment
has text: no headers in any rows, just for representational purposes
comment on: http://stackoverflow.com/q/49827677
score: 0
type: Comment

http://stackoverflow.com/q/49778007
accepted answer: http://stackoverflow.com/a/49842906
score: 0
answer count: 1
tagged with: python
has title: Django: Change url in Class based view GET request
type: Question
tagged with: url
has body: Hi I have two forms which render to the same template. When i submit my runsearchform, it takes me to the page: localhost/reporting/?run=2&amp;submit=Search+for+run where 2 is my run PK id How can I modify this URL into something like localhost/reporting/run_name where run_name = a unique field in my Run model that is not the primary key views: class ReportView(View): runsearchform = RunSearchForm samplesearchform = SampleSearchForm def get(self, request, *args, **kwargs): runsearchform = self.runsearchform() context = {'runsearchform': runsearchform} if 'run' in request.GET: samplesearchform = self.samplesearchform(request.GET) context = {'samplesearchform': samplesearchform} return render(request, 'results/reporting.html', context) def post(self, request, *args, **kwargs): """ do stuff with samples... """
tagged with: django
has answer: http://stackoverflow.com/a/49842906
type: AnsweredQuestion

http://stackoverflow.com/comment/111631161
score: 0
comment on: http://stackoverflow.com/q/49771589
type: Comment
type: QuestionComment
has text: I have looked up the possible duplicate, the question is a duplicate, the answers are not: they are still suggesting adding macros, it is at an old stage of mid 2017, which might rather confuse any users of today. This question again is outdated, as in some answers, the shortcut seems yet to come, though it is already there, also with the output popping up automatically. The answer of @ZacharyRianSmith should be accepted.

http://stackoverflow.com/comment/86652370
has text: Thanks! I didn't know this numpy feature. Tested the speed as well: %timeit tfidfmax[np.lexsort((tfidfmax.index, -tfidfmax.values))]. 211 µs ± 6.86 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49814962
type: AnswerComment

http://stackoverflow.com/comment/86833669
has text: Your real problem is the random errors anywhere anytime.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49908787
type: Comment

http://stackoverflow.com/comment/86841829
type: Comment
has text: @nahusznaj - in `Mydisciplines` are also `Mathematics` and `Computation Theory` ? then possible solition is extract both by `df['Mydisciplines'] = s.str.findall(pat).str.join(', ')`, but not sure if need it.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49817683

http://stackoverflow.com/a/49907592
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49888314
has comment: http://stackoverflow.com/comment/86832821
answers question: http://stackoverflow.com/q/49888314
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: The submit method on the form does not trigger the submit handler, a way around this would be to bind the ajax request to the select's change event. $(function() { $("#box1").on("change", function(event){ $.ajax({ data: { box1 : $("#box1").val() }, type:"POST", url : "/process" }) .done(function(data){ $("#site1").attr("href",data.site1); $("#image1").attr("src", data.image1); }); }); }); Select News Sites here CNN NBC Fox

http://stackoverflow.com/a/49842906
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49778007
answers question: http://stackoverflow.com/q/49778007
has body: You could specify the run_name in your urls.py such as: url(r'^(?i)reporting/(?P&lt;run_name&gt;[a-z0-9]+)/$', myapp.views.ReportView.as_view()) And then your view could receive the parameter such as: class ReportView(View): runsearchform = RunSearchForm samplesearchform = SampleSearchForm def get(self, request, run_name): # Load the report based on the run_name, and do something with it When a request is made to e.g. localhost/reporting/myreport, the run_name argument would be set to myreport.
downvote count: 0
score: 1

http://stackoverflow.com/a/49910010
upvote count: 1
answers question: http://stackoverflow.com/q/49909935
has comment: http://stackoverflow.com/comment/86836004
has body: Change: state = ["ARIZONA", [coordList], 7016270] to: state = ["ARIZONA", coordList, 7016270] coordList is already a list of x, y pairs, leave it like that.
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/q/49797786
has answer: http://stackoverflow.com/a/49816320
has answer: http://stackoverflow.com/a/49805176
upvote count: 36
accepted answer: http://stackoverflow.com/a/49816320
downvote count: 3
has title: How to get cursor in SQLAlchemy
tagged with: database-cursor
possible better answer: http://stackoverflow.com/a/62552627
has comment: http://stackoverflow.com/comment/86633107
has answer: http://stackoverflow.com/a/62552627
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/86647046
score: 33
has comment: http://stackoverflow.com/comment/86647368
favorite count: 0
type: Question
has body: I am newbie in Python Flask. In my project we are creating db object using below code. app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) I want to get cursor object from db. Can someone please help me on it. I know using connection object we can get cursor. But can we get cursor from db object which is created by above way? Thanks.
has comment: http://stackoverflow.com/comment/86648013
tagged with: python
has answer: http://stackoverflow.com/a/74007366
tagged with: flask
answer count: 4
linked to: http://stackoverflow.com/q/9752372
type: AnsweredQuestion

http://stackoverflow.com/a/52265391
has body: I believe the issue is in your "con = cnxn" statement. Try this: import pandas as pd import sqlalchemy from sqlalchemy import create_engine OBDC_cnxn='Python_Data_ODBC' #this will be the name of the ODBC connection to this database in your ODBC manager. engine = create_engine('mssql+pyodbc://'+ODBC_cnxn) df.to_sql('test', schema = 'public', con = engine, index = False, if_exists = 'replace')
score: -1
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/49825933
type: Answer

http://stackoverflow.com/q/49760092
has title: python numpy where returning unexpected warning
linked to: http://stackoverflow.com/q/48696344
has body: Using python 2.7, scipy 1.0.0-3 Apparently I have a misunderstanding of how the numpy where function is supposed to operate or there is a known bug in its operation. I'm hoping someone can tell me which and explain a work-around to suppress the annoying warning that I am trying to avoid. I'm getting the same behavior when I use the pandas Series where(). To make it simple, I'll use a numpy array as my example. Say I want to apply np.log() on the array and only so for the condition a value is a valid input, i.e., myArray>0.0. For values where this function should not be applied, I want to set the output flag of -999.9: myArray = np.array([1.0, 0.75, 0.5, 0.25, 0.0]) np.where(myArray&gt;0.0, np.log(myArray), -999.9) I expected numpy.where() to not complain about the 0.0 value in the array since the condition is False there, yet it does and it appears to actually execute for that False condition: -c:2: RuntimeWarning: divide by zero encountered in log array([ 0.00000000e+00, -2.87682072e-01, -6.93147181e-01, -1.38629436e+00, -9.99900000e+02]) The numpy documentation states: If x and y are given and input arrays are 1-D, where is equivalent to: [xv if c else yv for (c,xv,yv) in zip(condition,x,y)] I beg to differ with this statement since [np.log(val) if val&gt;0.0 else -999.9 for val in myArray] provides no warning at all: [0.0, -0.2876820724517809, -0.69314718055994529, -1.3862943611198906, -999.9] So, is this a known bug? I don't want to suppress the warning for my entire code.
has answer: http://stackoverflow.com/a/49760157
tagged with: python
score: 2
tagged with: numpy
has answer: http://stackoverflow.com/a/49760286
answer count: 3
upvote count: 2
tagged with: pandas
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49760871
favorite count: 0
type: Question

http://stackoverflow.com/comment/86738112
has text: The Beta distribution has no closed form for its median (except for a few very simple edge cases), so it is in general impossible to recover the values for a and b. An approximate expression for a, b > 1 exists, but it is not applicable in this case (assuming the expression, the resulting a, b are < 1 for mu = 12 and median = 6.5).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49859273
type: AnswerComment

http://stackoverflow.com/a/49869267
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86803528
score: 3
has body: You can use __file__ pseudo variable, to find the directory where your script is located. dir_path = os.path.dirname(os.path.realpath(__file__)) Then you can use os.path.join to compose full paths of your data files
has comment: http://stackoverflow.com/comment/86818352
upvote count: 3
has comment: http://stackoverflow.com/comment/86803437
type: Answer
accepted answer of: http://stackoverflow.com/q/49869161
answers question: http://stackoverflow.com/q/49869161
has comment: http://stackoverflow.com/comment/86819209

http://stackoverflow.com/q/49825610
has body: I am currently HTML scraping to get some data from a webpage for a bot I am creating in Discord. I have previously used lxml successfully to scrape HTML from a different website, however, the website I am trying to scrape right now is detecting an adblocker and as a result whatever data I try to scrape, I receive the same value; my code is as follows `import sys from lxml import html import requests def main(arg): page = requests.get("https://fortnitetracker.com/profile/pc/" + arg) tree = html.fromstring(page.content) killdeath = tree.xpath('//div[@class="stats"&gt;K/d]/text()') print(killdeath)` The value I am getting is '\nPlease consider adding Fortnite Tracker to your adblock whitelist! Our ads support the development and hardware costs of running this site. Really hate ads? Become a
answer count: 2
tagged with: lxml
has answer: http://stackoverflow.com/a/49825746
has title: Data scraping with Python lxml returns adblocker value
tagged with: web-scraping
type: Question
has answer: http://stackoverflow.com/a/49826317
possible better answer: http://stackoverflow.com/a/49825746
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49826317
score: 0

http://stackoverflow.com/q/49873779
has comment: http://stackoverflow.com/comment/87365112
type: UnansweredQuestion
tagged with: python
score: 15
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/87369009
has comment: http://stackoverflow.com/comment/87244046
has title: Hosting interactive jupyter notebook on private website
answer count: 3
has body: I currently run a personal website using Wordpress (but hosted on siteground) that is a set of engineering study guides. I would like to move towards making these study guides interactive (i.e. refreshing graphics based on sliders, doing basic calculations to indicate if a design works or not, so I need numpy). A friend recommended that I utilize Jupyter notebooks for this purpose, as you can both render LaTeX (which I'm currently using Mathjax with Wordpress to do), as well as have the types of interactive graphics I want using either Bokeh or Plotly. While I've seen tutorials for sharing notebooks on specific servers, what I'm after is being able for others to run my notebook in their browser (read-only), where the notebook is privately hosted. I'm still not sure if Jupyter is the correct avenue to accomplish what I want, so I'm open to other suggestions (someone also recommended using Julia, but I've seen fewer examples of this).
has answer: http://stackoverflow.com/a/51218538
downvote count: 1
tagged with: web-hosting
tagged with: python-interactive
upvote count: 16
tagged with: ijulia-notebook
has comment: http://stackoverflow.com/comment/87190567
has comment: http://stackoverflow.com/comment/87146502
has answer: http://stackoverflow.com/a/71037637
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54148365

http://stackoverflow.com/q/49804654
has comment: http://stackoverflow.com/comment/86624427
tagged with: c++
has comment: http://stackoverflow.com/comment/86624491
has comment: http://stackoverflow.com/comment/86626096
has title: Python extension build chokes on `std::unique_ptr` on Mac
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/86624037
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86624086
has comment: http://stackoverflow.com/comment/86624274
has body: I have a toy project that's implemented as a C++ library and exposed to Python using a Cython wrapper. After not touching the project for a few months, I tried to build it from scratch today and got the following error. gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/standage/anaconda3/include -arch x86_64 -I/Users/standage/anaconda3/include -arch x86_64 -Iinc/ -I/Users/standage/anaconda3/include/python3.6m -c contra.cpp -o build/temp.macosx-10.7-x86_64-3.6/contra.o --std=c++11 -Wno-unused-function In file included from contra.cpp:506: In file included from inc/bstree.hpp:13: inc/node.hpp:20:14: error: no template named 'unique_ptr' in namespace 'std' std::unique_ptr&lt; node&lt;Data&gt; &gt; left; ~~~~~^ inc/node.hpp:21:14: error: no template named 'unique_ptr' in namespace 'std' std::unique_ptr&lt; node&lt;Data&gt; &gt; right; ~~~~~^ In file included from contra.cpp:506: inc/bstree.hpp:35:22: error: no template named 'unique_ptr' in namespace 'std' typedef std::unique_ptr&lt; node&lt;Data&gt; &gt; nodeptr; ~~~~~^ inc/bstree.hpp:22:20: error: cannot initialize a member subobject of type 'contra_cpp::bstree::nodeptr' (aka 'int') with an rvalue of type 'nullptr_t' bstree() : _root(nullptr), _count(0) {} ^ ~~~~~~~ 4 errors generated. error: command 'gcc' failed with exit status 1 The error refers to this code below (see here for full context). #include &lt;memory&gt; namespace contra_cpp { template&lt;typename Data&gt; class node { public: std::unique_ptr&lt; node&lt;Data&gt; &gt; left; std::unique_ptr&lt; node&lt;Data&gt; &gt; right; Data data; int height; node&lt;Data&gt;(Data value) : left(nullptr), right(nullptr), data(value), height(-1) {} node&lt;Data&gt;(Data value, int ht) : left(nullptr), right(nullptr), data(value), height(ht) {} }; } // namespace contra_cpp There is no error when I compile the C++ code alone, or when I build the Python extension (python setup.py install) on Ubuntu 16.04. Th…
has comment: http://stackoverflow.com/comment/86624395
has comment: http://stackoverflow.com/comment/86624576
tagged with: macos
has comment: http://stackoverflow.com/comment/86624834
favorite count: 0
has comment: http://stackoverflow.com/comment/86624391
type: Question
has comment: http://stackoverflow.com/comment/86624535
has comment: http://stackoverflow.com/comment/86624047
has comment: http://stackoverflow.com/comment/86625472
has comment: http://stackoverflow.com/comment/86630777
has comment: http://stackoverflow.com/comment/86633519
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86625904
has comment: http://stackoverflow.com/comment/87382028
tagged with: python-extensions
has comment: http://stackoverflow.com/comment/86625485
tagged with: python
has comment: http://stackoverflow.com/comment/86624700
has comment: http://stackoverflow.com/comment/86624712
has comment: http://stackoverflow.com/comment/86625416

http://stackoverflow.com/comment/86828509
score: 0
has text: What are you trying to do with `limit([randowRow], 1)`?
comment on: http://stackoverflow.com/q/49906071
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86663399
score: 0
has text: @jameslarge: Maybe it does look like one of those questions. But I don't have anyone else to discuss this problem with and understand the flaws in my code. This is the only platform I have.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49823312

http://stackoverflow.com/q/49861147
answer count: 1
tagged with: web-scraping
has body: After doing some scraping, I get all my data, store it in a pandas df but I'm having an issue when writing the header. Since I'm scraping many pages of a job site, I had to create a loop that iterates through the pages and gets a different df per page, and when it's done, I save the df to a CSV file. The problem is that the header will always be written once per iteration and I would like to only be written once.. I have tried all solutions presented on this previous question here but I still I'm not able to come with a solution to this problem. I apologize if this is a silly question but I'm still learning and loving the journey. Any help, tip, advise would be very helpful. Here's my code: def find_data(soup): l = [] for div in soup.find_all('div', class_ = 'js_result_container'): d = {} try: d["Company"] = div.find('div', class_= 'company').find('a').find('span').get_text() d["Date"] = div.find('div', {'class':['job-specs-date', 'job-specs-date']}).find('p').find('time').get_text() pholder = div.find('div', class_= 'jobTitle').find('h2').find('a') d["URL"] = pholder['href'] d["Role"] = pholder.get_text().strip() l.append(d) except: pass df = pd.DataFrame(l) df = df'Date', 'Company', 'Role', 'URL' df = df.dropna() df = df.sort_values(by=['Date'], ascending=False) df.to_csv("csv_files/pandas_data.csv", mode='a', header=True, index=False) if __name__ == '__main__': f = open("csv_files/pandas_data.csv", "w") f.truncate() f.close() query = input('Enter role to search: ') max_pages = int(input('Enter number of pages to search: ')) for i in range(max_pages): page = 'https://www.monster.ie/jobs/search/?q='+query+'&amp;where=Dublin__2C-Dublin&amp;sort=dt.rv.di&amp;page=' + str(i+1) soup = getPageSource(page) print("Scraping Page number: " + str(i+1)) find_data(soup) Output: Date,Company,Role,URL Posted today,Solas IT,QA Engineer,https://job-openings.monster.ie/QA-Engineer-Dublin-Dublin-Ireland-Solas-IT/11/195166152 Posted today,Hays Ireland,Resident Engineer,https://jo…
tagged with: beautifulsoup
has title: Pandas Dataframe - Issue when writing Header
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48053207
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/49861236
accepted answer: http://stackoverflow.com/a/49861236

http://stackoverflow.com/a/49915409
answers question: http://stackoverflow.com/q/49914086
has comment: http://stackoverflow.com/comment/86884681
has comment: http://stackoverflow.com/comment/86882347
score: 0
has body: Set the PYTHONPATH variable in your ~/.bash_profile (OSX) or ~/.bashrc (Linux) to the caffe python. export PYTHONPATH=&lt;caffe-home&gt;/python:$PYTHONPATH
type: Answer

http://stackoverflow.com/q/49857751
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/86730573
has answer: http://stackoverflow.com/a/49857980
tagged with: django-templates
score: 0
has comment: http://stackoverflow.com/comment/86730092
answer count: 1
has body: I want to loop over a queryset in a Django template like so: {% for thing in things %} //Do stuff {% endfor %} But I do not want to loop over all my "things", but rather a subset of them. Lets say my things-model has a charfield "color". Now I only want to loop over things where the color is not None. I would now create a custom queryset in my models like so: def colored_things(self): return things.objects.filter(color__isnone=False) But if I go back into my template to loop over my colored things, it behaves as if it would be empty ( the {% empty %} part of my for loop is fired). {% for thing in things %} //Do stuff {% empty %} {% endfor %} So what do I need to do to access my custom queryset (created in models, but I can put it somewhere else if it helps) in my templates?
has comment: http://stackoverflow.com/comment/86730070
has title: Accessing a custom queryset in a django template for-loop
has comment: http://stackoverflow.com/comment/86730394
type: Question
has comment: http://stackoverflow.com/comment/86730045
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/q/49838755
has body: I'm printing a dataframe using tabulate which contains a cost field but the least significant digit is blank when it's zero. I suspect the issue is related to floating point vs decimal numbers but nothing I've tried has worked. I'm not sure what the correct way to format the decimal output is. The map parameter below suggests floating point; can I convert to decimal? Here's the relevant lines of code and the output: lists['Cost_Items'] = lists['Cost_Items'].map('{0:,.2f}'.format) print(tabulate(lists, headers='keys', tablefmt='pipe', numalign='decimal', showindex=False)) | Item | Date_Purchased | Cost_Items | |:---------|:-----------------|-------------:| | Item 1 | 2018-03-31 | 10.64 | | Item 2 | 2018-03-31 | 2.48 | | Item 3 | 2018-03-31 | 3.1 | | Item 4 | 2018-03-31 | 1.78 | | Item 5 | 2018-03-31 | 2.93 | | Item 6 | 2018-03-31 | 0.5 | Any help is appreciated.
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: python pandas tabulate not printing least significant digit when zero
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49838788
has answer: http://stackoverflow.com/a/49838788
tagged with: python

http://stackoverflow.com/comment/86602144
type: QuestionComment
comment on: http://stackoverflow.com/q/49792651
has text: thanks! - that did it, brilliant
score: 0
type: Comment

http://stackoverflow.com/comment/86663193
has text: You download the .whl file. Make sure its the right python version and bit architecture. And then you just pip install the whl file. "pip install matplotlib‑2.2.2‑cp36‑cp36m‑win_amd64.whl"
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49823512

http://stackoverflow.com/comment/86585212
score: 0
comment on: http://stackoverflow.com/q/49784328
type: Comment
type: QuestionComment
has text: At the moment we aren't using bisect because they're lists of lists. Although bisect would probably be a quick improvement as well.

http://stackoverflow.com/q/49885808
type: AnsweredQuestion
has title: How can I interpolate variables in Python heredocs?
tagged with: string-interpolation
possible better answer: http://stackoverflow.com/a/49885809
tagged with: python
tagged with: heredoc
linked to: http://stackoverflow.com/q/3542714
has body: In Perl languages, I can interpolate in double quoted heredocs: Perl: #!/bin/env perl use strict; use warnings; my $job = 'foo'; my $cpus = 3; my $heredoc = &lt;&lt;"END"; #SBATCH job $job #SBATCH cpus-per-task $cpus END print $heredoc; Raku (F.K.A. Perl 6): #!/bin/env perl6 my $job = 'foo'; my $cpus = 3; my $heredoc = qq:to/END/; #SBATCH job $job #SBATCH cpus-per-task $cpus END print $heredoc; How do I do something similar in Python? In searching "heredoc string interpolation Python", I did come across information on Python f-strings, which facilitate string interpolation (for Python 3.6 and later). Python 3.6+ with f-strings: #!/bin/env python3 job = 'foo' cpus = 3 print(f"#SBATCH job {job}") print(f"#SBATCH cpus-per-task {cpus}") All three of the above produce the exact same output: #SBATCH job cutadapt #SBATCH cpus-per-task 3 That's all nice and everything, but I'm still really interested in interpolation in heredocs using Python.
favorite count: 0
upvote count: 11
type: Question
has answer: http://stackoverflow.com/a/49892463
answer count: 2
accepted answer: http://stackoverflow.com/a/49892463
has answer: http://stackoverflow.com/a/49885809
downvote count: 0
has comment: http://stackoverflow.com/comment/86788132
score: 11

vector
tags question: http://stackoverflow.com/q/49819611
tags question: http://stackoverflow.com/q/49887526
type: Tag
tag name: vector
tags question: http://stackoverflow.com/q/49889113
tags question: http://stackoverflow.com/q/49866521
tags question: http://stackoverflow.com/q/49891727

http://stackoverflow.com/comment/86796217
has text: http://www.spotrac.com/nfl/denver-broncos/peyton-manning-5028/
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49890130
score: 0

http://stackoverflow.com/comment/87148740
type: Comment
has text: Hmm, are you sure it does solve the problem? Because `pytools/nms` is not a valid package name.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49866324

http://stackoverflow.com/q/49799331
type: UnansweredQuestion
has body: I am following this tutorial on how to set up a virtual environment in Python3.6 using the windows command prompt. I had no problem generating the necessary file by running this: python3 -m venv venv-test The tutorial then advises to activate the virtual environment by running this code: venv-test/Scripts/activate But when I do this , I get the error... File "venv-test/Scripts/activate", line 4 deactivate () { ^ SyntaxError: invalid syntax I opened the generated 'activate' file and this seems to be the part that's causing the problem but I'm not sure how to correct it. deactivate () { # reset old environment variables if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then PATH="${_OLD_VIRTUAL_PATH:-}" export PATH unset _OLD_VIRTUAL_PATH fi if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}" export PYTHONHOME unset _OLD_VIRTUAL_PYTHONHOME fi Thanks in advance!
downvote count: 1
has comment: http://stackoverflow.com/comment/111500447
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49807915
has answer: http://stackoverflow.com/a/77062161
tagged with: python
has answer: http://stackoverflow.com/a/69043944
has comment: http://stackoverflow.com/comment/86613608
has answer: http://stackoverflow.com/a/50549500
has answer: http://stackoverflow.com/a/63167789
upvote count: 6
has title: When I try to activate a virtual environment with venv I get an error
has answer: http://stackoverflow.com/a/50053584
has answer: http://stackoverflow.com/a/68150100
tagged with: python-venv
answer count: 8
has answer: http://stackoverflow.com/a/63052499
tagged with: syntax-error
score: 5

http://stackoverflow.com/q/49835457
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86762651
tagged with: seaborn
type: UnansweredQuestion
tagged with: matplotlib
has title: Python - Incomplete Legend on Subplots
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/86690599
has comment: http://stackoverflow.com/comment/86690591
downvote count: 0
has body: I'm trying to add some legends to two subplots while analysing my target variable. Once I manually add the legends I can only see the first letter on each of the charts. fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(20,10)) # Normal distplot for SalePrice normal = sns.distplot(target, ax=ax[0]) normal.set_title('Normal SalePrice Distribution') norm_mu, norm_sigma = norm.fit(target) norm_legend = 'Normal dist. ($\mu=$ {:.2f} and $\sigma=$ {:.2f} )'.format(norm_mu, norm_sigma) normal.legend(norm_legend) # Log Transformation target_log = np.log(target) log_transform = sns.distplot(target_log, ax=ax[1]) log_transform.set_title('Log Transformed SalePrice Distribution') log_mu, log_sigma = norm.fit(target) log_legend = 'Log dist. ($\mu=$ {:.2f} and $\sigma=$ {:.2f} )'.format(log_mu, log_sigma) log_transform.legend(log_legend) Any ideas why this can be happening?
upvote count: 1

http://stackoverflow.com/a/49867749
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86751563
has comment: http://stackoverflow.com/comment/86751472
answers question: http://stackoverflow.com/q/49867692
has comment: http://stackoverflow.com/comment/86751677
score: 1
type: Answer
has body: It's hard to tell what the exact problem with the serialiser is without an actual error log. If you can actually open the console that django is running in, it should display the error when it occurs. From that a better diagnostic of the issue can be made. It would be wise to do this in the future otherwise questions like this will be downvoted. Yes, you can filter arrays in Javascript using the filter function. The function creates a new array by interating through the objects in the array that will be passed into a function, which should return true if it should exist in the new array or false it is shouldn't. So for the example you provided, it would appear as so: sounds = sounds.filter((sound) =&gt; { sound.id === 1; }); Note you will have to assign the new array, the original array will not change bu running the function itself. I highly recommend you search for solutions to these problems yourself before creating threads on Slack Overflow or your reputation will quickly decrease.
has comment: http://stackoverflow.com/comment/86751624
has comment: http://stackoverflow.com/comment/86751332
has comment: http://stackoverflow.com/comment/86751740

http://stackoverflow.com/q/49853395
tagged with: python
has body: Followed by tutorial: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-debian-8 I have installed Django on virtualenv and when i want to startapp i have following error: (myprojectenv) pi@raspberrypi:~/myproject $ ls db.sqlite3 manage.py myproject myprojectenv static (myprojectenv) pi@raspberrypi:~/myproject $ python manage.py startapp blog CommandError: [Errno 13] Permission denied: '/home/pi/myproject/blog' When trying type "sudo" before the command i got error like this: (myprojectenv) pi@raspberrypi:~/myproject $ sudo python manage.py startapp blog File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax How to solve this problem?
duplicate of: http://stackoverflow.com/q/42611593
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86722109
has comment: http://stackoverflow.com/comment/86722225
has comment: http://stackoverflow.com/comment/86721228
has comment: http://stackoverflow.com/comment/86721219
type: Question
has title: Django framework startapp
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42611593
tagged with: django

http://stackoverflow.com/q/49834532
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49839797
score: 1
has comment: http://stackoverflow.com/comment/86685571
answer count: 1
has title: Keras generator
upvote count: 1
tagged with: keras
favorite count: 0
type: Question
has body: I wrote my generator, but I get an error at the output def batch_generator(X_data, y_data, batch_size): samples_per_epoch = X_data.shape[0] number_of_batches = samples_per_epoch/batch_size counter=0 index = np.arange(np.shape(y_data)[0]) while 1: index_batch = index[batch_size*counter:batch_size*(counter+1)] X_batch = X_data[index_batch,:].toarray() y_batch = y_data[y_data.index[index_batch]] counter += 1 yield X_batch,y_batch if (counter &gt; number_of_batches): counter=0 Error on line: y_batch = y_data[y_data.index[index_batch]] 'numpy.ndarray' object has no attribute 'index'
type: UnansweredQuestion
tagged with: neural-network

http://stackoverflow.com/comment/86621424
type: QuestionComment
has text: @bertew Do you only want to remove _consecutive duplicates_ (ones beside each other), or does the ordering of the sublist not matter at all? i.e. should `['F', 'I', 'X']` in `['X', 'X', 'F', 'I']` be true?
score: 1
comment on: http://stackoverflow.com/q/49803339
type: Comment

http://stackoverflow.com/q/49857842
has title: How to handle ImportError: cannot import name '_ellipsoid' Keras
tagged with: image-preprocessing
answer count: 1
has body: I am getting an error which says ImportError: cannot import name '_ellipsoid' while importing "from keras.preprocessing.image import ImageDataGenerator ". Please help me to rectify this issue. I am using keras version: 2.1.5 python version: 3 Thanks in advance
tagged with: keras
type: Question
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50049749
has comment: http://stackoverflow.com/comment/86730679
score: 0
tagged with: deep-learning

http://stackoverflow.com/comment/86540030
score: 1
has text: yeah, `pandas.Series,str.extract()` will do the trick with regex to place all off those groups into different columns if it's already read in a single DataFrame column
comment on: http://stackoverflow.com/a/49762093
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49836453
has comment: http://stackoverflow.com/comment/86708047
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/86707969
has body: It should be trivial... def value(self): p = self.stock.price return p*self.number_of_stocks the related_name on a foreign key is for accessing the other end of the relationship, ie. class Stock(...): ... def some_method(self): assets = self.testName.all() if you had not defined the related_name="testName" the last line of the above would need to be assets = self.asset_set.all()
answers question: http://stackoverflow.com/q/49836355
has comment: http://stackoverflow.com/comment/86705632
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49836355

http://stackoverflow.com/q/49886416
has comment: http://stackoverflow.com/comment/86789169
has comment: http://stackoverflow.com/comment/86790956
type: Question
has comment: http://stackoverflow.com/comment/86790147
answer count: 0
downvote count: 0
tagged with: neural-network
has title: How to solve this error in using TypeError: Expected int32, got <tf.Variable 'lstm_1_W_i:0' in Keras?
type: UnansweredQuestion
tagged with: python
has body: I am training a Vanilla RNN in Keras, using LSTM cells. This is the shape of my training data. Basically 600 samples, each sample is a 2500 length vector with 100 features. &gt;&gt;&gt; training_data.shape (600, 2500, 100) Here is the start of my model definition in Keras. rnn_inputs = Input(shape=(2500, 100), dtype='int32') simple_rnn = LSTM(3, return_sequences=True,activation='relu')(rnn_inputs) The first 'rnn_inputs' runs fine, but the second line, 'simple_rnn' raises this error: TypeError: Expected int32, got &lt;tf.Variable 'lstm_1_W_i:0' shape=(100, 3) dtype=float32_ref&gt; of type 'Variable' instead. The version of Keras I am using is 1.0.7 and tensorflow version is 1.5.0. I think it has something to do with the version of these libraries though, I updated and tried it and it doesn't work. Trace --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-36-fe4504deb980&gt; in &lt;module&gt;() 2 rnn_inputs = Input(shape=(2500, 100), dtype='float64') 3 print(rnn_inputs.dtype) ----&gt; 4 simple_rnn = LSTM(3, return_sequences=True,activation='relu')(rnn_inputs) 5 #output = TimeDistributed(Dense(1, activation='sigmoid'))(simple_rnn) 6 #model = Model(inputs=rnn_inputs, outputs=output) ~/miniconda2/envs/py35/lib/python3.5/site-packages/keras/engine/topology.py in __call__(self, x, mask) 482 '`layer.build(batch_input_shape)`') 483 if len(input_shapes) == 1: --&gt; 484 self.build(input_shapes[0]) 485 else: 486 self.build(input_shapes) ~/miniconda2/envs/py35/lib/python3.5/site-packages/keras/layers/recurrent.py in build(self, input_shape) 729 self.W_o, self.U_o, self.b_o] 730 --&gt; 731 self.W = K.concatenate([self.W_i, self.W_f, self.W_c, self.W_o]) 732 self.U = K.concatenate([self.U_i, self.U_f, self.U_c, self.U_o]) 733 self.b = K.concatenate([self.b_i, self.b_f, self.b_c, self.b_o]) ~/miniconda2/envs/py35/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py in concatenate(tenso…
tagged with: keras
has comment: http://stackoverflow.com/comment/86791332
upvote count: 1
score: 1
tagged with: recurrent-neural-network
has comment: http://stackoverflow.com/comment/86790394
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/86790793
has comment: http://stackoverflow.com/comment/86791793
has comment: http://stackoverflow.com/comment/86789077

http://stackoverflow.com/comment/86726106
type: QuestionComment
has text: Welcome, can you please add the Java code of yours and maybe also the one you tried for Python, even if it is not complete.
score: 2
type: Comment
comment on: http://stackoverflow.com/q/49855782

http://stackoverflow.com/q/49863501
has comment: http://stackoverflow.com/comment/86742505
type: Question
has comment: http://stackoverflow.com/comment/86742520
tagged with: arrays
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49865953
linked to: http://stackoverflow.com/q/3966303
linked to: http://stackoverflow.com/q/4299145
tagged with: tkinter
linked to: http://stackoverflow.com/q/18471886
score: 0
answer count: 1
has body: I combined this answer &amp; this answer to come up with a script that outputs a different value every time a slider in tkinter is adjusted. It works but prints all of the values for the array and ideally only want to see the changed value. Could someone point me in the right direction? import Tkinter as tk scales=list() Nscales=10 class App: def __init__(self): self.root = tk.Tk() for i in range(Nscales): self.slider = tk.Scale(self.root, from_=1, to=5, orient=tk.HORIZONTAL) # creates widget self.slider.bind("&lt;ButtonRelease-1&gt;", self.updateValue) self.slider.pack() self.slider.set(3) scales.append(self.slider) # stores widget in scales list self.root.mainloop() def updateValue(self, event): for i in range(Nscales): print ("Scale %d has value %d" %(i,scales[i].get())) app=App()
has title: printing only the changed value from slider tkinter tk.Scale array

http://stackoverflow.com/a/49909685
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49907356
downvote count: 0
type: Answer
has body: There may be a package on PackageControl that would provide this sort of behaviour, but Sublime has nothing like that straight out of the box. Since you've mentioned that you're new to Sublime, you may not realize that the panel that you're using is perhaps more powerful and useful than you think it is. In particular, you're not constrained to typing full file names or paths in the box, and instead you can type fragments of filenames as well in order to filter the list down. For example, this code base has roughly 4,000 files in it and I want to open a file named Reader.h from the folder DevSrc/RegionalCenter/TSE/. As you've noticed, you can filter the list with a name; say I do that here: Sadly for me, it turns out that the file that I want happens to be the last one in the list, which would require some scrolling to hit the correct file. In this case, I know I want the file from the TSE folder, so I can just enter that partial path fragment before the name of the file I want, which constrains the list and brings the file I want to the top right off the bat: If you examine the results in the panel as they appear, you can see that some text in the matches is highlighted, telling you how the match is being applied. That indicates that you don't actually have to type full file names at all; just any text will work and the best matches jump to the top. So here I can easily find the Reader.h in the SIAC folder or the TSE folder even more simply: Something to note here is that along with all of the internal criteria that Sublime uses to determine what files match, your previous choices are also taken into consideration. In this case when I enter tread the Reader.h file jumps to the top; if I actually wanted the Reader.m file instead, I could add an m to the text to select it. On the other hand, if I arrow down once and hit Enter to select the file, the next time I perform the same search with the same text, the Reader.m jumps to the top of the list because I've told Subl…
score: 2
has comment: http://stackoverflow.com/comment/86835622
accepted answer of: http://stackoverflow.com/q/49907356

http://stackoverflow.com/q/49812559
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49812775
answer count: 2
has answer: http://stackoverflow.com/a/49812775
possible better answer: http://stackoverflow.com/a/49812659
has answer: http://stackoverflow.com/a/49812659
has body: I want a Factory Pattern in my python code for two different files formats. Is it OK to define a static method to choose my new class, without defining init or new in the base class? something like: Class Field(fileName): @static method def chooseClass(fileName): if '.grb' in fileName: return FieldGrib(fileName) if '.nc' in fileName: return FieldnetCDF(fileName) else: raise valueError('File format not supported') And is it possible to dynamically allocate the new class as soon as Field(fileName) is called, without calling any of the methods? The answers below do solve my problem, but I end up with a recursive loop with super, could you help me point out the problem? class Field(object): def __new__(cls, fieldFile): if '.grb' in fieldFile: return FieldGrib(fieldFile) else: raise ValueError('no support for other formats') def __init__(self, fieldFile): print fieldFile class FieldGrib(Field): def __init__(self, fieldFile): # read Field, opening fieldFile if required super(FieldGrib, self).__init__(fieldFile)
downvote count: 1
favorite count: 0
type: Question
upvote count: 0
tagged with: python
score: -1
tagged with: factory-pattern
has title: Factory pattern - choosing using static method

http://stackoverflow.com/q/49860184
has answer: http://stackoverflow.com/a/49860408
favorite count: 0
has title: New columns with other columns conditions
type: Question
possible better answer: http://stackoverflow.com/a/49860508
tagged with: python
has answer: http://stackoverflow.com/a/49860508
has comment: http://stackoverflow.com/comment/86735700
has body: &gt; df = pd.DataFrame({"A": ["2002-01-12","2002-01-12","2002-01-12","2002-01-13","2002-01-13","2002-01-13","2002-01-16","2002-01-16","2002-01-16"], "B": ["12:00:00", "13:00:00", "14:00:00","11:00:00", "12:00:00", "13:00:00", "10:00:00", "11:00:00", "12:00:00"], "C": [ 3,19, 15, 6, 1, 5, 3, 12, 8]}) A B C 0 2002-01-12 12:00:00 3 1 2002-01-12 13:00:00 19 2 2002-01-12 14:00:00 15 3 2002-01-13 11:00:00 6 4 2002-01-13 12:00:00 1 5 2002-01-13 13:00:00 5 6 2002-01-16 10:00:00 3 7 2002-01-16 11:00:00 12 8 2002-01-16 12:00:00 8 I want to create a new df['D'] and df['E'] with next conditions, per each A group: df['D']: Take C values of day before (respect A group) when B == 12:00:00 df['E']: Take C values mean of day before (respect A group). Output should be: A B C D E 0 2002-01-12 12:00:00 3 0 0 1 2002-01-12 13:00:00 19 0 0 2 2002-01-12 14:00:00 15 0 0 3 2002-01-13 11:00:00 6 3 12.3 4 2002-01-13 12:00:00 1 3 12.3 5 2002-01-13 13:00:00 5 3 12.3 6 2002-01-16 10:00:00 3 1 4.0 7 2002-01-16 11:00:00 12 1 4.0 8 2002-01-16 12:00:00 8 1 4.0
answer count: 2
has comment: http://stackoverflow.com/comment/86735750
tagged with: pandas
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/49860408
downvote count: 0

http://stackoverflow.com/a/49797333
accepted answer of: http://stackoverflow.com/q/49797288
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49797288
upvote count: 3
score: 3
has body: Use regex to get content between the curly brackets and then parse it. Demo import json import re with open('C:\\Users\\billava\\Downloads\\journal.txt', 'r') as f: data = re.findall("\{(.*?)\}", f.read()) for i in data: print json.loads("{" + i + "}") Output: {u'_BOOT_ID': u'8ee885ed17a141abb35b8ef4903e8a41', u'__MONOTONIC_TIMESTAMP': u'92587043104', u'SYSLOG_FACILITY': u'3', u'CODE_LINE': u'803', u'CODE_FUNCTION': u'job_log_status_message', u'__REALTIME_TIMESTAMP': u'1523531563940162', u'PRIORITY': u'6', u'_TRANSPORT': u'journal', u'_HOSTNAME': u'tait-uvh-7381982', u'_CAP_EFFECTIVE': u'3fffffffff', u'_SYSTEMD_UNIT': u'init.scope', u'_MACHINE_ID': u'07c42c0296d34aea8b37c0acb2c260a8', u'_PID': u'1', u'SYSLOG_IDENTIFIER': u'systemd', u'_SOURCE_REALTIME_TIMESTAMP': u'1523531563938118', u'_SYSTEMD_CGROUP': u'/init.scope', u'__CURSOR': u's=b0110bcb6bd44e8394728027cb5d82ce;i=b06;b=8ee885ed17a141abb35b8ef4903e8a41;m=158e9e2920;t=569a4d5ac3942;x=d80562ac11b34953', u'RESULT': u'done', u'MESSAGE_ID': u'39f53479d3a045ac8e11786248231fbf', u'_COMM': u'systemd', u'CODE_FILE': u'../git/src/core/job.c', u'_CMDLINE': u'/sbin/init', u'_SYSTEMD_SLICE': u'-.slice', u'UNIT': u'audiorotator.service', u'_EXE': u'/lib/systemd/systemd', u'_UID': u'0', u'MESSAGE': u'Started Rotates audio files if they have filled up above the high tide mark..', u'_GID': u'0'} {u'_BOOT_ID': u'8ee885ed17a141abb35b8ef4903e8a41', u'__MONOTONIC_TIMESTAMP': u'92590821920', u'SYSLOG_FACILITY': u'1', u'_GID': u'0', u'__REALTIME_TIMESTAMP': u'1523531567718977', u'PRIORITY': u'7', u'_TRANSPORT': u'syslog', u'_HOSTNAME': u'tait-uvh-7381982', u'_CAP_EFFECTIVE': u'3fffffffff', u'_SYSTEMD_UNIT': u'audiorotator.service', u'_MACHINE_ID': u'07c42c0296d34aea8b37c0acb2c260a8', u'_PID': u'5202', u'SYSLOG_IDENTIFIER': u'audiorotator', u'_SOURCE_REALTIME_TIMESTAMP': u'1523531567716398', u'_SYSTEMD_CGROUP': u'/system.slice/audiorotator.service', u'__CURSOR': u's=b0110bcb6bd44e8394728027cb5d82ce;i=b07;b=8ee885ed17a141abb35b8ef4903…
type: Answer

http://stackoverflow.com/q/49894471
has comment: http://stackoverflow.com/comment/86807216
has comment: http://stackoverflow.com/comment/86909638
has comment: http://stackoverflow.com/comment/86808245
has comment: http://stackoverflow.com/comment/86807430
has answer: http://stackoverflow.com/a/49899037
tagged with: django-queryset
type: UnansweredQuestion
has body: Hi I have below setup. Django 1.9, mongoDB, pymongo 2.7, mongoengine 0.9 I have written an API to store logs at backend server userwise. Below is sample of table user subject registered changed_on abc eng Y "2018-04-18T00:00:00Z" abc maths N "2018-04-18T00:10:00Z" xyz eng Y "2018-04-18T00:10:00Z" I also have read API for this in which we give user name and timestamp for filter like below: { "user" : "abc", "from_date" : "2018-04-18T00:00:00Z" } The line in serializers.py which is applying filter is Logs.objects.filter(user__iexact='abc',changed_on__gte=from_date) Now Sometimes when I add new log and retrieve it from postman, it is not working. I have to restart django server and then it gives me newly added row. I dont understand why this is happening. EDIT1 : Full Serializer.py from rest_framework import serializers class GetUserLogs(serializers.Serializer): user = serializers.CharField(label=_("USER")) token = serializers.CharField(label=_("Token")) from_date = serializers.CharField(label=_('From date'), default="") till_date = serializers.CharField(label=_('Till date'), default=datetime.datetime.now().isoformat().split(".")[0]+'Z') def validate(self, attrs): user = attrs.get('user') token = attrs.get('token') from_date = attrs.get('from_date') if user: tokendetails = validate_token(token) if not tokendetails: msg = _('Invalid token.') raise serializers.ValidationError(msg) else: userdetails = tokendetails.user if userdetails.check_user(user): rows = Logs.objects.all().filter(user__iexact=user,changed_on__gte=from_date, changed_on__lte = till_date) print(len(rows)) else: msg = _('Invalid USER) raise serializers.ValidationError(msg) else: msg = _('Must include "USER".') raise serializers.ValidationError(msg) attrs['rows'] = rows return attrs
has comment: http://stackoverflow.com/comment/86806536
tagged with: django
has comment: http://stackoverflow.com/comment/86804843
has comment: http://stackoverflow.com/comment/86807860
has comment: http://stackoverflow.com/comment/86804553
has comment: http://stackoverflow.com/comment/86809235
has comment: http://stackoverflow.com/comment/86806802
has comment: http://stackoverflow.com/comment/86806159
has comment: http://stackoverflow.com/comment/86804353
linked to: http://stackoverflow.com/q/49852738
score: 0
has comment: http://stackoverflow.com/comment/86806644
has comment: http://stackoverflow.com/comment/86807249
has comment: http://stackoverflow.com/comment/86808876
has comment: http://stackoverflow.com/comment/86812876
has comment: http://stackoverflow.com/comment/86810704
has comment: http://stackoverflow.com/comment/86806930
has comment: http://stackoverflow.com/comment/86810248
has title: Django queryset not returning all rows
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86807281
has comment: http://stackoverflow.com/comment/86804444
has comment: http://stackoverflow.com/comment/86808852
type: Question
has comment: http://stackoverflow.com/comment/86806281

http://stackoverflow.com/q/49825342
has body: I have a dataset x which is generated as a sample of a mixture of four different Gaussians: mus = [60,150,300,500] sigmas = [5,10,10,50] Ns = [380,670,440,810] Ns_rel = [i/sum(Ns) for i in Ns] x = [] for mu,sig,N in zip(mus,sigmas,Ns): x = np.append(x,st.norm(mu,sig).rvs(N)) A kernel density plot via seaborn.kdeplot(x) of the dataset x yields: The plot of the "real" density of the gaussian mixture yield -- however -- a totally different graph: x_plot = np.arange(-200,1400) y_plot = np.zeros(1600) for mu,sig,N in zip(mus,sigmas,Ns_rel): y_plot += st.norm(mu,sig).pdf(x_plot)*N Plotting the kernel-density-estimation of the sample together with the real density yields two totally different graphs: sns.kdeplot(x, label="Density Estimation of sample of Gaussian Mixture") plt.plot(x_plot,y_plot, "-", label="Real density of Gaussian Mixture") plt.legend() The Density and the Density Estimation should to be very similar, specially when there are so many samples as in my example. What did I do wrong here?
tagged with: scipy
tagged with: probability-density
type: Question
tagged with: kernel-density
has comment: http://stackoverflow.com/comment/86666710
has comment: http://stackoverflow.com/comment/86678892
type: UnansweredQuestion
has title: Density Estimator of Gaussian Mixture differs from Density Plot
tagged with: mixture
tagged with: python
has comment: http://stackoverflow.com/comment/86666999
score: 0
answer count: 0

http://stackoverflow.com/comment/86698188
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49836827
has text: I guess the reason I find the mplot3D plots appealing is that they produce vector graphics, while I think many renderers produce raster graphics. So ideally I would want to visualise shapes and surfaces and export them as vector graphics images.
type: Comment

http://stackoverflow.com/comment/86580698
type: Comment
type: QuestionComment
has text: like if you type '123123' in google, then lets say the search result is approximately 100 results I want to copy the 'approximately 100 results' or better just the '100'
comment on: http://stackoverflow.com/q/49782514
score: 0

http://stackoverflow.com/comment/86664339
type: Comment
score: 0
type: QuestionComment
has text: If you're on windows you can run this and see that all three give the same output. Or you can change "dir" to "ls" and "/D" to "-l" and "/N" to "-a" and see for yourself on any other OS. `import subprocess print("\n".join(subprocess.check_output("dir /D /N", shell=True).decode("utf-8").split(","))) print("\n".join(subprocess.check_output("dir {} {}".format("/D", "/N"), shell=True).decode("utf-8").split(","))) print("\n".join(subprocess.check_output('dir %s %s' % ("/D","/N",), shell=True).decode("utf-8").split(",")))`
comment on: http://stackoverflow.com/q/49802789

http://stackoverflow.com/q/49909153
tagged with: random-seed
has comment: http://stackoverflow.com/comment/86834712
has comment: http://stackoverflow.com/comment/86836009
type: Question
has title: Logistic Regression: how to compare predicted value with a threshold and get the classification done
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49909306
tagged with: logistic-regression
score: 0
has comment: http://stackoverflow.com/comment/86836588
tagged with: python
has body: I have this Credit Default dataset with head like this: default student balance income default_Yes No No 729.526495 44361.625074 0 No Yes 817.180407 12106.134700 0 No No 1073.549164 31767.138947 0 No No 529.250605 35704.493935 0 No No 785.655883 38463.495879 0 I am trying to perform logistic regression for 'default_Yes' based on the 'balance' attribute and used the following function: from sklearn.cross_validation import train_test_split from sklearn import metrics X = cred_def'balance' Y = cred_def['default_Yes'] X_train, X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.3,random_state=76) logist = LogisticRegression() logist.fit(X_train,Y_train) y_pred = logist.predict(X_test) def model(threshold): def_thresh = np.greater(y_pred, threshold).astype(int) acc_score = metrics.accuracy_score(Y_test, def_thresh) print(acc_score) plt.scatter(X_test.values,Y_test.values) plt.scatter(X_test.values,def_thresh) conf = metrics.confusion_matrix(Y_test, y_pred) print(conf) The problem I am facing is: no matter what value of threshold I am passing to the function 'model', it's producing same output and not considering the value passed.

http://stackoverflow.com/q/49758348
upvote count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/49350221
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49763176
possible better answer: http://stackoverflow.com/a/49758686
has answer: http://stackoverflow.com/a/49763176
has answer: http://stackoverflow.com/a/49758686
has answer: http://stackoverflow.com/a/50300378
tagged with: django
tagged with: python
tagged with: facebook-login
has answer: http://stackoverflow.com/a/77890569
answer count: 4
has body: I´m doing a small project that requires login with facebook. I´m working locally, on https://localhost:8000/ The technologies used are Django 2.0, django-allauth and, in order to avoid an error that I was having for not using an SSL connection, I´m using Django-sslserver as a development server. When I click on the facebook-login button on my website, I´m bein redirected to this address: https://www.facebook.com/v2.12/dialog/oauth?client_id=160259374640207&redirect_uri=https%3A%2F%2Flocalhost%3A8000%2Fsocial-auth%2Ffacebook%2Flogin%2Fcallback%2F&scope=email+user_friends+public_profile&response_type=code&state=pavN29C9zMgo&auth_type=reauthenticate I´m having this error: Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. Part of my settings.py file: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['mysite.com', 'localhost'] # Application definition INSTALLED_APPS = [ # My Apps 'account', # Django Apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # Third party Apps 'sslserver', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_social_website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPT…
type: AnsweredQuestion
score: 3
has title: Django 2.0 - Facebook login with allauth - Can't Load URL: The domain of this URL isn't included in the app's domains
tagged with: django-allauth

http://stackoverflow.com/q/49858760
has title: Execute python scripts from bash file via crontab
tagged with: macos
has body: Set-up I have 2 simple python 3.x files on my desktop: 1) cronjob_test.py #!Applications/anaconda/bin/python # -*- coding: utf-8 -*- import os os.makedirs('/Users/myself/Desktop/TESTFOLDER') 2) cronjob_test_copy.py #!Applications/anaconda/bin/python # -*- coding: utf-8 -*- import os os.makedirs('/Users/myself/Desktop/TESTFOLDER2') Both .py are executed via bashfile A, #!/bin/bash cd /Users/myself/Desktop PATH=$PATH:/usr/local/bin export PATH /Applications/anaconda/bin/python cronjob_test.py /Applications/anaconda/bin/python cronjob_test_copy.py Problem When I execute bash file A from the MacOSX Terminal, everything works fine: I end up with the 2 folders on my desktop. However, when I try to execute A from crontab, nothing happens. My crontab command is, 25 15 * * * cd /Users/myself/Desktop ** bash A What am I doing wrong?
has comment: http://stackoverflow.com/comment/86732462
type: Question
has comment: http://stackoverflow.com/comment/86732388
tagged with: cron
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86732429
has comment: http://stackoverflow.com/comment/86732497
tagged with: bash
score: 0
answer count: 0

http://stackoverflow.com/a/49845020
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49842069
type: Answer
has body: This solution uses only pandas and numpy. Since pandas stores data in numpy arrays, there's no reason you should avoid using numpy functionality. import pandas as pd, numpy as np A = np.array(['this', 'is', 'not', 'working']) sizes = np.array([1, 0, 3]) df = pd.DataFrame({'utterances': utterance_list}) df['utterances'] = np.split(A, sizes.cumsum()) print(df) # utterances # 0 [this] # 1 [] # 2 [is, not, working] # 3 []
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49842069
downvote count: 0

http://stackoverflow.com/comment/86786403
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49884886
type: AnswerComment
has text: that is what I mentioned in my question itself. As I said take **minLineLength** to be **100**. It is giving better results than your code but lines are still incomplete and faded.

http://stackoverflow.com/a/49899583
has body: dataframe .withColumn('address_unique', your_function('address')) .groupBy('address_unique') .agg(collect_list('names'), collect_list('DoB')) UPD: A) find similarities between addresses and put it into separate dataset: Address1, Address2. adr_map = df.alias('a').join(df.alias('b'), on = (is_same(col('a.address'), col('b.address'))) &amp;&amp; (col('a.s_no') &gt; col('b.s_no')), how = 'left' ).select(col('a.address').alias('a1'), col('b.address').alias(a2)).filter(col('a2').isNotNull()) B) join original dataset with mapping dataset and add column with "first address" that is common for all same addresses. df.join(adr_map, on = col('address') == col('a2'), how='left') .withColumn('first_address', when(col('a1').isNull(), 'address').otherwise(col('a1'))) C) group by first_address ... NB: it does not cover scenario that was described in comment above. In case if your function is not perfect enough and does not cover transitive relations, you will see different groups. if A1 = A2 and A2 = A3 then A1 should be equals A3. There will be some other edge cases to cover (there will be duplicated in your output), but hopefully you've got an idea and can go from it.
type: Answer
answers question: http://stackoverflow.com/q/49898955
score: 0
has comment: http://stackoverflow.com/comment/86814539

http://stackoverflow.com/comment/86756381
type: Comment
has text: Because "html/body/footer/div/div[1]/section/div/div/div[2]/div[1]/ul/li[9]/div/div/a this Xpath has some serious issue .
comment on: http://stackoverflow.com/a/49855949
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86573806
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49778816
type: QuestionComment
has text: PS: Django does create objects in your DB (as you can see from `Product.objects.all()`). Probably it is just a problem with the raw query in the shell.

http://stackoverflow.com/a/49870158
downvote count: 0
has comment: http://stackoverflow.com/comment/86757202
has comment: http://stackoverflow.com/comment/86756099
type: Answer
has comment: http://stackoverflow.com/comment/86756433
answers question: http://stackoverflow.com/q/49869887
has comment: http://stackoverflow.com/comment/86756063
score: 2
upvote count: 2
has body: Assuming the following list to be your multi-label targets: 107 RA37|RA41|RM153 |RWT037 108 DA35|DA47|DWT030|DA35|DA47|DWT030 109 NaN 110 PI001 |PI040 111 PI001 |PI040 112 RA37|RA41|RWT037 113 DA35|DA47|DWT030|DA35|DA47|DWT030 114 NaN Part 1: Handling the Nan: There are multiple ways to handle the Nans: 1) 'Nan' as target doesnt make sense. If you dont know what the target is, how will you train the model for that and how will you compare it to output. So the solution here is to remove the complete samples (rows) which have Nans in it. So the resultant targets will look like this: 107 RA37|RA41|RM153 |RWT037 108 DA35|DA47|DWT030|DA35|DA47|DWT030 110 PI001 |PI040 111 PI001 |PI040 112 RA37|RA41|RWT037 113 DA35|DA47|DWT030|DA35|DA47|DWT030 2) Replace the Nan with a new label, something like Unknown or Unclassified. 107 RA37|RA41|RM153 |RWT037 108 DA35|DA47|DWT030|DA35|DA47|DWT030 109 UNKNOWN 110 PI001 |PI040 111 PI001 |PI040 112 RA37|RA41|RWT037 113 DA35|DA47|DWT030|DA35|DA47|DWT030 114 UNKNOWN Part 2: Using MultiLabelBinarizer: In both the above solutions, you will get a list of targets something like this: y = ['RA37|RA41|RM153|RWT037', 'DA35|DA47|DWT030|DA35|DA47|DWT030', 'UNKNOWN', 'PI001|PI040', 'PI001|PI040', 'RA37|RA41|RWT037', 'DA35|DA47|DWT030|DA35|DA47|DWT030', 'UNKNOWN'] But MultilabelBinarizer accepts a list of list, so we need to split the above strings as you were doing: y = [y_val.split('|') for y_val in y] Now y is in correct format. Now use the MLB: from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() y_encoded = mlb.fit_transform(y) # Output: array([[0, 0, 0, 0, 0, 1, 1, 1, 1, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 0, 1, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]]) You this can be used in a model of your choice (which should support the indicator matrix format above) for y.
has comment: http://stackoverflow.com/comment/86756183

http://stackoverflow.com/a/72730790
score: 1
downvote count: 0
upvote count: 1
has body: try 'cp1252', works fine for me for all French chars
type: Answer
answers question: http://stackoverflow.com/q/49898909

http://stackoverflow.com/q/49799700
has comment: http://stackoverflow.com/comment/86616794
has comment: http://stackoverflow.com/comment/86614484
has comment: http://stackoverflow.com/comment/86614833
has comment: http://stackoverflow.com/comment/86616206
has comment: http://stackoverflow.com/comment/86615929
tagged with: performance
has comment: http://stackoverflow.com/comment/86614600
has comment: http://stackoverflow.com/comment/86614763
has comment: http://stackoverflow.com/comment/86614831
has comment: http://stackoverflow.com/comment/86615725
has comment: http://stackoverflow.com/comment/86614420
has body: I'm iterating over the files in a folder and all subdirectories and then getting the hash of the file. Seems basic. In this example, there are 1036 total files. When I run this there will be 75,000 (or so) files The code flies over the iterations as expected until we get into the late 900s in the file counter. The issue is easy to isolate to the binary read. Chunk size of the read (1024 vs 4096 vs 65536) does make a difference If I run from the CMD line, the code executes the first 950 or so lines rapidly (~2 seconds) and then pauses on various files (not the same one all the time) and take about 20 seconds on avg to finish the file 75 files. In PyCharm iterating over the 1036 files takes about 2:20 (seriously) on average This code is pretty simple. What's the issue? (and please excuse the non-orthodox pythonic naming standards at this point) import os import hashlib from datetime import datetime def hash_file(filename): # make a hash object # the chance of a hash collision with sha1 or MD5 is minimal but I'm using sha256 because memory is plentiful h = hashlib.sha256() try: # open file for reading in binary mode - binary mode is a must with open(filename,'rb') as file: # loop till the end of the file fileChunk = None while fileChunk != b'': # read only 1024 bytes at a time #fileChunk = file.read(1024) # read only 4096 bytes at a time #fileChunk = file.read(4096) # read only 65536 bytes at a time fileChunk = file.read(65536) h.update(fileChunk) # the entire absolute path and file name print (os.path.realpath(file.name)) # e.g exampe "/Users/testuser/PycharmProjects/test2/Examples/brianshirt_1.jpg" # return the hex representation of digest return h.hexdigest() except IOError as ioe: print("\n\nfile %s could not be opened" % filename) return "Error" finally: file.close() startTime = datetime.now() fileCounter = 0 #rootDir = '.' rootDir = '/Users/testuser/Downloads' for dirName, subdirList, fileList in os.walk(rootDir, topdown=False): print('Found directory: %s' % dirN…
has comment: http://stackoverflow.com/comment/86615050
tagged with: python
has comment: http://stackoverflow.com/comment/86614161
has comment: http://stackoverflow.com/comment/86614544
favorite count: 0
type: Question
upvote count: 2
score: 2
has title: Poor performance in Python with Binary Read of files in a loop
has comment: http://stackoverflow.com/comment/86614402
has comment: http://stackoverflow.com/comment/86616092
has comment: http://stackoverflow.com/comment/86614929
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86614605
has comment: http://stackoverflow.com/comment/86614635

http://stackoverflow.com/comment/86645905
type: AnswerComment
score: 0
has text: Use `data={"key":"value"}` not `data = '{"key":"value"}'`. You've to use a dictionary, not a string.
comment on: http://stackoverflow.com/a/49802513
type: Comment

http://stackoverflow.com/q/49853843
type: Question
upvote count: 2
tagged with: numpy
score: 0
downvote count: 2
has answer: http://stackoverflow.com/a/49856382
answer count: 1
has comment: http://stackoverflow.com/comment/86722340
favorite count: 0
tagged with: matlab
type: AnsweredQuestion
has body: I'm trying to translate a Matlab script into Numpy. This is part of the Matlab code: function [idx,D]=knnsearch(varargin) [N,M] = size(Q); L=size(R,1); idx = zeros(N,K); D = idx; for k=1:N d=zeros(L,1); for t=1:M d=d+(R(:,t)-Q(k,t)).^2; end d(k)=inf; [D(k),idx(k)]=min(d); end where Q and R are matrices that can be considered e.g. as eye(5); you can consider K = 1. An example function call could be: Q = eye(5); R = eye(5); [idx,D] = knnsearch(Q,R,1); which returns: idx: 2 1 1 1 1 D: 2 2 2 2 2 This is the Numpy code: import numpy as np def knnsearch(Q, R, K): (N,M) = Q.shape L = len(R[:,1]) idx = np.zeros((N,K), dtype=int) D = np.copy(idx) for k in range(0, N): d = np.zeros((L, 1)) for t in range(0, M): d = d + (R[:,t] - Q[k,t])**2 d[k] = np.inf idx[k] = np.argmin(d) D[k] = np.amin(d) return (idx, D) where Q0 = np.identity(5) R0 = np.identity(5) idxout, Dout = knnsearch(Q0, R0, 1) This returns different from Matlab: idx: [[5] [1] [2] [3] [4]] D: [[0] [0] [0] [0] [0]] There is a problem with the row number 9. The second part of the row, the scalar ((R(:,t)-Q(k,t)).^2), returns the same values for both Matlab and Numpy. Instead, the addition (d + scalar) returns different values. So, the matrix d contains different values in Matlab and Numpy. Thanks in advance.
accepted answer: http://stackoverflow.com/a/49856382
has comment: http://stackoverflow.com/comment/86722986
has title: Matlab to Numpy translation - matrix + scalar differences
has comment: http://stackoverflow.com/comment/86723152
tagged with: python
has comment: http://stackoverflow.com/comment/86723375

http://stackoverflow.com/a/49764961
type: Answer
has body: mydict = {'frc1':40,'frc2':2,'frc3':1,'frc4':3} for key, value in sorted(mydict.iteritems(), key=lambda (k,v): (k[3:], v)): print "%s: %s" % (key, value) Output: frc1: 40 frc2: 2 frc3: 1 frc4: 3 This should work, if I undestand your problem correctly :) lambda functions are quite magical
score: 0
answers question: http://stackoverflow.com/q/49764897

http://stackoverflow.com/q/49797291
tagged with: keras
tagged with: tensorflow
has answer: http://stackoverflow.com/a/49798062
favorite count: 0
type: Question
has title: LSTM - time series predictions
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52532726
has answer: http://stackoverflow.com/a/49799893
tagged with: lstm
score: 0
answer count: 3
upvote count: 1
downvote count: 1
tagged with: machine-learning
has body: I am following this tutorial LSTM and I wonder how to map this to a multi-time series input. I have a dataset of several time-series and I want to predict for each time series the future. I don't know how to scale LSTM to several time-series. The aim is to avoid to make a model for each time series as I have 40k of time series. Thank you

http://stackoverflow.com/comment/86810126
type: AnswerComment
score: 0
has text: Thanks a lot for the suggestion, but I'd rather avoid using this technique, as I can't be sure of how many different tags there may be for text in these files (there are 4000 files). The most common tags seem to be <w> and <mw>, but there may be others and I wouldn't want to take the risk to lose some parts because of tags I wouldn't be aware of. This is why I'd like to make the 'strip_elements' function work instead.
comment on: http://stackoverflow.com/a/49880482
type: Comment

http://stackoverflow.com/comment/113192363
comment on: http://stackoverflow.com/a/63938150
score: 0
type: Comment
type: AnswerComment
has text: Thanks. That's a smart way to do it. Though there are limitations and will not be a full fledged solution anyway.

http://stackoverflow.com/comment/135173532
comment on: http://stackoverflow.com/a/49810617
score: 1
type: Comment
has text: @SolomidHero in this answer `cdef cppclass Coordinate` so it is a C++-object. If you have something different (i.e. a C-pointer), use free or whatever needs to be used.
type: AnswerComment

http://stackoverflow.com/q/49827107
tagged with: matplotlib
favorite count: 0
type: Question
answer count: 2
has body: I'm trying to graph some functions which for some reason look like they are composed of smaller fuzzy lines instead of being single lines. The four functions on these two graphs are simply lists of numbers that I created in a for loop. for i in range(iters): #zero the gradients amsgrad.zero_grad() adam.zero_grad() #Perform an optimization step adam.step(closure_adam) amsgrad.step(closure_amsgrad) #Clamp the variables between -1 and 1 x_var_adam.data = x_var_adam.data.clamp(-1,1) x_var_amsgrad.data = x_var_amsgrad.data.clamp(-1,1) #Calculate the regret adam_regret = regret(total_loss_adam,total_min_loss_adam,t) ams_regret = regret(total_loss_amsgrad,total_min_loss_amsgrad,t) #Store regret regret_adam_hist.append(adam_regret) regret_amsgrad_hist.append(ams_regret) #Store the x_t values x_var_adam_hist.append(x_var_adam.data[0]) x_var_amsgrad_hist.append(x_var_amsgrad.data[0]) #Adjust learning rate by dividing by sqrt(t) adjust_learning_rate(adam,my_lr,t) adjust_learning_rate(amsgrad,my_lr,t) t+=1 # this is the second photo x = np.arange(0,iters) plt.clf() plt.xlabel("Iterations") plt.ylabel("$R_t/t$") plt.plot(x,regret_adam_hist, label="adam", c='b', ls='--') plt.plot(x,regret_amsgrad_hist,label="amsgrad",c='g') plt.axis([0, iters, 0, 0.5]) plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) plt.legend(loc='best') plt.rcParams["figure.figsize"] = (15,10) plt.show() plt.clf() # this is the first photo x = np.arange(0,iters+1) plt.plot(x, x_var_adam_hist, label="adam", c='b', ls='--') plt.xlabel("Iterations") plt.ylabel("$x_t$") plt.plot(x, x_var_amsgrad_hist, label="amsgrad", c='g', ls='dotted') plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) plt.rcParams["figure.figsize"] = (15,10) plt.legend(loc='best') plt.show() I'm not sure why pyplot is giving me these graphs that look like it's calculating multiple lines. This is the regret function that is being plotted above: These should all look like smooth lines. I've checked the following: for n in re…
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86670089
has title: pyplot is creating many different lines
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/49829516
accepted answer: http://stackoverflow.com/a/49832743
has answer: http://stackoverflow.com/a/49829516
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49832743
has comment: http://stackoverflow.com/comment/86669997

http://stackoverflow.com/comment/86682030
comment on: http://stackoverflow.com/q/49833341
type: Comment
has text: Did you try to inspect(print) the data at the point of the exception? Work *backwards* from there.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86711817
type: Comment
type: QuestionComment
score: 0
has text: Hi, @viraptor, thanks very much for your reply! I've uploaded an image. Please have a check.
comment on: http://stackoverflow.com/q/49848500

http://stackoverflow.com/q/49879769
has answer: http://stackoverflow.com/a/49880139
has title: can we call a python file consisting of only function definition as a script?
linked to: http://stackoverflow.com/q/2996110
score: 2
has comment: http://stackoverflow.com/comment/86775247
upvote count: 3
tagged with: scripting
has comment: http://stackoverflow.com/comment/86775410
downvote count: 1
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49879822
has comment: http://stackoverflow.com/comment/86775533
has comment: http://stackoverflow.com/comment/86775229
has body: If there is a file in python with a function definition only and i don't call that function in that file.. is it a script or module? For eg:- def func(): print('Hey')
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/86813283
has text: If someone suffers from slicing-allergy, maybe should he switch from Python to C ;-)
type: AnswerComment
comment on: http://stackoverflow.com/a/49898673
score: 0
type: Comment

http://stackoverflow.com/comment/86575577
comment on: http://stackoverflow.com/a/49777827
score: 0
type: Comment
has text: And getting this error: `filters = int((filters / absMax) * 255) TypeError: only length-1 arrays can be converted to Python scalars`
type: AnswerComment

http://stackoverflow.com/q/49769623
tagged with: python-2.7
has title: process failed exception when running Python via laravel
answer count: 0
has comment: http://stackoverflow.com/comment/86560632
has comment: http://stackoverflow.com/comment/86560027
has comment: http://stackoverflow.com/comment/86556243
downvote count: 0
has comment: http://stackoverflow.com/comment/86558891
tagged with: cmd
has comment: http://stackoverflow.com/comment/86556598
linked to: http://stackoverflow.com/q/818255
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/41020068
has comment: http://stackoverflow.com/comment/86558276
has comment: http://stackoverflow.com/comment/86559544
has comment: http://stackoverflow.com/comment/86560051
has comment: http://stackoverflow.com/comment/86554345
has comment: http://stackoverflow.com/comment/86554665
has comment: http://stackoverflow.com/comment/86557707
has comment: http://stackoverflow.com/comment/86560119
has comment: http://stackoverflow.com/comment/86560325
has body: I'm trying to run python script via laravel using symfony process but when i run it I get this error: 'Python' is not recognized as an internal or external command, operable program or batch file. I tried to run the python script with cmd and it run and return the result my laravel code is this: ` $text="I luv my &amp;lt;3 iphone &amp;amp; you're awsm apple. DisplayIsAwesome, sooo happppppy http://www.apple.com"; $process=new Process("Python C:\Users\Bcc\PycharmProjects\twitter-data\Car.py \"{$text}\""); $process-&gt;run(); if (!$process-&gt;isSuccessful()){ throw new ProcessFailedException($process); } var_dump($process-&gt;getOutput()); die(); ` I run this command on cmd: Python C:\Users\Bcc\PycharmProjects\twitter-data\Car.py "I luv my &lt;3 iphone &amp; you're awsm apple. DisplayIsAwesome, sooo happppppy http://www.apple.com" EDIT: Problem Solved.I move python script to controllers folder and use shell_exec ,so just replace that code with this $text="I luv my &amp;lt;3 iphone &amp;amp; you're awsm apple. DisplayIsAwesome, sooo happppppy http://www.apple.com"; $result = shell_exec("python ". app_path()."\Http\Controllers\Car.py " . escapeshellarg($text)); var_dump($result); die();
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86563614
has comment: http://stackoverflow.com/comment/86555139
tagged with: python
has comment: http://stackoverflow.com/comment/86554444
has comment: http://stackoverflow.com/comment/86586018
tagged with: laravel
score: 2

http://stackoverflow.com/q/49805945
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86626694
has comment: http://stackoverflow.com/comment/88660116
has comment: http://stackoverflow.com/comment/86628351
has answer: http://stackoverflow.com/a/66079635
tagged with: scikit-learn
tagged with: imputation
has comment: http://stackoverflow.com/comment/86728446
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/60971943
has comment: http://stackoverflow.com/comment/88652546
has answer: http://stackoverflow.com/a/49806113
score: 5
has comment: http://stackoverflow.com/comment/88652516
tagged with: dataframe
tagged with: python
upvote count: 6
has body: Is it possible to impute values for a specific column? For example, if I have 3 columns: A (categorical): does not contain any missing values B (numeric): does not contain any missing values C: suppose this column contains numerics data and some of them are missing . I want to do the imputation only in this column.
has comment: http://stackoverflow.com/comment/86626728
type: Question
answer count: 3
tagged with: pandas
has title: Scikit-learn - Impute values in a specific column

http://stackoverflow.com/comment/86697896
type: Comment
comment on: http://stackoverflow.com/q/49841597
score: 0
type: QuestionComment
has text: Are you sure `quality='keep'` is valid? The [jpg format docs](http://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#jpeg) say that `quality` should be a number.

tensorflow
tags question: http://stackoverflow.com/q/49843345
tags question: http://stackoverflow.com/q/49872357
type: Tag
tags question: http://stackoverflow.com/q/49877422
tags question: http://stackoverflow.com/q/49768997
tags question: http://stackoverflow.com/q/49854778
tags question: http://stackoverflow.com/q/49812488
tags question: http://stackoverflow.com/q/49899526
tags question: http://stackoverflow.com/q/49901661
tags question: http://stackoverflow.com/q/49889385
tags question: http://stackoverflow.com/q/49837857
tags question: http://stackoverflow.com/q/49819148
tags question: http://stackoverflow.com/q/49793300
tags question: http://stackoverflow.com/q/49890477
tags question: http://stackoverflow.com/q/49765265
tags question: http://stackoverflow.com/q/49832900
tags question: http://stackoverflow.com/q/49807789
tags question: http://stackoverflow.com/q/49900798
tags question: http://stackoverflow.com/q/49765144
tags question: http://stackoverflow.com/q/49864234
tags question: http://stackoverflow.com/q/49865446
tags question: http://stackoverflow.com/q/49825590
tags question: http://stackoverflow.com/q/49805206
tags question: http://stackoverflow.com/q/49782292
tags question: http://stackoverflow.com/q/49824281
tags question: http://stackoverflow.com/q/49847523
tags question: http://stackoverflow.com/q/49915600
tags question: http://stackoverflow.com/q/49910880
tags question: http://stackoverflow.com/q/49821735
tags question: http://stackoverflow.com/q/49865478
tags question: http://stackoverflow.com/q/49882897
tags question: http://stackoverflow.com/q/49797291
tags question: http://stackoverflow.com/q/49883861
tags question: http://stackoverflow.com/q/49790152
tags question: http://stackoverflow.com/q/49853772
tags question: http://stackoverflow.com/q/49781923
tags question: http://stackoverflow.com/q/49805375
tags question: http://stackoverflow.com/q/49805955
tags question: http://stackoverflow.com/q/49828011
tags question: http://stackoverflow.com/q/49813458
tags question: http://stackoverflow.com/q/49800295
tags question: http://stackoverflow.com/q/49784472
tags question: http://stackoverflow.com/q/49862136
tags question: http://stackoverflow.com/q/49902780
tags question: http://stackoverflow.com/q/49890278
tags question: http://stackoverflow.com/q/49834380
tags question: http://stackoverflow.com/q/49809148
tags question: http://stackoverflow.com/q/49761816
tags question: http://stackoverflow.com/q/49770934
tags question: http://stackoverflow.com/q/49879873
tags question: http://stackoverflow.com/q/49882424
tags question: http://stackoverflow.com/q/49849185
tags question: http://stackoverflow.com/q/49893741
tags question: http://stackoverflow.com/q/49835838
tags question: http://stackoverflow.com/q/49822322
tags question: http://stackoverflow.com/q/49906434
tags question: http://stackoverflow.com/q/49775515
tags question: http://stackoverflow.com/q/49892136
tags question: http://stackoverflow.com/q/49797450
tags question: http://stackoverflow.com/q/49841971
tags question: http://stackoverflow.com/q/49873594
tags question: http://stackoverflow.com/q/49777020
tags question: http://stackoverflow.com/q/49767233
tags question: http://stackoverflow.com/q/49782180
tags question: http://stackoverflow.com/q/49811350
tags question: http://stackoverflow.com/q/49813577
tags question: http://stackoverflow.com/q/49889641
tags question: http://stackoverflow.com/q/49789478
tags question: http://stackoverflow.com/q/49880372
tags question: http://stackoverflow.com/q/49811006
tags question: http://stackoverflow.com/q/49886574
tags question: http://stackoverflow.com/q/49887325
tags question: http://stackoverflow.com/q/49845685
tags question: http://stackoverflow.com/q/49838852
tags question: http://stackoverflow.com/q/49904556
tags question: http://stackoverflow.com/q/49893201
tags question: http://stackoverflow.com/q/49853718
tags question: http://stackoverflow.com/q/49852241
tags question: http://stackoverflow.com/q/49799424
tags question: http://stackoverflow.com/q/49880700

bitwise-xor
tags question: http://stackoverflow.com/q/49864714
tag name: bitwise-xor
type: Tag

http://stackoverflow.com/comment/86736050
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49835272
has text: using Raw sql should not be causing this error

pipeline
type: Tag
tags question: http://stackoverflow.com/q/49916196
tags question: http://stackoverflow.com/q/49777173
tags question: http://stackoverflow.com/q/49770851
tag name: pipeline
tags question: http://stackoverflow.com/q/49779027

http://stackoverflow.com/comment/86817124
has text: Thank you so much Peko, it works! Now all i have to do is figure out how to loop the video until the song ends so the video can end and return to another script
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49878803

http://stackoverflow.com/q/49827911
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/22701799
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/86672301
score: 3
duplicate of: http://stackoverflow.com/q/22701799
tagged with: pandas
has title: Check Equality of Multiple Columns in a Pandas DataFrame
has body: data = [[10,10,10],[12,12,12],[10,12,10]] df = DataFrame(data,columns=['Col1','Col2','Col3']) df Col1 Col2 Col3 0 10 10 10 1 12 12 12 2 10 12 10 I need something that would return - True, True, False. This was an example. My data has 20 columns that need this check. How can I do it?
favorite count: 0
type: Question
upvote count: 4

numpy
tags question: http://stackoverflow.com/q/49809095
tags question: http://stackoverflow.com/q/49869622
tags question: http://stackoverflow.com/q/49903247
tags question: http://stackoverflow.com/q/49784784
tags question: http://stackoverflow.com/q/49891074
tags question: http://stackoverflow.com/q/49897968
tags question: http://stackoverflow.com/q/49895663
tags question: http://stackoverflow.com/q/49762240
tags question: http://stackoverflow.com/q/49847143
tags question: http://stackoverflow.com/q/49899310
tags question: http://stackoverflow.com/q/49805647
tags question: http://stackoverflow.com/q/49885181
tags question: http://stackoverflow.com/q/49880575
tags question: http://stackoverflow.com/q/49787422
tags question: http://stackoverflow.com/q/49897926
tags question: http://stackoverflow.com/q/49803899
tags question: http://stackoverflow.com/q/49830644
tags question: http://stackoverflow.com/q/49866263
tags question: http://stackoverflow.com/q/49909773
tags question: http://stackoverflow.com/q/49820329
tags question: http://stackoverflow.com/q/49773143
tags question: http://stackoverflow.com/q/49760092
tags question: http://stackoverflow.com/q/49805576
tags question: http://stackoverflow.com/q/49821169
tags question: http://stackoverflow.com/q/49833144
tags question: http://stackoverflow.com/q/49828554
tags question: http://stackoverflow.com/q/49797287
tags question: http://stackoverflow.com/q/49869644
tags question: http://stackoverflow.com/q/49857395
tags question: http://stackoverflow.com/q/49884353
tags question: http://stackoverflow.com/q/49863276
tags question: http://stackoverflow.com/q/49908788
tags question: http://stackoverflow.com/q/49903830
tags question: http://stackoverflow.com/q/49915894
tags question: http://stackoverflow.com/q/49812284
tags question: http://stackoverflow.com/q/49833270
tags question: http://stackoverflow.com/q/49903037
tags question: http://stackoverflow.com/q/49789861
tags question: http://stackoverflow.com/q/49759710
tags question: http://stackoverflow.com/q/49783757
tags question: http://stackoverflow.com/q/49867945
tags question: http://stackoverflow.com/q/49776493
tags question: http://stackoverflow.com/q/49857526
tags question: http://stackoverflow.com/q/49869287
tags question: http://stackoverflow.com/q/49878041
tags question: http://stackoverflow.com/q/49910665
tags question: http://stackoverflow.com/q/49841917
tags question: http://stackoverflow.com/q/49798358
tags question: http://stackoverflow.com/q/49853783
tags question: http://stackoverflow.com/q/49836933
tags question: http://stackoverflow.com/q/49844496
tags question: http://stackoverflow.com/q/49855586
tags question: http://stackoverflow.com/q/49768306
tags question: http://stackoverflow.com/q/49872695
tags question: http://stackoverflow.com/q/49769335
tags question: http://stackoverflow.com/q/49841378
tags question: http://stackoverflow.com/q/49762450
tags question: http://stackoverflow.com/q/49913275
tags question: http://stackoverflow.com/q/49853843
tags question: http://stackoverflow.com/q/49905558
tags question: http://stackoverflow.com/q/49775405
tags question: http://stackoverflow.com/q/49822572
tags question: http://stackoverflow.com/q/49846246
tags question: http://stackoverflow.com/q/49891302
tags question: http://stackoverflow.com/q/49868846
tags question: http://stackoverflow.com/q/49798451
tags question: http://stackoverflow.com/q/49847548
tags question: http://stackoverflow.com/q/49844327
tags question: http://stackoverflow.com/q/49817025
tags question: http://stackoverflow.com/q/49820999
tags question: http://stackoverflow.com/q/49884600
tags question: http://stackoverflow.com/q/49824338
tags question: http://stackoverflow.com/q/49904296
tags question: http://stackoverflow.com/q/49774179
tags question: http://stackoverflow.com/q/49778594
tags question: http://stackoverflow.com/q/49846534
tags question: http://stackoverflow.com/q/49862153
tags question: http://stackoverflow.com/q/49850429
tags question: http://stackoverflow.com/q/49775571
tags question: http://stackoverflow.com/q/49763277

http://stackoverflow.com/comment/86606557
type: Comment
score: 0
has text: yes, depending on how you intend to use the methods from each file there are other workarounds, but they are not good practice, such as instead of imports at the start of the file, import just before you need it (inside functions or class functions that are not executed at time of import) but this doesn't allow you to do things like subclassing
type: QuestionComment
comment on: http://stackoverflow.com/q/49795985

http://stackoverflow.com/comment/86702986
comment on: http://stackoverflow.com/q/49844189
type: Comment
type: QuestionComment
score: 0
has text: No. When you save the plot it becomes an image.

http://stackoverflow.com/comment/86745691
comment on: http://stackoverflow.com/q/49865101
type: Comment
type: QuestionComment
has text: `all_customer` or `all_customers`? note that your list is empty, this is so wrong...
score: 0

http://stackoverflow.com/q/49763583
tagged with: pyinstaller
score: 1
tagged with: python
has body: I'm trying to compile my code in oython that uses the library langdetect into a .app with pyinstaller. as answered in this question : https://github.com/pyinstaller/pyinstaller/issues/2680 I modified the .spec file to include this : a = Analysis( # your other stuff here... datas=[ ('langdetect/utils', 'langdetect/utils'), # for messages.properties file ('langdetect/profiles', 'langdetect/profiles'), # don't forget if you load langdetect as a submodule of your app, change the second string to the relative path from your parent module. The first argument is the relative path inside the pyinstaller bundle. ] # the rest of your analysis spec... ) But pyinstaller stil does not find utils. I think that I didn't enter the right path in the tuple, but I don't know what I'm supposed to do (the program is supposed to already 'be' in the libraries directory, so shouldn't it work in theory ?) I used anaconda anaconda to install langdetect. The problem is that I'm not using my laptop to build the .app file, so I would refer if it's a generic path rather than specific. thanks !
favorite count: 0
type: Question
has title: Langdetect Issue With pyinstaller
has answer: http://stackoverflow.com/a/62138950
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86827819
has text: I solved the problem, when ı try to code my app with python 2.7 it is created succesfully, thank you for your help.
comment on: http://stackoverflow.com/q/49887142
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86827689
comment on: http://stackoverflow.com/a/49903333
type: Comment
score: 0
type: AnswerComment
has text: @Javier I'm even more confused, since my example does run a server in a separate thread. Can you show both the production code and the test code that you would like this mock server to be used with?

http://stackoverflow.com/comment/86639567
type: QuestionComment
comment on: http://stackoverflow.com/q/49812521
score: 0
has text: do you have the same python version on your friend's computer ?
type: Comment

http://stackoverflow.com/comment/86616419
score: 3
type: Comment
has text: why are you trying to use global vars to modify the values inside your class ? To rewrite player variable, you need to modify `self.stren` and assign your new value.
comment on: http://stackoverflow.com/q/49800802
type: QuestionComment

http://stackoverflow.com/q/49827567
favorite count: 0
has body: I have a dictionary as below : 'give': (('VBP', 6), ('VB', 15)), 'discounts': ('NNS', 1), 'maintaining': ('VBG', 4), 'increasing': ('VBG', 18), 'spending': (('NN', 24), ('VBG', 2)), 'become': ((('VBN', 7), ('VB', 15)), ('VBP', 1)), 'permanent': ('JJ', 2), 'fixtures': ('NNS', 1), 'news': ('NN', 24), 'weeklies': ('NNS', 2), 'underscore': ('VBP', 1), 'fierce': ('JJ', 2), 'competition': ('NN', 10) I am writing a list comprehension as below : result = [x for x in mydict.items() if type(x[1][0]) == 'str'] But this results in an empty list, whereas if I see there are many elements in dictionary, for which this condition satisfies.
type: Question
accepted answer: http://stackoverflow.com/a/49827589
has title: list comprehension on a dictionary giving empty list
has comment: http://stackoverflow.com/comment/86670616
has answer: http://stackoverflow.com/a/49827589
tagged with: python
tagged with: dictionary
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/86670617
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86670832

http://stackoverflow.com/q/49815472
upvote count: 1
tagged with: scikit-learn
tagged with: python
has comment: http://stackoverflow.com/comment/86728922
type: AnsweredQuestion
score: 0
has body: I'm trying to tune the alpha parameter of a Multinomial Naive Bayes, with the 20newsgroups database. This is my code so far: from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline from sklearn.metrics import classification_report from sklearn.model_selection import GridSearchCV import numpy as np # Divide dataset dataset_train = fetch_20newsgroups(subset='train', shuffle=True) dataset_test = fetch_20newsgroups(subset='test', shuffle=True) text_clf = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer(sublinear_tf=True)), ('clf', MultinomialNB())]) param_grid = {'tfidf__use_idf': (True, False), 'clf__alpha' : np.linspace(0.001, 1, 100)} grid_search = GridSearchCV(text_clf, param_grid=param_grid, scoring='precision', cv = None) # Training text_clf = grid_search.fit(dataset_train.data,dataset_train.target, average=None) #prediction predicted = text_clf.predict(dataset_test.data) print("NB Accuracy:", 100*np.mean(predicted == dataset_test.target), '%') print(classification_report(dataset_test.target, predicted, target_names=dataset_train.target_names)) print("Best estimator for alpha in order to get precision ", grid_search.best_estimator_) The problem is i'm getting the following error: runfile('C:/Users/omarl/Downloads/new_NB.py', wdir='C:/Users/omarl/Downloads') Traceback (most recent call last): File "&lt;ipython-input-12-d478372ef22a&gt;", line 1, in &lt;module&gt; runfile('C:/Users/omarl/Downloads/new_NB.py', wdir='C:/Users/omarl/Downloads') File "C:\Users\omarl\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Users\omarl\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/omarl/D…
answer count: 1
has comment: http://stackoverflow.com/comment/86652639
accepted answer: http://stackoverflow.com/a/49836101
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49836101
has title: ValueError: not enough values to unpack in GridSearch with Scikit
type: Question
tagged with: multinomial
tagged with: bayesian

http://stackoverflow.com/q/49859802
type: UnansweredQuestion
score: 1
has title: Azure thinks authentication key is 1024 bits, but it's not
tagged with: python
has body: I've been struggling to retrieve a token using the acquire_token_with_client_certificate function. No matter what I use for my PEM encoded key / cert, I receive the below error: AdalError: Get Token request returned http error: 401 and server response: {"error":"invalid_client","error_description":"AADSTS70002: Error validating credentials. AADSTS50032: RSA key size 1024 is less than the minimum required 2048 bits.\r\nTrace ID: 32bf21de-e77a-4419-ab2b-cdc3a9343200\r\nCorrelation ID: 291050ae-0e86-4d09-bd62-7cfc53750db9\r\nTimestamp: 2018-04-16 13:51:50Z","error_codes":[70002,50032],"timestamp":"2018-04-16 13:51:50Z","trace_id":"32bf21de-e77a-4419-ab2b-cdc3a9343200","correlation_id":"291050ae-0e86-4d09-bd62-7cfc53750db9"} My code is as follows: def get_private_key(filename): with open(filename, 'r') as pem_file: private_pem = pem_file.read() return private_pem context = adal.AuthenticationContext(authority_url, api_version=None) key = get_private_key('../keys/fullkey.pem') token = context.acquire_token_with_client_certificate( resource_id, client_id, key, thumbprint_new) print token No matter which .pem file I point to (I've generated multiple in an attempt to debug), I continue to receive the same error. Any help would be hugely appreciated! Thank you, Mike
has comment: http://stackoverflow.com/comment/86738102
has comment: http://stackoverflow.com/comment/86735818
answer count: 1
tagged with: adal
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50124127

http://stackoverflow.com/q/49784195
has title: Tic Tac Toe Game using Turtle
has comment: http://stackoverflow.com/comment/86583978
has body: This is for an extra credit assignment in Python. I've finished most until the last part where I have to determine the area of the tictactoe box chosen. I can only detect diagonal boxes, used from combining both code reply's below. I can detect those 3 boxes but the rest still show as none and most logic is used with loop so I can understand where I am going wrong. import turtle from time import sleep import sys CURSOR_SIZE = 20 SQUARE_SIZE = 99 FONT_SIZE = 40 FONT = ('Arial', FONT_SIZE, 'bold') BOXES = {} # TRACK BOX pen = turtle.Turtle() pen.penup() def mouse(x, y): print('|--------------X={0} Y={1}--------------|'.format(x, y)) for key in BOXES: minx, miny, maxx, maxy = BOXES[key] print(key, BOXES[key]) if (minx <= x <= maxx) and (miny <= y <= maxy): print("Found", key) return key print('None') return None # Not found. class TicTacToe: global BOXES def __init__(self): # CREATES 2D LIST FOR INTERROGATION self.board = [['?'] * 3 for i in range(3)] def minmax(self, points): """ Find extreme x and y values in a list of 2-D coordinates. """ minx, miny, maxx, maxy = points[0][0], points[0][1], points[0][0], points[0][1] for x, y in points[1:]: if x < minx: minx = x if y < minx: miny = y if x > maxx: maxx = x if y > maxy: maxy = y return minx, miny, maxx, maxy def drawBoard(self): ############################################## turtle.shape('square') turtle.shapesize(SQUARE_SIZE * 3 / CURSOR_SIZE) turtle.color('black') turtle.stamp() turtle.hideturtle() ############################################## for j in range(3): for i in range(3): # CREATES SHAPE AND STORES IN PLACEHOLDER turtle.shape('square') box = turtle.shape('square') # CREATES SHAPE SIZE AND STORES IN PLACEHOLDER turtle.shapesize(SQUARE_SIZE / CURSOR_SIZE) boxsize = turtle.shapesize() # CREATES SHAPE COLOR turtle.color('white') turtle.penup() # CREATES SHAPE POS AND STORES IN PLACEHOLDER turtle.goto(i * (SQUARE_SIZE + 2) - (SQUARE_SIZE + 2), j * (SQUARE_SIZE + 2) - (SQUARE_SIZE + 2)) boxpos = turtle.pos() myp…
tagged with: tic-tac-toe
type: Question
has answer: http://stackoverflow.com/a/49785949
has answer: http://stackoverflow.com/a/49785060
tagged with: turtle-graphics
has comment: http://stackoverflow.com/comment/86584367
tagged with: python-turtle
tagged with: python
possible better answer: http://stackoverflow.com/a/49785060
accepted answer: http://stackoverflow.com/a/49785949
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/comment/86768749
score: 0
has text: @Benjamin apparently it takes about 15 ms to split one line and to write it to the variable 'out'. I dont think I'll get the single line splitting faster, but I will try to use some multithreading to check several lines simultaneously .
type: QuestionComment
comment on: http://stackoverflow.com/q/49874492
type: Comment

http://stackoverflow.com/a/49773404
accepted answer of: http://stackoverflow.com/q/49772915
type: Answer
has comment: http://stackoverflow.com/comment/86563068
has comment: http://stackoverflow.com/comment/86562880
has body: I don't think you need regex to find a simple string. This might be a simplification of what you're looking for: s=""" some complex text abcd more text ----------- some complex text aoecd more text ----------- some complex text abcd more text """ # split the strings and add only those that contain "abcd" result = [d for d in s.split("-----------") if "abcd" in d] for r in result: print(r) # result: # some complex text # abcd # more text # # some complex text # abcd # more text As you can see, we split the string when "-----------" appears and then we evaluate if the substring "abcd" is contain in each of the strings, and we keep the strings that passed this condition.
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49772915

http://stackoverflow.com/comment/86617470
comment on: http://stackoverflow.com/a/49780443
score: 0
has text: Thank you, your proposal actually fixed my problem - i used inlines and it is actually what i wanted
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86630077
type: Comment
type: QuestionComment
has text: the should be add together , thank you for your question.
score: 0
comment on: http://stackoverflow.com/q/49801029

http://stackoverflow.com/q/49807252
tagged with: matplotlib
tagged with: datetime
answer count: 1
has title: How to increase xticks with a datetime index in matplotlib?
has comment: http://stackoverflow.com/comment/86629725
favorite count: 0
has answer: http://stackoverflow.com/a/49808424
type: Question
has comment: http://stackoverflow.com/comment/86629455
has body: I am trying to use matplotlib to graph stock prices against a datetime index. So I have a graph that looks like this: And I need it to look like this: I think it might have something to do with xticks, but I cannot figure out how to make xticks work with a datetime index. Thanks for the help. tesla['Open'].plot(title='Open Price', label = 'Tesla', figsize = (16, 6)) ford['Open'].plot(label = 'ford') gm['Open'].plot(label = 'GM') plt.legend() plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
downvote count: 0
accepted answer: http://stackoverflow.com/a/49808424
tagged with: python
has comment: http://stackoverflow.com/comment/86629468
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86631684
tagged with: pandas
upvote count: 3
linked to: http://stackoverflow.com/q/43968985
score: 3

http://stackoverflow.com/a/49898093
has body: After searching a while I found a solution burried in this specific site. If you've already set your .kivy/config.ini file up to work when you use a command to start kivy, this will work for you: "sudo cp ~/.kivy/config.ini /root/.kivy/config.ini" It copies the config file to the root folder, which made touchscreen on boot work for me. source
accepted answer of: http://stackoverflow.com/q/49894375
type: Answer
answers question: http://stackoverflow.com/q/49894375
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/86652970
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49817843
type: AnswerComment
has text: Add a `[` at the beggining of your text file and a `]` at the end.

http://stackoverflow.com/a/49884976
downvote count: 0
has body: You need to know the focal length of your webcam as well as the distance you are from the webcam, otherwise, you cannot know the absolute distance since a camera only measure angle.
answers question: http://stackoverflow.com/q/49884890
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/86824226
type: Comment
score: 0
type: AnswerComment
has text: F is a list ( a set mathematically) i is the feature i in the set and feat is feature.
comment on: http://stackoverflow.com/a/49903753

rfid
tag name: rfid
tags question: http://stackoverflow.com/q/49803018
tags question: http://stackoverflow.com/q/49842247
tags question: http://stackoverflow.com/q/49833654
type: Tag

http://stackoverflow.com/q/49837145
score: -2
tagged with: python
has body: I'm a beginner in python and during practicing stuck in the code of reassigning values: ##Task to take the first letter of each word and place it at the end of a word, except "special characters", like "!" entries = "I love Python, its awesome !"; transformed = entrens.split(' ') print(len(transformed)) for x in transformed: if x.isalpha(): print(x[0], x[-1] = '', (x[-1] + x[0]) ) else: x print(transformed) Output: $python main.py File "main.py", line 13 print(x[0], x[-1] = '', (x[-1] + x[0]) ) ^ SyntaxError: invalid syntax How possible to reassign value in one line? Grateful for feedback and support
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/49837193
has answer: http://stackoverflow.com/a/49837163
type: UnansweredQuestion
has title: Execution failed on equal sign "=" in python
downvote count: 3
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86689602
has comment: http://stackoverflow.com/comment/86689610

http://stackoverflow.com/comment/86704133
has text: Strange that it happens using Python3. How did you install Python? Which version are you using exactly?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49844560

http://stackoverflow.com/comment/86696652
type: Comment
has text: @ Günther I've tried just using the pyinstaller command line and manipulated the .spec file to exclude the PyQt4 package. However, now the program won't run at all? I'm not really sure how to get an overview of what to exclude and what not to exclude?
type: AnswerComment
comment on: http://stackoverflow.com/a/49814584
score: 0

http://stackoverflow.com/comment/86692504
type: QuestionComment
has text: @RamkishoreM - unfortunately, no. I tried what you mentioned about using a "key + 1", but the keys are not sequential. They also skip; for example "001", then "003", then "006", etc. In all of the for loops I've tried, I can reference the "d" value, but I am stuck with referencing the "d" value of the next loop iteration. for k,v in dict.items(): print(v["d"]) print(k+1[v]["d"]) <-- not really sure how to reference the next iteration "d" value. Surprisingly, I haven't found any examples that show this. They start talking about using pandas but that is way beyond my level.
comment on: http://stackoverflow.com/q/49838416
score: 0
type: Comment

http://stackoverflow.com/comment/86730092
type: Comment
score: 0
type: QuestionComment
has text: colored_things is a method in the things-model. @Daniel I guess that is my question. How do I pass the results to my template? I thought I can access them by just calling the method in the for loop. I tried it as a property, it behaves the same way as the method
comment on: http://stackoverflow.com/q/49857751

http://stackoverflow.com/comment/86788740
score: 0
has text: How would this output the third column df2['plate']? I don't think I quite follow.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49886229

http://stackoverflow.com/a/49907471
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: I will recap the details enlisted in the various comments and provide the final solution for your question. Paths and backslashes The QProcess API uses the CreateProcess on Win32 platforms and therefore paths must be provided in accordance with the OS convention (using backslashes instead of slashes). In your example, "C:/python27/python.exe" must be converted to "C:\Python27\python.exe". The double backslash here is due to C++ string literals escaping. Environment As you have correctly noted in your update, you need to set a few environment variables in order to make the Python interpreter work as expected. You also specified you want to detach the invoked python script, so it can run even when your application is closed. This is trickier with Qt &lt; 5.10 as the appropriate API to accomplish this task was introduced with Qt 5.10 (see this post from the Qt blog). With Qt 5.10, the correct code is: QProcess process; // set the environment variables QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert("PYTHONHOME", "C:\\Python27"); env.insert("PYTHONPATH", "C:\\Python27\\Lib"); process.setProcessEnvironment(env); // set program name and args process.setProgram("C:\\Python27\\python.exe"); process.setArguments(args); // start the detached process process.startDetached(); The code you have in your updated answer doesn't work because it is using the static execute() method. You see, a static method is part of a class, and this means you can call it from an object instance of that class, however, since it's static, it can't access the object's members. In other words, execute() can't know anything about the QProcessEnvironment you set before. For the same reason, calling the startDetached() overload which accepts two arguments won't work either, because it is static too. The Qt blog post explains exactly why this new non static overload was created, and this fits perfectly in your scenario. Closing my app kills the python interpreter. This is tr…
accepted answer of: http://stackoverflow.com/q/49902533
answers question: http://stackoverflow.com/q/49902533
type: Answer
score: 2

http://stackoverflow.com/q/49890034
downvote count: 3
tagged with: python
score: -1
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/4937491
has answer: http://stackoverflow.com/a/49890169
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49890065
has answer: http://stackoverflow.com/a/49890459
has body: I have a list with lists in it. [['H','J','K','L'],['Q','W','E','R'],['R','W','Q','T']] I want to print the same indexes within one line with a space between them.the So output would be: H Q R J W W K E Q L R T I tried using for loop using enumerate and while loop. Nothing seems to work and I'm just a beginner so I don't even know the correct way to approach this. I'd be really grateful if someone could help me out. Thanks a lot! Have a nice day!
has title: Print same index of lists within lists
answer count: 3
duplicate of: http://stackoverflow.com/q/23525451

http://stackoverflow.com/a/49846898
upvote count: 1
answers question: http://stackoverflow.com/q/49846661
has body: The code works for x because the if/else block in the lower part updates x to include a value for x[i] (which will be checked on the next iteration as x[i-1]). There's no such update to the y dict, so on the second pass, y[i-1] is not available. You probably need to add lines like y[i]=yt[i], either in the existing if/else blocks, or in an equivalent one that has it's own logic.
accepted answer of: http://stackoverflow.com/q/49846661
type: Answer
has comment: http://stackoverflow.com/comment/86708834
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86591138
type: QuestionComment
has text: Do you want only the titles?
comment on: http://stackoverflow.com/q/49787982
score: 0
type: Comment

http://stackoverflow.com/q/49782603
has comment: http://stackoverflow.com/comment/86580693
has comment: http://stackoverflow.com/comment/86581138
score: 15
tagged with: documentation
favorite count: 0
has title: Does main() need a docstring?
has comment: http://stackoverflow.com/comment/86580529
has comment: http://stackoverflow.com/comment/86580537
has comment: http://stackoverflow.com/comment/86580493
has comment: http://stackoverflow.com/comment/86580488
tagged with: python
has comment: http://stackoverflow.com/comment/86581005
has body: I always thought that a main() function (as called from if __name__ == '__main__')doesn't need a docstring, since Docstrings can be seen when calling a function from within python, but outside the module, but main() is usually only called from the command line (where the docstring is not accessible). The idea of main() should be well enough understood that it need no documentation. Yet, from pep8: Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the "def" line. Which line of thought wins out?
type: Question
upvote count: 15
has comment: http://stackoverflow.com/comment/86580780
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/104725432
tagged with: pep8
downvote count: 0

http://stackoverflow.com/comment/86632575
type: AnswerComment
comment on: http://stackoverflow.com/a/49808852
type: Comment
has text: If `k` contains multiple words, count them and add to the initial word count: `3` + (`0`, `1`, ...)
score: 0

http://stackoverflow.com/q/49843095
has title: Truncating texts before and after a certain character python
tagged with: python
tagged with: regex
has body: I have large texts that I am reading in python, The format of the texts is : blablabla ***** END HEADER ****** valid content ***** start footer ***** blablalba I need to remove the headers and footers in all the texts by removing all the string until ***** END HEADER ***** and everything after ***** start footer ***** Any help would be appreciated I tried this so far: import re chop = re.compile('(/.+)*** END HEADER *****', re.DOTALL) data_chopped = chop.sub('', text_file) But i keep getting the error: sre_constants.error: multiple repeat at position
tagged with: text
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86700754
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: truncate
accepted answer: http://stackoverflow.com/a/49843177
has comment: http://stackoverflow.com/comment/86700806
has answer: http://stackoverflow.com/a/49843177

http://stackoverflow.com/q/49860848
type: Question
type: UnansweredQuestion
has title: 'tensorflow.python.framework.errors_impl.InvalidArgumentError'>, Input to reshape is a tensor with 6144 values, but the requested shape has 3072
downvote count: 0
upvote count: 1
tagged with: python
has body: I created TFrecord file with mfccs of music segment and theirs labels. But I am running into a problem of tenor shape. I'm sure that the shape of mfcc is [256,12] before writing to TFrecord file. It seems that the requested shape is half of the tensor read from the file. I can't locate the mistake and don't know the reason. Could you please give me some advice? thanks enter code here def read_tfRecord(file_tfRecord): queue = tf.train.string_input_producer([file_tfRecord]) reader = tf.TFRecordReader() _,serialized_example = reader.read(queue) features = tf.parse_single_example(serialized_example,features={'micsegment': tf.FixedLenFeature([], tf.string), 'label': tf.FixedLenFeature([], tf.int64)}) mic=tf.decode_raw(features['micsegment'],tf.float32) mic=tf.reshape(mic,[256,12,1]) label=tf.cast(features['label'], tf.int64) return mic,label [mic,label]=read_tfRecord('D:/360MoveData/training.tfrecords') [testmic,testlabel]=read_tfRecord('D:/360MoveData/test1.tfrecords') sess = tf.InteractiveSession() x=tf.placeholder(tf.float32, [256*12]) y_actual = tf.placeholder(tf.float32, [None, num_classes]) def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool(x,ksize): return tf.nn.max_pool(x, ksize,strides=[1, 1, 1, 1], padding='SAME') x_mic=tf.reshape(x,[-1,256,12,1]) W_conv1 = weight_variable([3, 3, 1, 16]) b_conv1 = bias_variable([16]) h_conv1 = tf.nn.relu(conv2d(x_mic, W_conv1) + b_conv1) #第一个卷积层 h_pool1 = max_pool(h_conv1,ksize=[1,2,2,1]) W_conv2 = weight_variable([3, 3, 16, 32]) b_conv2 = bias_variable([32]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool(h_conv2,ksize=[1,2,3,1]) W_conv3 = weight_variable([3, 3, 32, 32]) b_conv3 = bias_variable([32]) h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3) h_po…
answer count: 0
score: 1
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/a/49892977
answers question: http://stackoverflow.com/q/49892870
type: Answer
score: -1
upvote count: 0
downvote count: 1
has body: Your problem is that your "switcher" dictionary has integer keys, and argument is a string when you call print switcher.get(argument, "Invalid month") One possible solution is to cast argument to int, it should then work. print switcher.get(int(argument), "Invalid month")

http://stackoverflow.com/comment/129517725
has text: Thank you, @urban! Just a point of attention for anyone not getting it to work: - Be aware that "-e your_env_var_name = env_var_value" must come BEFORE the image name in the RUN command
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49771684

http://stackoverflow.com/comment/86690760
type: Comment
has text: I tweaked it a tiny bit
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49837765

http://stackoverflow.com/comment/104621733
comment on: http://stackoverflow.com/a/49864806
has text: RESTART VM is essential here. I was on a Jupyter Notebook and I simply "restarted kernel" And finally it worked for me
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86822342
comment on: http://stackoverflow.com/q/49903165
type: Comment
type: QuestionComment
has text: I havent used abstract methods as I had little understanding of metaclasses. I will read the documentation to have it more conventional. By then, I have tried @Jean-FrançoisFabre's answer and it works
score: 0

http://stackoverflow.com/comment/86605090
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49794713
has text: It seem to be working exactly like you are asking for, i cannot recreate your issue. I run the program in one terminal, call kill 15 PID, the loop ends fine and then exits. Im using Python 3.6.3

http://stackoverflow.com/q/49889908
tagged with: python-3.x
upvote count: 3
tagged with: batch-processing
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49889944
has body: I have a folder with 10 images that I wish to move into a new folder based on it's current filenames. I've successfully been able to move every images in the folder into a new folder but I've yet to figure out how to move the files based on it's filename, For example below I want to move the images accordingly. 1600_01.jpg ---> folder 1 1700_01.jpg ---> folder 1 1800_02.jpg ---> folder 2 1900_02.jpg ---> folder 2 2000_03.jpg ---> folder 3 2100_03.jpg ---> folder 3 This is my code thus far for moving entire files in a folder to a destination that I want. # Moving Files from one place to another import shutil import os sourcefile = 'Desktop/00/' destination = 'Desktop/00/d' # Loading the files from source files = os.listdir(path=sourcefile) # Reading the files in folder for f in files: shutil.move(sourcefile+f, destination)
linked to: http://stackoverflow.com/q/49893501
type: Question
type: AnsweredQuestion
score: 3
tagged with: python
tagged with: image
has answer: http://stackoverflow.com/a/49889944
has title: Python 3.5: Moving files to folder based on filenames
favorite count: 0

http://stackoverflow.com/a/49857222
has comment: http://stackoverflow.com/comment/86729828
upvote count: 2
answers question: http://stackoverflow.com/q/49857185
downvote count: 0
has comment: http://stackoverflow.com/comment/86729919
has comment: http://stackoverflow.com/comment/86729282
score: 2
type: Answer
has body: Here is one way using str.split: a = (('_a_1', '_a_2'), [0.3, 0.6]) b = (('_a_3', '_a_4'), [0.15, 0.56]) c = (('_a_5', '_a_6'), [0.22, 0.6]) res = [[i.split('_')[-1], j.split('_')[-1]] for (i, j), k in [a, b, c]] # [['1', '2'], ['3', '4'], ['5', '6']] You can also use str.replace: res = [[i.replace('_a_', ''), j.replace('_a_', '')] for (i, j), k in [a, b, c]] As suggested by @Ev.Kounis, you can also write this functionally: res = [list(map(lambda x: x.rsplit('_', 1)[-1], k)) for k, _ in [a, b, c]] Nested list comprehensions require specific ordering, intuitive to some but not to others. The above solutions avoid them altogether.

http://stackoverflow.com/q/49800726
has comment: http://stackoverflow.com/comment/86641889
tagged with: python
has comment: http://stackoverflow.com/comment/86627499
tagged with: cplex
tagged with: mathematical-optimization
has title: Cplex Python equivalent of Callable Library CPXaddcols
answer count: 0
has comment: http://stackoverflow.com/comment/86654583
score: 1
has body: I am trying some performance experimentation using the CPLEX Python API and found that most of the CPLEX row or column updates are via sparse pair or sparse triplets. On large matrices ( millions of columns), it just gets too slow. I am looking for more efficient ways (equivalent of int CPXaddcols(CPXENVptr env,CPXLPptr lp,int ccnt,int nzcnt,double *obj,int *cmatbeg,int *cmatind,double *cmatval, double *lb, double *ub,char **colname) from Callable Library) I found the methods to be in the cplex._internal._procedural, but could not really call it successfully. Anyone used CPLEX Python for large scale LP? Any one used the addcols(env, lp, ccnt, nzcnt, obj, cmat, lb, ub, colname, enc=default_encoding) method in python cplex? Any help is highly appreciated. Thanks Code import cplex import os WORKDIR = "data1" filename = "matrix1.prefix.LP" os.chdir(WORKDIR) problem = cplex.Cplex(filename) theEnv = problem._env theLP = problem._lp returnCols = cplex._proc.getcols(theEnv, theLP, 0,10) print( returnCols) Output File "C:/TSWork/Misc/Calendar_Year_2018/Experiments/MtrxDnst/CPX_Proc_V1.py", line 15, in returnCols = cplex._proc.getcols(theEnv, theLP, 0,10) File "C:\Software\Anaconda3\envs\cplex\lib\site-packages\cplex_internal_procedural.py", line 861, in getcols status = CR.CPXXgetcols(env, lp, inout_list) TypeError: in method 'CPXXgetcols', argument 1 of type 'CPXCENVptr'
has comment: http://stackoverflow.com/comment/86714202
has comment: http://stackoverflow.com/comment/86635604
has comment: http://stackoverflow.com/comment/86739950
has comment: http://stackoverflow.com/comment/86638484
tagged with: linear-programming
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86616695
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86753527
downvote count: 0

http://stackoverflow.com/q/49831600
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
has title: Python 2D Interpolation
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49837403
answer count: 2
score: 1
has answer: http://stackoverflow.com/a/49832091
has body: I would be very much grateful of someone can someone help me with understand 2D interpolation for the below mentioned problem. I have a list of temperature values corresponding to x and y indices of pixels. And also I have latitudes and longitudes corresponding to selected indices of pixels. Now I want to interpolate my latitudes and longitudes, so that I can get latitudes and longitudes corresponding to all the pixels, that I have temperature data. #List 1 represents temperature values for each x and y indices of pixels List1 = [[10,13,17,18,20], [3,5,1,4,5], [13,11,12,11,12]] #print List1[2][2] #List 2 represents latitude for just the first, middle and the last indices #of pixels List2=[[2,3,4],[2.4,3.5,6],[2.2,4.5,7]] #List 2 represents longitude for just the first, middle and the last indices #of pixels List2=[[5,8,12],[4.4,7.5,8.6],[2.5,4.6,7.9]] #I want to interpolate latitude and longitude values for the unknown #indices.
downvote count: 1

http://stackoverflow.com/q/49848819
has answer: http://stackoverflow.com/a/59936337
has comment: http://stackoverflow.com/comment/97920124
type: Question
has comment: http://stackoverflow.com/comment/87307770
has comment: http://stackoverflow.com/comment/87310139
tagged with: python
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/87324391
tagged with: node.js
has title: python-shell send json from nodejs to python
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/87310123
has body: At the nodejs side I created a script for sending json to python, but I don't know how to retrieve these data and convert it into dictionary, Anyone can help me on this issue? const schedule = require('node-schedule'); const PythonShell = require('python-shell'); let d = new Date('2018-04-16 10:16:10') var pyshell = new PythonShell('../a.py', { mode: 'json' }); let j = schedule.scheduleJob(d, () =&gt; { pyshell.send({test:1,ff:2}); pyshell.end(err =&gt; { if (err) res.send("Error : ", err); }); pyshell.on('message', function(message) { // console.log(message) // handle message (a line of text from stdout, parsed as JSON) }); }); a.py import sys, json lines = sys.stdin.readlines() f = json.loads(lines[0]) print(f) It gives me an error undefined:1 {'test': 1, 'ff': 2} SyntaxError: Unexpected token &lt; in JSON at position 0
favorite count: 0

http://stackoverflow.com/q/49763973
type: Question
accepted answer: http://stackoverflow.com/a/49766088
has answer: http://stackoverflow.com/a/49766088
upvote count: 2
downvote count: 0
tagged with: python
tagged with: excel
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/49764028
answer count: 2
tagged with: pandas
has body: I'll just start with the example and then break down what is happening. This is a sample input: DataFrame: **Name** **No.** **Test** ***Grade*** Bob 2123320 Math Nan Joe 2832883 English 90 John 2139300 Science 85 Bob 2123320 History 93 John 2234903 Math 99 Hopeful output: **Name** ********2139300********* ********2234903******* Math English Science Math English Science John 0 0 85 99 0 0 Like the title suggests, I am trying to apply multiple indexes. So basically it starts by looking for each name, and then for each name it finds to see how many distinct No.'s it has. In this case it sets a threshold at at least 2 distinct No.'s (which is why only John is outputted and Joe/Bob are not). Now in each of these distinct No's. I have a specific subset of Tests I want to search for, in this case only {Math, English, Science}. For each of these tests, if the person in question took it in that No., there should be a grade. I would like that grade to be outputted for the test in question and for the tests not taken by that person on that No. I would like it to output some sort of simple marker (i.e if the person only took Math on that day, for English and Science output 0). So in effect, it first indexes people by the number of distinct No.'s and groups them as such. It then indexes them by type of Test (for which I only want a subset). It finally assigns each person a value for the type of test they took and for the ones they didn't simply outputs an 0. It's similar to another problem I asked earlier: Grouped Feature Matrix in Python #2- Follow Up Except now instead of 1's and 0's I have another column with actual values that I would like to output. Thank you. EDIT: More sample/Output **Name** **No.** **Test** ***Grade*** Bob 2123320 Math Nan Joe 2832883 English 90 John 2139300 Science 85 Bob 2123320 History 93 John 2234903 Math 99 Bob 2932848 English 99 **Name** 2139300 2234903 2123320 2932848 M E S M E S M E S M E S John 0 0 85 99 0 0 Nan Nan Nan Nan Nan Nan Bob Nan Nan N…
has answer: http://stackoverflow.com/a/49764028
linked to: http://stackoverflow.com/q/49744958
tagged with: dataframe
has title: Multiple Indexes for Dataframe Grouping
favorite count: 0

http://stackoverflow.com/q/49891013
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86880407
has comment: http://stackoverflow.com/comment/86817010
has comment: http://stackoverflow.com/comment/86858531
has comment: http://stackoverflow.com/comment/131680727
tagged with: python
tagged with: nlp
has comment: http://stackoverflow.com/comment/86858145
upvote count: 2
has answer: http://stackoverflow.com/a/49937599
score: 2
has comment: http://stackoverflow.com/comment/86849479
has body: EDITED: I've updated my traceback below I know this kind of problems has been asked for many times, but I have been struggling to this issue 2 days and still can't figure a solution. Here the case: I'm using pycrfsuite (a python implementation of CRF), and this snippets raise UnicodeEncodeError. trainer = pycrfsuite.Trainer(verbose=True) for xseq, yseq in zip(X_train, y_train): trainer.append(xseq, yseq) Error ... Traceback (most recent call last): File "/home/enamoria/Dropbox/NLP/POS-tagger/MyTagger/V2_CRF/src/pos-tag/pos-tag.py", line 46, in &lt;module&gt; trainer.append(xseq, yseq) File "pycrfsuite/_pycrfsuite.pyx", line 312, in pycrfsuite._pycrfsuite.BaseTrainer.append File "stringsource", line 48, in vector.from_py.__pyx_convert_vector_from_py_std_3a__3a_string File "stringsource", line 15, in string.from_py.__pyx_convert_string_from_py_std__in_string UnicodeEncodeError: 'ascii' codec can't encode character '\u201d' in position 0: ordinal not in range(128) \u201d is the closing double quote ” in utf8 encoding. This exception was also raised for \u201c (opening double quote) and \u2026 (ellipsis IIRC) FYI, X_train and y_train is a features representation of a text and its corresponding labels, which I read from a file. I've try using encoding='utf8', errors='ignore' but the error still there for file in filelist: with open(self.datapath + "/" + file, "r", encoding='utf8', errors='ignore') as f: raw_text = [(line.strip("\n").strip(" ").replace(" ", " ").replace(" ", " ")).split(" ") for line in f.readlines() if line != '\n'] data.extend(raw_text) My question is: Is pycrfsuite only support ascii encoding? If so, is there any workaround available for me? My data is Vietnamese which ascii can't represent, and a new crf library is the last thing I want Thanks in advance.
answer count: 2
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/130539618
has title: UnicodeEndcodeError - utf-8 encoding in python-crfsuite (pycrfsuite)
tagged with: unicode
has answer: http://stackoverflow.com/a/55506785

http://stackoverflow.com/comment/86673686
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49829087
type: QuestionComment
has text: remove the `input('press enter')`?

http://stackoverflow.com/q/49901415
has title: Change every value in a dataframe column to the value returned by a function
downvote count: 1
tagged with: dataframe
tagged with: python
has body: I have a dataframe that contains a column containing a string value. I need to replace each value in that column with the results of a function. I'd like to do this without iterating over thousands of rows. The function takes a term and returns the approved new value of that term. Example: getPreferredTerm('STAINED') would return 'DISCOLORED' so values of 'STAINED' in the P_TERM column would all be replaced by 'DISCOLORED'. I'm struggling with using numpy to accomplish this. df['P_TERM'] = getPreferredTerm(df['P_TERM']) the getPreferredTerm function is as follows: def getPreferredTerm(stresc): # NOTE" obsData is a dataframe containing legacy terms in a # column called 'STRESC' and preferred terms in a column # named 'PTERM' so this function takes a legacy term as input # and returns a preferred term try: df = obsData.loc[(obsData['STRESC'] == stresc)].iloc[0]['P_TERM'] pterm = df except Exception as e: pterm = 'UNMAPPED' return pterm is it possible to vectorize this function if I pass it a series instead of a single value?
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49901530
linked to: http://stackoverflow.com/q/49259580
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49901530
type: AnsweredQuestion
score: 0
tagged with: pandas

http://stackoverflow.com/comment/86620943
type: Comment
comment on: http://stackoverflow.com/q/49803221
score: 1
type: QuestionComment
has text: Your python needs updating. See the last line `C:\Python27\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py:137: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings`. You're using 2.7 so you can just download another 2.7 installer from the python website and install over your old one - it'll be replaced.

http://stackoverflow.com/comment/86821655
comment on: http://stackoverflow.com/q/49887257
has text: Hi @AuroSarma thanks for commenting. I've attached the console output and some supporting imagery. As you can hopefully see in the third screenshot, the timeline control appears to be disconnected from the DOM itself as a result of executing actions.drag_and_drop_by_offset(). I suspect this is because it's too sudden; a human user would drag and scroll over time whereas perhaps the driver does so instantly(?). Therefore even if I created a new reference to 'tlh' in the code, a StaleElementReferenceException would still be thrown. This is the problem I'm seeking advice on.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/55590613
answers question: http://stackoverflow.com/q/49894919
type: Answer
has body: For Python v3 (64 bit), try installing ImageMagick-6.9.10-2-Q16-x64-dll.exe from here then put installed directory file path in Path environment variable, ex - C:\Program Files\ImageMagick-6.9.10-Q16 then install wand pip install wand==0.4.4 this should fix the issue as there are compatibility issues with wand and ImageMagick
score: 0

http://stackoverflow.com/q/49778278
has answer: http://stackoverflow.com/a/49823446
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49779162
downvote count: 0
has comment: http://stackoverflow.com/comment/86572086
score: 1
upvote count: 1
has body: I would like to use the DBF module to split a vfp dbf based on a value in a column, dist. I therefore extracted all necessary indices to use them for the export. Unfortunately, the original table does not allow a list of indices. input_file = 'refrence.dbf' table = dbf.Table(input_file) l = [] for ind, record in enumerate(table.open(mode=dbf.READ_WRITE)): with record as r: if r.dist &gt;= start and r.dist &lt;= end: l.append(ind) is there an easier way to get to n separate dbf files containing only the rows which satisfy the condition r.dist &gt;= start and r.dist &lt;= end ?
has answer: http://stackoverflow.com/a/49780950
has comment: http://stackoverflow.com/comment/86572322
favorite count: 0
type: Question
tagged with: dbf
answer count: 3
tagged with: database
has comment: http://stackoverflow.com/comment/86572455
tagged with: python
has title: write dbf slice from dbf in python
tagged with: foxpro

http://stackoverflow.com/q/49852738
tagged with: python
score: -1
has title: Django app SSL socket connection to firmware
linked to: http://stackoverflow.com/q/8047204
answer count: 1
downvote count: 1
has body: I have a Django app created using Django rest framework. Below is the configuration that my setup is using: Django 1.9 mongoDB as backend gunicorn nginx Now I have created an API to enter data in DB and retrieve it using REST. I have test it via postman and it is working fine. We have a firmware which is consuming those APIs and that team want to use SSL socket connection instead of REST API. I am new in SSL Socket connection and I am not able to find anything on internet that can help me on this. I know it is possible to create socket in Python but I am not able to understand how to use it in Django app to Read/Write data in mongoDB. Any guidance will be very helpful. TO READER : I understand you may want to close this question but please put up a remark on how to get guidance on this as SO is the biggest portal for putting up questions. EDIT 1 : I am adding the code of my serializer.py API. from rest_framework import serializers class SaveUserLogs(serializers.Serializer): token = serializers.CharField(label=_("Token")) device_ip = serializers.CharField(label=_('Device IP')) device_name = serializers.CharField(label=_('Device Name')) device_os = serializers.CharField(label=_('Device OS')) device_macid = serializers.CharField(label=_('Device MAC ID')) dest_port = serializers.CharField(label=_('Device Port')) conn_type = serializers.CharField(label=_('Connection Type')) date = serializers.CharField(label=_('modified date')) def validate(self, attrs): device_macid = attrs.get('device_macid') token = attrs.get('token') if device_macid: tokendetails = validate_token(token) if not tokendetails: msg = _('Invalid token.') raise serializers.ValidationError(msg) else: userdetails = tokendetails.user if userdetails.check_mac_id(device_macid): all_logs = UserLog.objects.all().order_by("-id") log_id = 1 if all_logs: getid = all_logs[0].id log_id = getid + 1 new_log = UserLog( id=log_id, device_ip=attrs.get('device_ip'), device_name=attrs.get('device_name'), device_os=attrs.get(…
favorite count: 0
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/49854706
upvote count: 0
type: UnansweredQuestion
tagged with: sockets
tagged with: django
tagged with: ssl

http://stackoverflow.com/q/49819328
has comment: http://stackoverflow.com/comment/86653910
has answer: http://stackoverflow.com/a/49819739
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/59585669
has comment: http://stackoverflow.com/comment/86653852
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49819587
tagged with: css
has answer: http://stackoverflow.com/a/49819575
has comment: http://stackoverflow.com/comment/86653795
tagged with: substring
answer count: 4
possible better answer: http://stackoverflow.com/a/49819575
type: Question
accepted answer: http://stackoverflow.com/a/49819739
downvote count: 0
has title: Python loop through all urls in CSS file and replace
tagged with: url
upvote count: 1
tagged with: string
has body: I'm trying to find all relative urls in a css file and replace them with absolute url. I know how to get the absolute path but first I need to find all occurances of the url() in the file, then grab the relative path and replace it with absolute path. Here is what I tried so far. Given my Css is: css= "background:url(/pub-assets/img/index/sec8-bg.png) src:url('../fonts/fontawesome-webfont.eot?v=4.6.3') background-image:url('../img/index/blok1-bg.jpg')" Im trying this code: start = "url(" end = ")" print css[css.find(start)+len(start):css.rfind(end)] but it does not return the url and instead is returning css code sadly. Can anyone help me with this. Any suggestion much appreciated
favorite count: 0

http://stackoverflow.com/comment/86604326
type: QuestionComment
comment on: http://stackoverflow.com/q/49794878
type: Comment
score: 0
has text: How exactly is it not working, do you get an error message?

http://stackoverflow.com/q/49809879
has answer: http://stackoverflow.com/a/49809931
possible better answer: http://stackoverflow.com/a/49809931
answer count: 2
tagged with: hidden-field
has body: I am getting the error module 'django.forms.forms' has no attribute 'HiddenInput' on the following code: from django.forms import ModelForm, forms from comments.models import Comment class CommentForm(ModelForm): class Meta: model = Comment fields = ['video', 'text'] widgets = {'video': forms.HiddenInput(), 'text': forms.TextArea()} Does anyone know what could be causing this? I looked it up in the documentation, and HiddenInput() should be valid (https://docs.djangoproject.com/en/2.0/ref/forms/widgets/).
upvote count: 1
tagged with: django
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49809916
accepted answer: http://stackoverflow.com/a/49809916
downvote count: 0
score: 1
tagged with: python
has title: Django has no Attribute 'HiddenInput'
tagged with: forms
tagged with: django-forms
type: Question

http://stackoverflow.com/q/49769562
has body: I am trying to copy all the .txt files from a compressed file (this file has unknown_name_folders): .txt files location ---> my_path/?unknown_name_folder?/file.txt I want to do ---> my_path/file.txt I did this code, but I have this error: EOFError: Compressed file ended before the end-of-stream marker was reached. Any idea? file=my_path+"/"+fil if file.endswith('.tar.gz'): tarf = tarfile.open(file, "r:gz") for info in tarf: if info.name.endswith('.txt'): print(info.name) tar = tarfile.open(file) #extracting tar.extractall() tar.close() code=os.system('cp ' + my_path+'/'+info.name +' '+ file)
favorite count: 0
type: AnsweredQuestion
score: 3
tagged with: python-2.7
upvote count: 3
downvote count: 0
has title: Copy .txt files from a .tar.gz file to other directory
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/49770121
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49770121
has comment: http://stackoverflow.com/comment/86554269
answer count: 1

http://stackoverflow.com/comment/133354221
has text: Turns out this was my actual problem, though: https://stackoverflow.com/questions/24886625/pycharm-does-not-show-plot/46965602#comment133354212_46965602 It plots interactively without any changes once I say `plt.show()`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49844189

http://stackoverflow.com/a/49856355
has body: re.findall() approach with specific regex pattern: import re strings = ['abc1235abc53abcXX', '123abc098YXabc'] pat = re.compile(r'(?:abc|^)(.+?)(?=abc|$)') # prepared pattern for s in strings: items = pat.findall(s) print(items) # further processing The output: ['1235', '53', 'XX'] ['123', '098YX'] (?:abc|^) - non-captured group to match either abc substring OR start of the string ^ (.+?) - captured group to match any character sequence as few times as possible (?=abc|$) - lookahead positive assertion, ensures that the previous matched item is followed by either abc sequence OR end of the string $
type: Answer
answers question: http://stackoverflow.com/q/49856172
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49856172

http://stackoverflow.com/q/49771377
answer count: 2
linked to: http://stackoverflow.com/q/47188756
tagged with: anaconda
downvote count: 0
tagged with: pydot
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49787850
has body: I am trying to run this script https://github.com/dennybritz/nn-theano/blob/master/nn-theano.ipynb which implements a neural network using theano. All goes fine until I get to the cell: theano.printing.pydotprint(forward_prop, var_with_name_simple=True, compact=True, outfile='img/nn-theano-forward_prop.png', format='png') SVG(theano.printing.pydotprint(forward_prop, var_with_name_simple=True, compact=True, return_image=True, format='svg')) Then I get this error: RuntimeError Traceback (most recent call last) &lt;ipython-input-11-db44e43f05ee&gt; in &lt;module&gt;() ----&gt; 1 theano.printing.pydotprint(forward_prop, var_with_name_simple=True, compact=True, outfile='img/nn-theano-forward_prop.png', format='png') 2 SVG(theano.printing.pydotprint(forward_prop, var_with_name_simple=True, compact=True, return_image=True, format='svg')) ~\Anaconda3\lib\site-packages\theano\printing.py in pydotprint(fct, outfile, compact, format, with_ids, high_contrast, cond_highlight, colorCodes, max_label_size, scan_graphs, var_with_name_simple, print_output_file, return_image) 781 " and either pydot or pydot-ng for " 782 "pydotprint to work.", --> 783 pydot_imported_msg) 784 785 g = pd.Dot() RuntimeError: ('Failed to import pydot. You must install graphviz and either pydot or pydot-ng for `pydotprint` to work.', 'An error happened while importing/trying pydot: (2, \'"dot.exe" not found in path.\', None, 2, None)') I have read other questions on Stack and have tried installing graphviz via https://graphviz.gitlab.io/ I have pydot, pydotplus, graphviz (2.38.0) and also python-graphviz (0.8.2) installed. I am using Anaconda Navigator which I have recently updated. Python 3.6.4 Windows 10 32bit.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/58797722
tagged with: theano
has answer: http://stackoverflow.com/a/49787850
tagged with: python
has title: python - theano printing pydotprint - runtime error: failed to import pydot
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/58797722

http://stackoverflow.com/comment/86787283
type: AnswerComment
comment on: http://stackoverflow.com/a/49855057
has text: I also tried to reinstall both python and pandas, but it still has the same problem. :(
type: Comment
score: 0

http://stackoverflow.com/comment/86619470
type: Comment
type: QuestionComment
has text: I don't think you want to add them to the class itself. The `members` list should be created/initialized in the `Team` class' `__init__()` method with a `self.members = []`, **not** declared as a class-level attribute the way you're doing it. That way each `Team` instance created will have its own member list instead of all instances sharing the same one. After that's done, in the `add_member()` method, you can use `self.members.append([user_id, first_name, second_name, address])` to add an item to the members of just that `Team` class instance (as opposed adding it to all of them)..
comment on: http://stackoverflow.com/q/49801901
score: 0

http://stackoverflow.com/comment/86534244
type: QuestionComment
comment on: http://stackoverflow.com/q/49758589
has text: Can you explain what you mean by the numbers being too large?
score: 0
type: Comment

http://stackoverflow.com/q/49821442
score: -1
has answer: http://stackoverflow.com/a/49821485
type: AnsweredQuestion
upvote count: 0
tagged with: list
has body: Say I have a list my_input_list = [22,33,56,1] and from a variable target_len I want to make (exclusive, sorted) sublists of that length target_len = 2 #my_output_list_not_sorted = [[22,33][22,56][22,1][33,56][33,1][56,1]] my_output_list = [[22,33][22,56][1,22][33,56][1,33][1,56]] or target_len = 3 #my_output_list_not_sorted = [[[22,33,56][22,33,1][33,56,1]] my_output_list = [[22,33,56][1,22,33][1,33,56]] Is there a neat way to do this? I'm OK to sort my_input_list first if needed. Thanks!
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49821485
favorite count: 0
type: Question
has title: expand a list to list of lists by a variable length
linked to: http://stackoverflow.com/q/464864
duplicate of: http://stackoverflow.com/q/464864
tagged with: python

http://stackoverflow.com/q/49858713
has answer: http://stackoverflow.com/a/49858798
type: Question
linked to: http://stackoverflow.com/q/6871016
has title: Adding days to a specigic date
has body: Currently using bash I am using this string in order to add 27 days to a specific date that is entered by the user: d1="$(date -d "$date +27 days" +"%a %b %d %Y")" I am currently trying to do something in python (trying to learn python) that is similar where I am trying to add 27 days to a specific date import datetime print ("Last billing run date mm/dd/yy") d = input() a = datetime.timedelta(days=27) b = datetime.timedelta(days=45) x = d + b y = d + a print(x) print(y)
type: UnansweredQuestion
tagged with: datetime
tagged with: python
duplicate of: http://stackoverflow.com/q/6871016
score: 0
answer count: 1

http://stackoverflow.com/comment/86731300
type: QuestionComment
comment on: http://stackoverflow.com/q/49857395
score: 0
has text: Thank you for your reply @jpp both readability and performance matters, since I have to use the same idea for a very large matrix K which updates after an iteration of optimization.
type: Comment

http://stackoverflow.com/q/49869161
has comment: http://stackoverflow.com/comment/86753708
has title: What's required for Python Click script to access it's own module directory?
tagged with: python
tagged with: command-line-interface
answer count: 2
tagged with: python-click
has body: How do I use a Python Click script anywhere in my home directory, and have my script access configs inside the the module's directory? Let's say I have a little scriptie called ClickDir and it resides in my home directory ~/bin. Here's the tree for a simple script: . ├── ClickDir │ ├── config │ │ └── helloworld_input.txt │ ├── __init__.py │ └── scripts │ ├── clickscript.py │ └── __init__.py ├── HelloWorld_output.txt └── setup.py It's a very useless script. It reads a file in config and concatenates this text with an input text file of your choosing. Finally, it writes HelloWorld_output.txt to the same directory as your INPUT file, Usage: ClickDir [OPTIONS] INPUT I can call the Click function from anywhere, but Click also looks relative to that directory for config/helloworld_input.txt. And so, the script fails to find the config input, FileNotFoundError: [Errno 2] No such file or directory: '../config/helloworld_input.txt' I need to apply this in both Linux and Windows (Anaconda on Win 10) UPDATE: import click import os dir_path = os.path.dirname(os.path.realpath("config/helloworld_input")) #@cli.command() @click.command() @click.argument('input', type=click.File('rb')) @click.option('--saveas', default='HelloWorld.txt', type=click.File('wb')) def inout(input, saveas): with open(dir_path + "/helloworld_input") as conf: print(conf.read()) while True: chunk = input.read(1024) if not chunk: break saveas.write(chunk) My script is located here: /home/xtian/Documents.x/Projects/CliTools.d/ClickDir/scripts I backed up a few directories, and ran the script from Projects, but unfortunately the solution described below just calls from the call directory--same as before: FileNotFoundError: [Errno 2] No such file or directory: '/home/xtian/Documents.x/Projects/config/helloworld_input'
has answer: http://stackoverflow.com/a/49869200
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49869267
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49869267
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49869200

http://stackoverflow.com/q/49912739
linked to: http://stackoverflow.com/q/49748063
type: Question
linked to: http://stackoverflow.com/q/49768770
type: UnansweredQuestion
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/86863965
has body: I am trying to do pip install to install tensorflow in my computer. I am behind company proxy and I am bypassing SSL cert so normally I would use this command pip --proxy 0.0.0.0:80 --trusted-host pypi.python.org install tensorflow It normally works well but just today pip install keeps throwing SSL certificate error to me: Collecting tensorflow Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),)': /simple/tensorflow/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),)': /simple/tensorflow/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),)': /simple/tensorflow/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),)': /simple/tensorflow/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),)': /simple/tensorflow/ Could not fetch URL https://pypi.python.org/simple/tensorflow/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/tensorflow/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),)) - skipping Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow I tried to use curl and it works: curl -x 0…
score: 0
has title: Pip install in windows does not work due to ssl issue
has comment: http://stackoverflow.com/comment/86869579
answer count: 1
has answer: http://stackoverflow.com/a/49913962

http://stackoverflow.com/comment/86558212
comment on: http://stackoverflow.com/a/49771481
has text: Same reason ;-) I updated my answer, so you can copy&paste if you want to.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49980800
accepted answer of: http://stackoverflow.com/q/49854214
score: 1
type: Answer
has body: What you need is the waitKey function. It holds execution of your code for the number of milliseconds specified in the argument. So if you want to wait for 3 seconds, you can decrement in milliseconds instead of seconds, as shown below: import numpy as np import cv2 cap = cv2.VideoCapture(0) seconds = 3 millis = seconds * 1000 while (millis &gt; 0): # Capture frame-by-frame ret, frame = cap.read() millis = millis - 10 # Display the resulting frame cv2.imshow('video recording', frame) if cv2.waitKey(10) &amp; 0xFF == ord('q'): #this method holds execution for 10 milliseconds, which is why we #reduce millis by 10 break #once the while loop breaks, write img img_name = "example.png" cv2.imwrite(img_name, frame) print("{} written!".format(img_name))
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49854214

http://stackoverflow.com/comment/86624427
comment on: http://stackoverflow.com/q/49804654
score: 0
type: Comment
has text: @abarnert I'm not installing Cython with Anaconda, so it must be using a pip-installed Cython.
type: QuestionComment

http://stackoverflow.com/comment/86768186
type: Comment
comment on: http://stackoverflow.com/q/49875399
type: QuestionComment
score: 0
has text: @arsho no error messages, it simply not updating but while i print validate data inside update() code, updated dropdown values ( in PUT fn) are shown in my terminal

http://stackoverflow.com/a/49785217
type: Answer
score: 3
upvote count: 3
downvote count: 0
has body: By adding drop=False within set_index then, with str.contains + fillna we achieve the expected output dfs = [df_a.set_index(['type_1','subject_id_1'],drop=False), df_b.set_index(['type_2','subject_id_2'],drop=False), df_c.set_index(['type_3','subject_id_3'],drop=False)] df = pd.concat(dfs, axis=1) df.loc[:,df.columns.str.contains('type')]=df.loc[:,df.columns.str.contains('type')].apply(lambda x : x.fillna(df.index.to_frame()[0]).astype(int)) df.loc[:,df.columns.str.contains('subject_id')]=df.loc[:,df.columns.str.contains('subject_id')].apply(lambda x :x.fillna(df.index.to_frame()[1]).astype(int))
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49785127
answers question: http://stackoverflow.com/q/49785127

http://stackoverflow.com/comment/86727848
type: QuestionComment
score: 0
has text: @Joaquin, please read up on dictionaries in the [docs](https://docs.python.org/3/tutorial/datastructures.html#dictionaries).
comment on: http://stackoverflow.com/q/49856694
type: Comment

http://stackoverflow.com/comment/86785292
score: 0
type: AnswerComment
type: Comment
has text: Actually, I mean to be `emp` instead of vendor :) I don't think it needs to be sorted.
comment on: http://stackoverflow.com/a/49884395

http://stackoverflow.com/a/49862741
downvote count: 0
has body: You should use unchecked-byte when it's OK to overflow: (unchecked-byte 234) =&gt; -22 FYI it's also possible to toggle the default behavior with the *unchecked-math* binding: (set! *unchecked-math* true) =&gt; true (byte 234) =&gt; -22 But you probably want to constrain this non-default behavior to the smallest scope possible.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49862614
upvote count: 3
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49862614

http://stackoverflow.com/comment/86796782
comment on: http://stackoverflow.com/a/49885282
type: Comment
has text: So if I do this I would be doing all the backend functions as methods inside `window_home`?
type: AnswerComment
score: 0

http://stackoverflow.com/q/49890196
tagged with: python
has body: I have a question about import different branch of a repo on Google Colab. Autograd(https://github.com/HIPS/autograd) have a cupy-adaptable version which lies in another branch(https://github.com/HIPS/autograd/tree/cupy).I want to import autograd(cupy-friendly version into google colab and used following command: !pip install git+git://github.com/ericmjl/autograd/tree/cupy but it have following errors: Collecting git+git://github.com/ericmjl/autograd/tree/cupy Cloning git://github.com/ericmjl/autograd/tree/cupy to /tmp/pip-yoasr9_z-build fatal: remote error: ericmjl/autograd/tree/cupy is not a valid repository name Email support@github.com for help Command "git clone -q git://github.com/ericmjl/autograd/tree/cupy /tmp/pip-yoasr9_z-build" failed with error code 128 in None Is there anybody who can help me with that? Thanks so much!!
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
tagged with: branch
tagged with: github
answer count: 1
tagged with: import
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49890291
tagged with: cupy
has answer: http://stackoverflow.com/a/49890291
has title: How to import different branch of a package(based on python) in GitHub to local computer?

http://stackoverflow.com/a/49792095
has comment: http://stackoverflow.com/comment/86602148
has comment: http://stackoverflow.com/comment/86602571
has comment: http://stackoverflow.com/comment/86701044
answers question: http://stackoverflow.com/q/49791178
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86600421
has comment: http://stackoverflow.com/comment/86602323
type: Answer
has body: After struggling for a while, I was so willing to make myself clear of this issue, so I searched for a while, and just figured out and tested. When you create a new conda env by specifying the python version, it will use the conda_root_python version. And if you didn't install the pip package, and try to use pip under your created conda env, it will only run the conda_root_pip and install the package in the root site_packages. I know three ways to install python packages only in your created conda env. For a better explanation, we create a conda env with same python version of conda root environment. conda create -n myenv python I. One of the officials advise, install package with conda command for specified conda environment, conda install -n myenv tensorflow II. Another one of official advise, get into your specified environment and run conda install source activate myenv conda install tensorflow in above two ways you don't need to install extra packages like pip and other pip related packages. III. For people who really want to pip, just because get used of that. install pip package(just as above two ways did). conda install -n myenv pip or source active myenv conda install pip then comes the pip install when you are in your environment pip install tensorflow --------new edit above 15.April.2018-------------- Just to make it more clear. If you are working under anaconda environment, you should also install all the modules and IDE you need in that environment. Here I just put one example of anaconda env flows: conda create --name=my_conda_env python=2.7 #create an environment activate my_conda_env #get into that env pip install numpy #install packages you need ... pip install keras_contrib pip install spyder #install IDE Getting Started with conda --------- Try install in root activate root pip install keras_conrib go back to your tensorflow start your spyder and try again Maybe this is your issue Module installed on Conda, but gives error on importing in Spyder (…

http://stackoverflow.com/q/49789862
possible better answer: http://stackoverflow.com/a/49790407
score: 1
linked to: http://stackoverflow.com/q/35137952
accepted answer: http://stackoverflow.com/a/49792125
has title: python - pandas append dataframe failing
tagged with: append
favorite count: 0
has answer: http://stackoverflow.com/a/49792125
type: Question
answer count: 2
tagged with: concatenation
downvote count: 0
has answer: http://stackoverflow.com/a/49790407
upvote count: 1
tagged with: python
has body: I am trying to concatenate three separate dataframes (bs_df, income_df, cash_df) of each ticker then append them into a dataframe df. It successfully appends the dataframe the first time it goes through the for loop, but when it tries to append the new dataframe to the original dataframe, it fails to do so and throws an Assertion Error. I think it's because the dataframes have different columns (reference), but I cannot figure out a way to bypass this and still create a dataframe with all the column names and fill in with NaN values if a dataframe does not have the value for a specific column that the other dataframe has. Here is the code I am running: from yahoofinancials import YahooFinancials import pandas as pd tickers = ["PIH","AAPL","AMZN"] df = pd.DataFrame() for ticker in tickers: print (ticker) # Updates every loop ticker_yahoo_financials = YahooFinancials(ticker) # Get financial info bs_hist = ticker_yahoo_financials.get_financial_stmts('annual', 'balance') income_hist = ticker_yahoo_financials.get_financial_stmts('annual', 'income') cash_hist = ticker_yahoo_financials.get_financial_stmts('annual', 'cash') # Create dataframes and comebine them bs_df = pd.DataFrame(list(bs_hist['balanceSheetHistory'][ticker][0].values())) income_df = pd.DataFrame(list(income_hist['incomeStatementHistory'][ticker][0].values())) cash_df = pd.DataFrame(list(cash_hist['cashflowStatementHistory'][ticker][0].values())) comb = pd.concat([bs_df, income_df, cash_df], axis=1) df = df.append(comb) Here is the error message: --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) &lt;ipython-input-23-f476ca9fbb70&gt; in &lt;module&gt;() 19 cash_df = pd.DataFrame(list(cash_hist['cashflowStatementHistory'][ticker][0].values())) 20 comb = pd.concat([bs_df, income_df, cash_df], axis=1) ---&gt; 21 df = df.append(comb) C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in append(self, other, ignore_index, verif…
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/a/49839252
has body: Simply use line.split() for each string line. It also works on lines with more than two coordinates. Examples: line = "934 100", x, y = line.split(), print(x,y) = 934 100 line = "1 61 298 3333 ", a, b, c, d = line.split(), print(a,b,c,d) = 1 61 298 3333
score: 0
accepted answer of: http://stackoverflow.com/q/49839185
answers question: http://stackoverflow.com/q/49839185
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/49858968
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
has answer: http://stackoverflow.com/a/49859107
has body: Forgive me if this is obvious, but I can't tell from the documentation whether the output when using a queue is ordered. That is, if the inputs are [1, 2, 3] will the outputs be f(1), f(2), f(3), or can they be out of order? Edit: I understand that the inputs are handled in FIFO. But does FIFO retrieval necessarily guarantee that the results are also returned in order?
has answer: http://stackoverflow.com/a/70303849
type: UnansweredQuestion
tagged with: python
answer count: 6
score: 4
downvote count: 1
favorite count: 0
has title: Are Python Multiprocessing Queues Ordered?
has answer: http://stackoverflow.com/a/60517449
has answer: http://stackoverflow.com/a/49859267
has answer: http://stackoverflow.com/a/79309891
upvote count: 5
has answer: http://stackoverflow.com/a/69815820

scipy
tags question: http://stackoverflow.com/q/49873446
tags question: http://stackoverflow.com/q/49799535
tags question: http://stackoverflow.com/q/49804670
tags question: http://stackoverflow.com/q/49826125
tags question: http://stackoverflow.com/q/49879324
tags question: http://stackoverflow.com/q/49852703
tags question: http://stackoverflow.com/q/49769952
tags question: http://stackoverflow.com/q/49860866
tags question: http://stackoverflow.com/q/49805647
tags question: http://stackoverflow.com/q/49821159
tags question: http://stackoverflow.com/q/49899039
tags question: http://stackoverflow.com/q/49796019
tags question: http://stackoverflow.com/q/49778057
tags question: http://stackoverflow.com/q/49857526
tags question: http://stackoverflow.com/q/49766806
tags question: http://stackoverflow.com/q/49913737
tags question: http://stackoverflow.com/q/49837400
tags question: http://stackoverflow.com/q/49780821
tags question: http://stackoverflow.com/q/49814258
tags question: http://stackoverflow.com/q/49904819
tags question: http://stackoverflow.com/q/49806961
type: Tag
tags question: http://stackoverflow.com/q/49761020
tags question: http://stackoverflow.com/q/49847946
tags question: http://stackoverflow.com/q/49781991
tags question: http://stackoverflow.com/q/49835342
tags question: http://stackoverflow.com/q/49867706
tags question: http://stackoverflow.com/q/49909487
tag name: scipy
tags question: http://stackoverflow.com/q/49802950
tags question: http://stackoverflow.com/q/49818846
tags question: http://stackoverflow.com/q/49805529
tags question: http://stackoverflow.com/q/49853578
tags question: http://stackoverflow.com/q/49869050
tags question: http://stackoverflow.com/q/49861354
tags question: http://stackoverflow.com/q/49891074
tags question: http://stackoverflow.com/q/49896377
tags question: http://stackoverflow.com/q/49907180
tags question: http://stackoverflow.com/q/49845195
tags question: http://stackoverflow.com/q/49820329
tags question: http://stackoverflow.com/q/49861468
tags question: http://stackoverflow.com/q/49806651
tags question: http://stackoverflow.com/q/49764662
tags question: http://stackoverflow.com/q/49758371
tags question: http://stackoverflow.com/q/49881561
tags question: http://stackoverflow.com/q/49905190
tags question: http://stackoverflow.com/q/49848209
tags question: http://stackoverflow.com/q/49913275
tags question: http://stackoverflow.com/q/49763568
tags question: http://stackoverflow.com/q/49870998
tags question: http://stackoverflow.com/q/49825342
tags question: http://stackoverflow.com/q/49848962
tags question: http://stackoverflow.com/q/49799906
tags question: http://stackoverflow.com/q/49911442
tags question: http://stackoverflow.com/q/49878701
tags question: http://stackoverflow.com/q/49765174
tags question: http://stackoverflow.com/q/49868167
tags question: http://stackoverflow.com/q/49776015
tags question: http://stackoverflow.com/q/49786670

http://stackoverflow.com/comment/86748616
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49865952
has text: To which competition does this apply?
score: 0

http://stackoverflow.com/comment/86839849
comment on: http://stackoverflow.com/q/49887476
type: Comment
score: 0
type: QuestionComment
has text: @bimsapi, the H10 error persists after implementing the suggested changes, is there any other possible cause?

http://stackoverflow.com/q/49884864
has comment: http://stackoverflow.com/comment/86786566
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/86788158
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86801728
has title: python program is super slow, and I can't find out why
tagged with: neural-network
has comment: http://stackoverflow.com/comment/86786422
favorite count: 0
has body: I'm writing a multi-layer perceptron from scratch and I think it's way slower than it should be. the culprit seems to be my compute_gradients-function, which according to my investigation answers for most of the execution time. It looks like this: def compute_gradients(X, Y, S1, H, P, W1, W2, lamb): # Y must be one-hot # Y and P must be (10, n) # X and H must be (3072, n) # P is the softmax layer if not (Y.shape[0] == 10 and P.shape[0] == 10 and Y.shape == P.shape): raise ValueError("Y and P must have shape (10, k). Y: {}, P: {}".format(Y.shape, P.shape)) if not X.shape[0] == n_input: raise ValueError("X must have shape ({}, k), has {}".format(n_input, X.shape)) if not H.shape[0] == n_hidden: raise ValueError("H must have shape ({}, k)".format(n_hidden)) grad_W1 = np.zeros([n_hidden, n_input]) grad_W2 = np.zeros([10, n_hidden]) grad_b1 = np.zeros([n_hidden, 1]) grad_b2 = np.zeros([10, 1]) X, Y, H, P = X.T, Y.T, H.T, P.T for x, y, s1, h, p in zip(X, Y, S1, H, P): h = np.reshape(h, [1, n_hidden]) y = np.reshape(y, [10, 1]) p = np.reshape(p, [10, 1]) # Second layer g = -(y-p).T grad_b2 += g.T grad_W2 += np.matmul(g.T, h) # First layer g = np.matmul(g, W2) ind = np.zeros(h.shape[1]) for i, val in enumerate(s1): if val &gt; 0: ind[i] = 1 diag = np.diag(ind) g = np.matmul(g, diag) grad_b1 += g.T grad_W1 += np.matmul(g.T, np.reshape(x, [1, n_input])) # Divide by batch size grad_b1 /= X.shape[0] grad_b2 /= X.shape[0] grad_W1 /= X.shape[0] grad_W2 /= X.shape[0] # Add regularization term grad_W1 += 2*lamb*W1 grad_W2 += 2*lamb*W2 return grad_W1, grad_W2, grad_b1, grad_b2 If X, Y, H, P are all 10 rows long (n=10), the computations take about 1 second. This is way too much compared to my friends who are doing the same task. But I can't see any obvious inefficiencies in my code. What can I do to speed the computations up? EDIT: Input data is the CIFAR dataset. Load it like this: def one_hot(Y): # assume Y = [1, 4, 9, 0, ...] result = [None]*len(Y) for i, cls in enumerate(Y): oneh…
has comment: http://stackoverflow.com/comment/86786099
type: Question
has comment: http://stackoverflow.com/comment/86787119
has comment: http://stackoverflow.com/comment/86786783
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86786375
has comment: http://stackoverflow.com/comment/86785944
tagged with: python
has comment: http://stackoverflow.com/comment/86786076
has comment: http://stackoverflow.com/comment/86786887
has comment: http://stackoverflow.com/comment/86788020
has comment: http://stackoverflow.com/comment/86788917
tagged with: numpy

http://stackoverflow.com/q/49860182
has title: Normalizing inputs decreases accuracy
type: Question
has comment: http://stackoverflow.com/comment/86735503
tagged with: python
has body: I am training a neural network for audio classification. I implemented normalization of the inputs as it is suggested in any book/course about neural networks. I normalized them to have 0 mean and unit variance. The problem is that I did not get better accuracy, neither in the training nor in the test set. On the contrary, both accuracies reduced considerably (4-8%) I implemented it as follows: mean = np.mean(X_train, axis = 0) std = np.std(X_train, axis = 0) X_train = (X_train-mean)/std X_test = (X_test-mean)/std # apply the same transformation to the test set X_val = (X_val-mean)/std # apply the same transformation to the validation set Where X_train is a matrix of dimensions (4000,60,130,1) where (batch, height, width, #channels) Did I do something wrong with the code or my problem might be somewhere else? Is normalization of the inputs always supossed to improve accuracy and/or time of convergence of the optimization algorithm?
tagged with: normalization
answer count: 0
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86759201
tagged with: neural-network

http://stackoverflow.com/q/49864945
type: Question
has comment: http://stackoverflow.com/comment/86745275
has comment: http://stackoverflow.com/comment/86745433
has body: I am struggling a little with this. I have pieced together some code to get Python to Telnet/SSH to a group of switches. It runs show ip interface brief and show run. It then takes that creates one file per IP and combines the output from both. I then pick it up and run regex against it to parse info for a database. Here is the regex I used ([A-Za-z]+)(\d+)/(\d+)/?(\d?)\W+(\S+)\W+(\S+)\W+\S+\W+(\S+)(\W+)(\S+) But I would expect the right way is to use. ^([A-Za-z]+)(\d+)/(\d+)/?(\d?)\W+(\S+)\W+(\S+)\W+\S+\W+(\S+)(\W+)(\S+) A sample of the text is below. I want it to just pickup on lines that begin with FastEthernet (Could Be GigabitEternet...) Interface IP-Address OK? Method Status Protocol Vlan1 192.168.3.2 YES NVRAM up up FastEthernet0/1/2 unassigned YES unset up up FastEthernet0/2 unassigned YES unset up up FastEthernet0/3 unassigned YES unset up up FastEthernet0/4 unassigned YES unset up up FastEthernet0/5 unassigned YES unset up up FastEthernet0/6 unassigned YES unset up up interface FastEthernet0/3 description Karen switchport mode access switchport port-security switchport port-security mac-address sticky no ip address spanning-tree portfast
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86745327
has comment: http://stackoverflow.com/comment/86746251
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49865070
has comment: http://stackoverflow.com/comment/86745783
has comment: http://stackoverflow.com/comment/86745795
has answer: http://stackoverflow.com/a/49865070
score: 1
answer count: 1
has title: regex is not working python
has comment: http://stackoverflow.com/comment/86745856
tagged with: python
has comment: http://stackoverflow.com/comment/86745272
tagged with: regex

http://stackoverflow.com/a/49815667
score: 1
type: Answer
has body: You can use mysqldump for this task. (Source for command) mysqldump -u username -p --tab -T/path/to/directory dbname table_name --fields-terminated-by=',' The arguments are as follows: -u username for the username -p to indicate that a password should be used -ppassword to give the password via command line --tab Produce tab-separated data files For mor command line switches see https://dev.mysql.com/doc/refman/5.5/en/mysqldump.html To run it on a regular basis, create a cron task like written in the other answers.
downvote count: 0
answers question: http://stackoverflow.com/q/49813964
upvote count: 1

http://stackoverflow.com/a/49880498
upvote count: 1
has body: As the exception says - you cannot use expressions as keywords so this: Row( jsn['column1'] = r[0], jsn['column2'] = r[1]) is not a valid Python code. You can use alternative constructor and then apply arguments: Row(jsn['column1'], jsn['column2'])(r[0], r[1]) but in general there it would be better to tmp = spark.read.option("delimiter", "|").csv("testdata") df = tmp.select(tmp.columns[2:]).toDF(jsn['column1'], jsn['column2'])
answers question: http://stackoverflow.com/q/49877253
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/86789196
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49886388
has text: url(r"^download_zip_file/$",SearchView.as_view(),name="lexisnexisearch.SearchView") .

http://stackoverflow.com/comment/86569167
type: QuestionComment
type: Comment
score: 1
has text: @jezrael thanks man... was wondering whether it was a dupe, but could not find one so am posting an answer ...
comment on: http://stackoverflow.com/q/49776936

http://stackoverflow.com/comment/86572369
type: Comment
has text: Constructing file paths as `data_dir_path + month_path + filename` is a bad idea. Whenever possible `os.path.join()` should be used.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49778519

http://stackoverflow.com/comment/86638982
has text: `ClassTester.age = 20`
type: QuestionComment
comment on: http://stackoverflow.com/q/49812261
score: 1
type: Comment

http://stackoverflow.com/a/49779174
answers question: http://stackoverflow.com/q/49777262
has body: Here is a version without using itertools: def tmp_func(a,b): i = 0 m = len(max(a,b)) len_diff = len(a) - len(b) if(len_diff &lt; 0): a.extend(abs(len_diff)*['']) elif (len_diff &gt; 0): b.extend(abs(len_diff)*['']) while i &lt; m: yield (a[i], b[i]) i=i+1 a = ['a','b', 'c'] b = ['a', 'b'] list(map(lambda x: x[0]==x[1], tmp_func(a,b))) Output: [True, True, False]
score: 1
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/86570126
type: Comment
comment on: http://stackoverflow.com/a/49776743
type: AnswerComment
has text: Yep. I'd advise you read up on it [here](https://pandas.pydata.org/pandas-docs/stable/indexing.html).
score: 0

http://stackoverflow.com/comment/86617649
type: Comment
comment on: http://stackoverflow.com/a/49799930
score: 0
type: AnswerComment
has text: yea its strange as the error you are reporting as coming back is more of an interface issue not expecting a keyword. I've added something else to my answer you can try, creating it from the class instead

http://stackoverflow.com/a/49932353
answers question: http://stackoverflow.com/q/49887717
type: AcceptedAnswer
has body: I was able to reproduce your issue using pyodbc 4.0.23. The MemoryError was related to your use of the ancient DRIVER={SQL Server} Further testing using DRIVER=ODBC Driver 11 for SQL Server also failed, with Function sequence error (0) (SQLParamData) which was related to an existing pyodbc issue on GitHub. I posted my findings here. That issue is still under investigation. In the meantime you might be able to proceed by using a newer ODBC driver like DRIVER=ODBC Driver 13 for SQL Server, and running pip install pyodbc==4.0.22 to use an earlier version of pyodbc.
downvote count: 0
has comment: http://stackoverflow.com/comment/86991820
type: Answer
upvote count: 29
score: 29
accepted answer of: http://stackoverflow.com/q/49887717
has comment: http://stackoverflow.com/comment/99837116

http://stackoverflow.com/comment/86534389
type: Comment
type: QuestionComment
has text: Have you considered using datetime objects rather than string representations of dates?
score: 2
comment on: http://stackoverflow.com/q/49759661

http://stackoverflow.com/a/49878619
has body: To get the slope of your line you need to calculate (y2 - y1) / (x2 - x1). You are doing (y2 - x2) / (y1 - x1). So you just need to calculate the correct slope by o = np.subtract(2, 5) # y[1] - y[0] q = np.subtract(7, 0) # x[1] - x[0] slope = o/q which will give a slope of approx. -0.42857. This will give you the following plot:
score: 2
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49877370

http://stackoverflow.com/a/72916860
type: Answer
has body: For me I got this error once I was trying to fix this issue raise TypeError("option values must be strings") TypeError: option values must be strings so I tried to stringify the url like so config.set_main_option( "sqlalchemy.url", f'{os.environ.get("DATABASE_URL")}') After that I got new error because os.environ.get() does not return the Environment Value in windows without exporting the value, here is the error I got sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'None' So I should either export the value than get it with os.environ.get() or use a config file and get it like so: config.set_main_option( "sqlalchemy.url", settings.database_url.replace("postgres://", "postgresql+asyncpg://", 1)) A detail about how to get env vars using config file you can find it on this answer os.environ.get() does not return the Environment Value in windows?
answers question: http://stackoverflow.com/q/49776619
score: 0

http://stackoverflow.com/comment/86836341
type: Comment
has text: {% load static %} is there. I am able to load images through the HTML BUT not through the CSS file. How do I load it? #home{ background-image: url('store/img/store.jpg') no-repeat; } ..... this is not working
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49910082

http://stackoverflow.com/comment/87044798
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49900521
score: 0
has text: Possible duplicate of [Not able to install python packages \[SSL: TLSV1\_ALERT\_PROTOCOL\_VERSION\]](https://stackoverflow.com/questions/49768770/not-able-to-install-python-packages-ssl-tlsv1-alert-protocol-version)

http://stackoverflow.com/a/49852313
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49852022
has body: We can first sort on n%2 (n modulo 2), which will be 0 for odd numbers and 1 for even ones, then on the number itself: L = [5,6,4,7,11,14,12,1,3] out = sorted(L, key = lambda n:(n%2, n)) print(out) # [4, 6, 12, 14, 1, 3, 5, 7, 11] The tuples we use as a key are sorted according to their first item first, then to their second. And it will also work for negative numbers...
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/86834205
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49908787
type: QuestionComment
has text: "Random errors" can include I/O errors, which happen but over which you have no control.

http://stackoverflow.com/a/49816016
has body: Cloud Dataflow is a batch data processing, Cloud Dataproc is a managed Spark and Hadoop service and Cloud Dataprep is used to Transform/Clean raw data. All of them can be used to perform interpolation/resampling of data. I would discard Cloud Dataprep. It might change in backward-incompatible ways because is in beta release. The main difference between Cloud Dataflow and Cloud Dataproc is the cluster management capabilities in the last one. If you do not expect a clear comeback by managing clusters, Cloud Dataflow is the product in which you can set up the mentioned operations in the easiest way. Apache Beam Java version is older than Python version since Apache Beam 1.X supports only Java. The new 2.X version supports both languages with no apparent Python/Java difference. You will find useful this Dataflow timeseries example in Java if you decide that Dataflow is the best suited option.
type: Answer
answers question: http://stackoverflow.com/q/49809084
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/49795823
answer count: 0
has body: VS Code 1.22.1 Linux Language: Python I have a specific file within a project to which I recently copied text from the terminal to include it in a docstring. By doing so I accidentally changed the indentation for that file to 2 spaces. All other files remain indented with 4 spaces. But even if I change back to 4 spaces for that specific file, it changes back to 2 spaces the next time I start VS Code. What am I missing and how can I fix this?
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86606061
favorite count: 0
type: Question
type: UnansweredQuestion
score: 1
has title: VS Code Python: Wrong indentation for file
has comment: http://stackoverflow.com/comment/86606434
tagged with: python
has comment: http://stackoverflow.com/comment/86606841
tagged with: visual-studio-code

http://stackoverflow.com/q/49794808
answer count: 3
tagged with: pandas
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49795019
has answer: http://stackoverflow.com/a/49794843
has answer: http://stackoverflow.com/a/49795875
downvote count: 1
favorite count: 0
type: Question
has body: list1 = [1,2,3] list2 = [3,5,6] list3 = [4,5,6] I want output in csv file as: A B C 1 3 4 2 5 5 3 6 6 I tried using pandas as well as np.savetxt() but it doesnt work!
score: 3
has title: write list columnwise in csv file using python
tagged with: python
upvote count: 4
tagged with: export-to-csv

http://stackoverflow.com/q/49815577
type: UnansweredQuestion
has title: Change color of text in GTK 3.0
linked to: http://stackoverflow.com/q/41452162
tagged with: python
tagged with: gtk
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49815817
has body: I am using a Gtk.TextBuffer() inside a Gtk.TextView() to write some text on the screen. I wish to change colors of the text while writing often. eg. In Green -- Printing Green color In Red -- Printing Red color In Green -- Printing Green color In Red -- Printing Red color Can you please suggest some function to do this.
tagged with: gtk3
type: Question
has answer: http://stackoverflow.com/a/57317662
has comment: http://stackoverflow.com/comment/86645355

http://stackoverflow.com/a/49903166
type: Answer
accepted answer of: http://stackoverflow.com/q/49902930
has comment: http://stackoverflow.com/comment/86824687
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86824285
has body: I think you can check by first reading in the csv, and then checking which rows wouldn't convert. This finds them all at once, instead of one by one with the ValueError. Just remember, python begins numbering at 0 and wont include the header so the row indices of the df will be off from those in the csv (by 1 or 2). import pandas as pd df = pd.read_excel(xl) # Example df column1 column2 0 100 A 1 100% B 2 112,312 C 3 171 D 4 123.123 E 5 NaN F df['column1_num'] = pd.to_numeric(df.column1, errors='coerce') bad_mask = (df.column1_num.isnull()) &amp; ~(df.column1.astype('str').str.lower().isin(['nan'])) bad_rows = df[bad_mask].index.values #array([1, 2], dtype=int64) df[bad_mask] # column1 column2 column1_num #1 100% B NaN #2 112,312 C NaN I updated the mask because float is able to handle the 'NaN' string, so it wont actually show up as an issue in your read, though pd.to_numeric still coerces it to NaN. float('NaN') #nan pd.to_numeric('NaN') #ValueError: Unable to parse string "NaN" at position 0
answers question: http://stackoverflow.com/q/49902930

http://stackoverflow.com/a/77880402
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/139313911
downvote count: 0
has body: ntfy is exactly what you want. ntfy, it is free, open source, no personal data to share, and takes 2 minutes to setup. Doc is here, you just have to: Download the app on Android or iOS Choose a key (e.g. stack_overflow, but you probably want something more unique since everything is public with the key) Subscribe to the server on the app with your key. Then with a simple line of code, you can send any notification on your phone with request on URL https://ntfy.sh/your_key_here Examples: curl curl -d "Hi from curl :)" ntfy.sh/stack_overflow Python import requests requests.post("https://ntfy.sh/stack_overflow", data="Hi from Python :)".encode(encoding='utf-8')) JavaScript fetch('https://ntfy.sh/stack_overflow', { method: 'POST', // PUT works too body: 'Hi from JavaScript :)' })
upvote count: 7
answers question: http://stackoverflow.com/q/49879993

http://stackoverflow.com/a/69038307
answers question: http://stackoverflow.com/q/49901824
type: Answer
has body: Kinda an old question but I have the answer: DON'T USE STARMAP; USE MAP. Given, pool.starmap(func, list_of_dictionaries) Instead do: pool.map(func, list_of_dictionaries) Context From the docs, The difference between map() and starmap() parallels the distinction between function(a,b) and function(*c). So using starmap with a list of dictionaries will unpack the dictionaries keys as the arguments; which is not what you want at all. Full example Broken using starmap from multiprocessing import Pool data = [ {"name": "Delphi"}, {"name": "Orion"}, {"name": "Asher"}, {"name": "Baccus"} ] def fun(*args): print(args) with Pool(4) as pool: pool.starmap(fun,data) #Prints: """ $> name $> name $> name $> name """ Working using map from multiprocessing import Pool data = [ {"name": "Delphi"}, {"name": "Orion"}, {"name": "Asher"}, {"name": "Baccus"} ] def fun(object): print(object) with Pool(4) as pool: pool.map(fun,data) #Prints: """ $> {"name": "Delphi"} $> {"name": "Orion"} $> {"name": "Asher"} $> {"name": "Baccus"} """
has comment: http://stackoverflow.com/comment/122572433
score: 1
downvote count: 1
upvote count: 2

http://stackoverflow.com/comment/86718081
type: QuestionComment
has text: Possible duplicate of [Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""](https://stackoverflow.com/questions/24627525/fatal-error-in-launcher-unable-to-create-process-using-c-program-files-x86)
type: Comment
score: 4
comment on: http://stackoverflow.com/q/49851668

http://stackoverflow.com/q/49874590
has title: Problems when using tf.data.Dataset.batch
type: AnsweredQuestion
has body: I want to make clear how tf.data.Dataset.batch work with my dataset. The dataset is as follows: dataset = tf.convert_to_tensor([[5.1, 3.3, 1.7, 0.5, ], [5.9, 3.0, 4.2, 1.5], [6.9, 3.1, 5.4, 2.1], [2.3, 1.3, 6.4, 9.3]]) Then I use batch method: dataset = dataset.batch(2) and iterate the dataset once. x = tfe.Iterator(dataset).next() As I suppose, the result should be a 2*4 array, but it returns the whole 4*4 dataset. Could anyone give me some details about how to apply the batch method?
has answer: http://stackoverflow.com/a/49874888
score: 1
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49874888
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: python

http://stackoverflow.com/a/49775098
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49770492
score: 0
has body: When using a pymysql.cursors.DictCursor cursor the fetched data is returned as a dictionary, therefore you can use all the common dict traversal/accessing/modifying methods on it. This means that you can access your returned hash as: user["hash"]. When it comes to JSON, Python comes with a built-in json module that can readily convert your retrieved dict into a JSON string, so in your case, to get a JSON representation of the returned user dictionary use: import json json_string = json.dumps(user) print(json_string) # or do whatever you need with it
answers question: http://stackoverflow.com/q/49770492

http://stackoverflow.com/comment/86768008
type: Comment
comment on: http://stackoverflow.com/a/49869004
type: AnswerComment
has text: Great, congrats!
score: 0

http://stackoverflow.com/comment/86573723
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49778904
type: Comment
has text: @Imas That's alright, providing code (even if it doesn't do what you want it to do), allows other users to more easily develop code that fits in with what you're doing in a way that you can understand, it also shows that you've given the problem some thought and research before coming to SO

http://stackoverflow.com/comment/86663486
has text: Sure, didn't know how to implement a python code other then that way.
score: 0
comment on: http://stackoverflow.com/q/49823770
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49868678
answer count: 1
has comment: http://stackoverflow.com/comment/86754470
tagged with: python
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/86755434
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49869889
has answer: http://stackoverflow.com/a/49869889
type: Question
has body: I am new to AWS, im trying to write a function whenever there is a new object created in s3 bucket, rekognition will start analysis. I looked at AWS documentation for lambda function handler(python), it gives a general syntax structure for handling, but what operators should I use to call the name of new object in s3 bucket? I hardly find any, can anyone please help? thank you so much import boto3 client = boto3.client('rekognition') s3 = boto3.resource('s3') bucket = s3.bucket('my_bucket') for obj in bucket.object.all(): print(obj.key) def my_handler(event,context): income_Name = event.***** # not sure what operator here? response = client.search_faces_by_image( CollectionId='my_collection', Image={ #'Bytes': b'bytes', 'S3Object': { 'Bucket': 'my_bucket', 'Name': income_name, }, MaxFaces=123, FaceMatchThreshold=70 ) return response[]
has title: aws lambda function handler python
tagged with: handler

http://stackoverflow.com/a/49880840
score: 0
answers question: http://stackoverflow.com/q/49879789
type: Answer
has body: Here a solution: with open('test.txt') as infile, open('output.txt', 'w') as outfile: lines = "\n".join([line.strip() for line in infile if line.strip()]) outfile.writelines(lines)

http://stackoverflow.com/comment/86813018
has text: Sure. Post then that as the answer and accept it so if someone searching for a similar issue and gets here, will find the solution easily.
type: AnswerComment
comment on: http://stackoverflow.com/a/49826833
score: 0
type: Comment

http://stackoverflow.com/a/49898419
has body: You can use exact class name to avoid fetching Next link: //a[@class="page-numbers"][last()] Note that contains(@class,'page-numbers') will return you links with numbers and Next while @class="page-numbers" numbers only
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49897682
score: 4
answers question: http://stackoverflow.com/q/49897682
has comment: http://stackoverflow.com/comment/86812422
downvote count: 0
type: Answer
upvote count: 4

http://stackoverflow.com/q/49909113
has answer: http://stackoverflow.com/a/49909854
possible better answer: http://stackoverflow.com/a/49909854
tagged with: button
has title: How do I use a Tkinter Button for two states?
accepted answer: http://stackoverflow.com/a/49909160
favorite count: 0
has comment: http://stackoverflow.com/comment/86834313
type: Question
has comment: http://stackoverflow.com/comment/86834147
has comment: http://stackoverflow.com/comment/86834293
has body: I have the following code, which causes a color/text change when a Tkinter button is clicked. I would like to revert to the original color/text when the button is clicked a second time. from Tkinter import * window = Tk() window.title("Start/Stop Button") window.geometry('200x100') def clicked_rf1(): btn_rf1.configure(text="Stop") lbl_rf1.configure(text=" ON ", bg="green") btn_rf1 = Button(window, text="Start", command=clicked_rf1) btn_rf1.grid(column=1, row=1) lbl_rf1 = Label(window, text=" OFF ", bg="red") lbl_rf1.grid(column=2, row=1) window.mainloop() I want something that behaves a little more like a toggle, but I would like the look of a button. Help gratefully received.
tagged with: python
has answer: http://stackoverflow.com/a/49909160
has answer: http://stackoverflow.com/a/49909291
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: tkinter
answer count: 3
downvote count: 0

http://stackoverflow.com/q/49827112
type: Question
tagged with: django-2.0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/130353875
tagged with: python
upvote count: 7
has title: How to upload multiple images from a single "Choose Files" selector in django admin
has body: I'm doing this little project simulating a clothing ordering system to brush up my django skills. I have to add several pictures of a certain item(not a fixed number). So, using a fixed number of image fields in Item model is not ideal. So, I thought of another model consisting only of images connected to the model 'items' by a key. Now I know that django has the inline option for adding model objects one by one as per requirement. But that seems a bit of a sucker as you have to open that dialog box and select the images one by one. Is it possible that there be a selector via which we could choose multiple files at once and they be added to the model??
has answer: http://stackoverflow.com/a/49836079
answer count: 2
linked to: http://stackoverflow.com/q/59922054
score: 7
has answer: http://stackoverflow.com/a/59070997
has comment: http://stackoverflow.com/comment/86670614
downvote count: 0
linked to: http://stackoverflow.com/q/34006994
has comment: http://stackoverflow.com/comment/107852020
favorite count: 0

http://stackoverflow.com/q/49791246
possible better answer: http://stackoverflow.com/a/49792609
favorite count: 0
type: Question
has body: I have got a dataframe like this: import pandas as pd data = { 'c1': ['Test1','Test2','NULL','Test3',' ','Test4','Test4','Test1',"Test3"], 'c2': [' ','Test1',' ','NULL',' ','NULL','NULL','NULL','NULL'], 'c3': [0,0,0,0,0,1,5,0,0], 'c4': ['NULL', 'Test2', 'Test1','Test1', 'Test2', 'Test2','Test1','Test1','Test2'] } df = pd.DataFrame(data) df The dataframe looks like this: c1 c2 c3 c4 0 Test1 0 NULL 1 Test2 Test1 0 Test2 2 NULL 0 Test1 3 Test3 NULL 0 Test1 4 0 Test2 5 Test4 NULL 1 Test2 6 Test4 NULL 5 Test1 7 Test1 NULL 0 Test1 8 Test3 NULL 0 Test2 I want to drop all columns, that have more than 60 % of "empty" values. "Empty" means in my case that the values are for example: ' ', 'NULL' or 0. There are strings (c1, c2, c4) as well as integers (c3). The result should be a dataframe with columns c1 and c4 only. c1 c4 0 Test1 NULL 1 Test2 Test2 2 NULL Test1 3 Test3 Test1 4 Test2 5 Test4 Test2 6 Test4 Test1 7 Test1 Test1 8 Test3 Test2 I have no idea how to handle that problem. Only thing that comes to my mind is something like df.loc[:, (df != 0).any(axis=0)] to delete all columns where all values are 0, 'NULL' and so on.
downvote count: 0
accepted answer: http://stackoverflow.com/a/49791402
linked to: http://stackoverflow.com/q/43311555
tagged with: python
score: 19
has answer: http://stackoverflow.com/a/49791402
has answer: http://stackoverflow.com/a/49792609
has title: Drop Columns with more than 60 Percent of "empty" Values in Pandas
type: AnsweredQuestion
upvote count: 19
has comment: http://stackoverflow.com/comment/91693006
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/71847073

http://stackoverflow.com/comment/86600453
type: QuestionComment
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ Sorry I forgot to edit it. Now the string is fine.
comment on: http://stackoverflow.com/q/49793008
type: Comment

http://stackoverflow.com/a/49906388
answers question: http://stackoverflow.com/q/49906269
has body: You could use --(.*?)=(.*). Uses ungreedy matching to find everything between -- and the first =, and then greedily matches everything after. x = """ --key_a=value1 --key_b=value2 --key_c=value3 --key_d=value4 --key_e=valuewith======init======== """ import re print(re.findall(r'--(.*?)=(.*)', x)) Output: [('key_a', 'value1'), ('key_b', 'value2'), ('key_c', 'value3'), ('key_d', 'value4'), ('key_e', 'valuewith======init========')]
type: Answer
has comment: http://stackoverflow.com/comment/86829361
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/67571543
answers question: http://stackoverflow.com/q/49896513
type: Answer
score: 1
downvote count: 0
upvote count: 1
has body: You can now tag the VPC on creation response = client.create_vpc( CidrBlock='string', AmazonProvidedIpv6CidrBlock=True|False, Ipv6Pool='string', Ipv6CidrBlock='string', DryRun=True|False, InstanceTenancy='default'|'dedicated'|'host', Ipv6CidrBlockNetworkBorderGroup='string', TagSpecifications=[ { 'ResourceType': 'vpc', 'Tags': [ { 'Key': 'string', 'Value': 'string' }, ] }, ] )

dijkstra
tags question: http://stackoverflow.com/q/49844433
tag name: dijkstra
type: Tag
tags question: http://stackoverflow.com/q/49848989

http://stackoverflow.com/q/49784269
has comment: http://stackoverflow.com/comment/86583981
tagged with: python
has body: Considering the following minimal not working example: import numba as nb import numpy as np @nb.jit(nopython=True) def resize_np_array(np_array, new_size, fill_value): if new_size &lt;= np_array.shape[0]: return np_array else: new_shape = np_array.shape new_shape[0] = new_size new_np_array = fill_value*np.ones(new_shape, dtype=np_array.dtype) for i in range(np_array.shape[0]): new_np_array[i] = np_array[i] return new_np_array @nb.jit(nopython=True) def test_function(): x = np.zeros(10, dtype=np.int64) x = resize_np_array(x, 20, 0) return x x = test_function() The above code will fail with error: File "A:\anaconda\lib\site-packages\numba\typeinfer.py", line 595, in __call__ (targetty, self.index, valty), loc=self.loc) TypingError: Cannot resolve setitem: (int64 x 1)[0] = int64 due to the line: x = resize_np_array(x, 20, 0) in test_function. How should I go about deleting whatever is stored in x so that I can reassign a new array to it?
has answer: http://stackoverflow.com/a/49784514
accepted answer: http://stackoverflow.com/a/49784514
type: Question
tagged with: numpy
has title: numba: How to delete an existing array and assign a new array to the old array's name?
has comment: http://stackoverflow.com/comment/86585997
tagged with: numba
answer count: 1
has comment: http://stackoverflow.com/comment/86584001
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49901843
has comment: http://stackoverflow.com/comment/86823460
type: Answer
has body: You've set a single attribute of an object (a function object in this case). If you wanted to document it, then a more traditional way is to set the docstring: def Greeting(): """ This function will say hello """ return "Hello there!" then it can be viewed via help(Greeting): &gt;&gt;&gt; def Greeting(): ... """ This function will say hello """ ... return "Hello there!" ... &gt;&gt;&gt; Greeting.__doc__ ' This function will say hello ' &gt;&gt;&gt; help(Greeting) It prints: Help on function Greeting in module __main__: Greeting() This function will say hello (END)
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49901767

http://stackoverflow.com/q/49800045
tagged with: python
has comment: http://stackoverflow.com/comment/86615600
has answer: http://stackoverflow.com/a/49800191
has answer: http://stackoverflow.com/a/57086549
answer count: 4
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86615647
upvote count: 5
has comment: http://stackoverflow.com/comment/86615262
has comment: http://stackoverflow.com/comment/86615112
has answer: http://stackoverflow.com/a/49800501
has comment: http://stackoverflow.com/comment/86615017
downvote count: 1
has comment: http://stackoverflow.com/comment/86615467
has comment: http://stackoverflow.com/comment/86615333
has comment: http://stackoverflow.com/comment/86615562
tagged with: machine-learning
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/86614886
score: 4
has body: I use the following way to scale an n-dimensional array between 0 and 1: x_scaled = (x-np.amin(x))/(np.amax(x)-np.amin(x)) But it's very slow for large datasets. I have thousands of relatively large arrays which I need to process. Is there a faster method to this in python? Edit: My arrays are in shape (24,24,24,9). For MinMax scaler in scikit, the input array has to have a certain shape which mine doesn't so I can't use it. In the documentation it says: Parameters: X : array-like, shape [n_samples, n_features]
has title: Python: Fast way of MinMax scaling an array
favorite count: 0
has comment: http://stackoverflow.com/comment/86615382
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/52808695
has comment: http://stackoverflow.com/comment/86614870
tagged with: data-analysis
has comment: http://stackoverflow.com/comment/86614875
has answer: http://stackoverflow.com/a/52808695
accepted answer: http://stackoverflow.com/a/49800501
has comment: http://stackoverflow.com/comment/86614990
linked to: http://stackoverflow.com/q/21764475

http://stackoverflow.com/comment/86620629
comment on: http://stackoverflow.com/q/49802553
has text: If the average is precomputed and you simply want to merge two dataframes, you can use `left` [merge](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html). Make sure the dataframe with `Timestamps` is the `left` dataframe.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86840855
type: Comment
comment on: http://stackoverflow.com/a/49909944
type: AnswerComment
has text: Hi, thanks a lot for the answer and I get it! So the problem is not about the JS rendering right?
score: 0

http://stackoverflow.com/q/49901824
has answer: http://stackoverflow.com/a/63673450
downvote count: 0
has body: Is there a function similar to pools.starmap that can be used with list of dictionaries? Instead of : pools.starmap(func, iterable_of_tuple) You would have: pools.starmapdict(func, iterable_of_dictionaries) so that the function starmapdict would be responsible for unpacking the dictionary of argument of the function.
accepted answer: http://stackoverflow.com/a/69041301
favorite count: 0
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/112595898
has answer: http://stackoverflow.com/a/69038307
answer count: 3
score: 10
upvote count: 10
has comment: http://stackoverflow.com/comment/108066237
has title: Python pool.starmap with list of dictionaries?
tagged with: python
has answer: http://stackoverflow.com/a/69041301
possible better answer: http://stackoverflow.com/a/69038307
type: AnsweredQuestion

http://stackoverflow.com/q/49786713
tagged with: python
accepted answer: http://stackoverflow.com/a/49793053
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49793053
upvote count: 2
has body: I have Python code that generates a deep convolutional neural network using Keras. I'm trying to save the model, but the result is gigantic (100s of MBs). I'd like to pare that down a bit to make something more manageable. The problem is that model.save() stores (quoting the Keras FAQ): the architecture of the model, allowing to re-create the model the weights of the model the training configuration (loss, optimizer) the state of the optimizer, allowing to resume training exactly where you left off. If I'm not doing any more training, I think I just need the first two. I can use model.to_json() to make a JSON string of the architecture and save that off, and model.save_weights() to make a separate file containing the weights. That's about a third the size of the full model.save() result. But I'm wondering if there's some way to store these in a single self-contained file? (Short of outputting two files, zipping them together, and deleting the originals.) Alternatively, maybe there's a way to delete the training configuration and optimizer state when training is complete, so that model.save() doesn't give me something nearly so big? Thanks.
downvote count: 0
answer count: 1
has title: Saving just model & weights in Keras (in single file)
tagged with: keras
favorite count: 0
type: Question
tagged with: saving-data

http://stackoverflow.com/comment/86747242
score: 1
has text: You are missing a `+` after one of the `str(x)` in both of your cases.
type: Comment
comment on: http://stackoverflow.com/q/49865933
type: QuestionComment

http://stackoverflow.com/a/49880701
answers question: http://stackoverflow.com/q/49880373
score: 2
type: Answer
upvote count: 2
downvote count: 0
has body: I would use PyGame on Mac, because of its portability. If you really want to use mp3 try this code: import pygame pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag pygame.init() pygame.mixer.init() pygame.mixer.music.load('your_mp3_file.mp3') pygame.mixer.music.play(-1) But, if I were you, I would prefer this simpler approach on a Mac: from os import system system('say Hello world!')

http://stackoverflow.com/q/49792966
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49793132
accepted answer: http://stackoverflow.com/a/49793132
has title: Get Index of the search array with .all() and any()
favorite count: 0
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/86600396
upvote count: 3
has comment: http://stackoverflow.com/comment/86600243
has body: I have list of arrays and i am using .all() and .any() to check if the array im searching is in the list of arrays. t = np.array([[1,2,3], [4,5,6] , [7,8,9], [10, 11, 12]]) t2 = np.array([1,2,3]) print((t == t2).all(1)) outpu:&gt; [ True False False False] here i can check if t2 is in t print((t == t2).all(1).any()) outpu:&gt; True My question is can i get on what index in t that t2 exist with .all and .any method?
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86600424
tagged with: arrays
answer count: 1

http://stackoverflow.com/comment/86847861
type: QuestionComment
has text: @Jan: I know about it, but AFAIK the standard library only contains the old `re` module and OP has an `import re` line...
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49915974

http://stackoverflow.com/a/49878978
answers question: http://stackoverflow.com/q/49878918
upvote count: 5
has body: Simply sort the tuples first: In [21]: l = [tuple(sorted(i)) for i in l] In [22]: l Out[22]: [('a', 'b'), ('a', 'b'), ('c', 'd'), ('d', 'e'), ('d', 'e')] In [23]: Counter(l) Out[23]: Counter({('a', 'b'): 2, ('c', 'd'): 1, ('d', 'e'): 2})
type: Answer
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/86777098

http://stackoverflow.com/comment/86613710
type: Comment
has text: I cannot replicate your issue - I see the curve as per your R example. And you can create `k` easier with `k = np.arange(1,100001,1) ** 2`
score: 1
comment on: http://stackoverflow.com/q/49799470
type: QuestionComment

http://stackoverflow.com/q/49803018
score: 3
tagged with: contactless-smartcard
has body: I build up some kind of RFID-Reader with an Raspberry Pi 3 and an RC522 using this code as a start: https://github.com/mxgxw/MFRC522-python. Unfortunately I'm not able to get a APDU-Response from my card after sending any APDU-Command. My current workflow is more or less the ISO 14443-4: Search for cards receive ATQA Perform anticollision and select card Determine whether card is supporting ISO-14443-4 protocol or not Send RATS and receive ATS Perform an PPS-Request [Until here everything is fine and I get responses.] Send an APDU-Command [btw. command works fine with my smartphone and an APP] #Scan for cards (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) #If a card is found if status == MIFAREReader.MI_OK: print "Card detected" TagType = (TagType &gt;&gt; 6) | 0 #(Länge der UID errechnen print "Tagtype: %s" % (TagType) # START ANTI-COLLISION AS OF ISO 14443 if TagType == 0: print "UID length is single -- starting ANTI-COLLISION CL1" (status,uid) = MIFAREReader.MFRC522_Anticoll() if status == MIFAREReader.MI_OK: print "Card read UID: %s,%s,%s,%s" % (uid[0], uid[1], uid[2], uid[3]) elif TagType == 1: # Ignore this part as there is no functionality by now print "CARD IS NOT SUPPORTED YET" (status,uid) = MIFAREReader.MFRC522_Anticoll() elif TagType == 2: print "CARD IS NOT SUPPORTED YET" (status,uid) = MIFAREReader.MFRC522_Anticoll() elif TagType == 3: print "CARD IS NOT SUPPORTED YET" (status,uid) = MIFAREReader.MFRC522_Anticoll() else: print "An unexpected error occured: UID length is not covered by ISO-14443." (size, APDU) = MIFAREReader.MFRC522_SelectTag(uid) print "Card selected" print "ISO 14443-4 Compatibility: %s" % (APDU) if APDU == 1: # Card supports ISO 14443-4 protocol [Problem could be here] #SEND RATS print "Sening RATS" RATS_Sequenz = [0xE0, 0x50] CRC_RATS = [] CRC_RATS = MIFAREReader.CalulateCRC(RATS_Sequenz) RATS_Sequenz.append(CRC_RATS[0]) RATS_Sequenz.append(CRC_RATS[1]) (stat, res, leng) = MIFAREReader.MFRC522_ToCard(MIFAR…
answer count: 0
has comment: http://stackoverflow.com/comment/86620698
upvote count: 3
tagged with: apdu
downvote count: 0
has title: Send APDU Commands in python (RC522, RaspberryPi)
favorite count: 0
type: Question
tagged with: raspberry-pi
type: UnansweredQuestion
tagged with: python
tagged with: rfid
has comment: http://stackoverflow.com/comment/107688070

http://stackoverflow.com/comment/86834150
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49908548
type: Comment
has text: Not exactly, but almost :) -- `np.array(3,2,3)` will cause a syntax error, `np.zeros((3,2,3))` will use `np.float64` as datatype. To make it equivalent to the C++ code, you want `np.float32`. `cv::Vec3f` matches `CV_32FC3`. It could be used to represent pixel colors in a 3 channel image (e.g. RGB).

http://stackoverflow.com/q/49776333
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86567747
downvote count: 0
tagged with: animation
upvote count: 1
has title: How to add a timer in an animation.FuncAnimation (), using pandas/Geopandas?
favorite count: 0
type: Question
tagged with: pandas
score: 1
tagged with: geopandas
tagged with: python
has body: I am creating an animation by using GeoPandas and everything is going well but I'd like to include a timer, in order to know the time corresponding to my visualization. I think the way is by means of set_text, but I think everything is lost in the update done by Geopandas to plot (ax=ax). So, the instruction time_text is the one that is not working on my code. Please any help/suggestion/idea? Thanks in advance!! Here the important part of my code: import numpy as np from matplotlib import pyplot as plt from matplotlib import animation import geopandas as gpd import pandas as pd from shapely.geometry import Point fig = plt.figure() ax = plt.axes(xlim=(2.5, 7), ylim=(48, 52)) time_text = ax.text(2.8, 50.,"",transform = ax.transAxes, ha="right") ax.legend() t=0 bel = gpd.read_file('....') def init(): global inicio inicio = bel.plot( ax=ax, color='black', markersize=5) time_text.set_text("") return inicio, time_text data = pd.read_csv('.....') legend = plt.legend(loc='lower left',prop={'size': 7}) def animate(i): global inu, iterar, t t += 1 ax.clear() inu = bel.plot( ax=ax, color='lightgray', linewidth=1., edgecolor='black') cond = geo_data[ geo_data['newdate'].dt.minute == i] iterar = cond.plot(ax=ax,marker='s',color='yellow', markersize=7.,alpha=0.3,label='Max &gt;= 60 Tonne'); legend = plt.legend(loc='lower left',prop={'size': 7}) time_text.set_text("time = "+str(t)) return iterar,inu,time_text anim = animation.FuncAnimation(fig, animate, init_func=init,frames=60, interval=500, blit=False) plt.show()
tagged with: timer

http://stackoverflow.com/q/49845893
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86711489
type: Question
has comment: http://stackoverflow.com/comment/86712343
type: UnansweredQuestion
has body: Other questions here have suggested that my PATH variable is set wrong, but I checked my ~/.bashrc and found this: export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games: /usr/local/games" export PATH="/home/name/anaconda3/bin:$PATH" When I run "python" from terminal, I get Python 2.7.14 |Anaconda custom (64-bit)| (default, Mar 27 2018, 17:29:31) [GCC 7.2.0] on linux2 Which looks like Anaconda's installed properly. However, I can't run any commands starting with "conda" - I just get a ImportError: No module named conda.cli
tagged with: python
has comment: http://stackoverflow.com/comment/86712041
has title: No module named conda.cli
tagged with: conda
has comment: http://stackoverflow.com/comment/86706870
upvote count: 3
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49845975

http://stackoverflow.com/a/49885761
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/86787691
has comment: http://stackoverflow.com/comment/86788774
accepted answer of: http://stackoverflow.com/q/49885663
upvote count: 0
has comment: http://stackoverflow.com/comment/86787611
has body: awTest.json returns you with a list of dicts: [{'SampleTime': '4/17/2018 6:39:00 PM', 'Latitude': '32.18007400', 'Longitude': '-94.35314700', 'Elevation': '72.76', 'Speed': '16.43', 'DeviceId': {'Value': 74365}, 'Id': {'Value': 126709703}}, {'SampleTime': '4/17/2018 6:24:00 PM', 'Latitude': '32.18735200', 'Longitude': '-94.36022700', 'Elevation': '64.67', 'Speed': '5.59', 'DeviceId': {'Value': 74365}, 'Id': {'Value': 126705738}},...] You can iterate it the following way: for item in deviceDetails: logging.info(item) Or if you need only SampleTime from each record: for item in deviceDetails: logging.info(item['SampleTime'])
type: Answer
score: -1
answers question: http://stackoverflow.com/q/49885663
has comment: http://stackoverflow.com/comment/86788570
has comment: http://stackoverflow.com/comment/86788431

http://stackoverflow.com/comment/132777607
score: 0
has text: @YaelBen-Haim: The `@deprecated_alias` decorator doesn't actually need you to make `id_object` optional, or any arguments after it.
type: Comment
comment on: http://stackoverflow.com/a/49802489
type: AnswerComment

http://stackoverflow.com/a/49929914
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49903137
has body: Thanks to the answer of piRSquared with his map function, I had the idea to use merge such as: df_s['value'] = df_s['sentence'].apply(lambda x: sum(pd.merge(pd.DataFrame({'word':x.split(' ')}),df_w)['value'])) Thanks to the answer of Wen with his stack function, I use his idea but with merge such as: df_stack = pd.DataFrame({'word': df_s['sentence'].str.split(' ',expand=True).stack()}) df_s['value'] = df_stack.reset_index().merge(df_w).set_index(['level_0','level_1'])['value'].sum(level=0) And both methods give me the right answer. Finally, to test which solution is faster, I define functions such as: def sol_dict (df_s, df_w): # answer with a dict dict_w = pd.Series(df_w['value'].values,index=df_w['word']).to_dict() df_s['value'] = df_s['sentence'].apply(lambda x: sum([dict_w[word] for word in x.split(' ') if word in dict_w.keys()])) return df_s def sol_wen(df_s, df_w): # answer of Wen s=df_s.sentence.str.split(' ',expand=True).stack() df_s['value']=s[s.isin(df_w.word)].replace(dict(zip(df_w.word,df_w.value))).sum(level=0) return df_s def sol_pi (df_s, df_w): # answer of piRSquared dw = lambda x: dict(zip(df_w.word, df_w.value)).get(x, 0) df_s.assign(value=[sum(map(dw, s.split())) for s in df_s.sentence]) # or df_s['value'] = [sum(map(dw, s.split())) for s in df_s.sentence] return df_s def sol_merge(df_s, df_w): # answer with merge df_s['value'] = df_s['sentence'].apply(lambda x: sum(pd.merge(pd.DataFrame({'word':x.split(' ')}),df_w)['value'])) return df_s def sol_stack(df_s, df_w): # answer with stack and merge df_stack = pd.DataFrame({'word': df_s['sentence'].str.split(' ',expand=True).stack()}) df_s['value'] = df_stack.reset_index().merge(df_w).set_index(['level_0','level_1'])['value'].sum(level=0) return df_s My "large" test DFs where composed of around 3200 words in df_w and around 42700 words in df_s (once split all sentences). I run timeit with several size of df_w (from 320 to 3200 words) with the full size of df_s and then with several size of df_s (from 3…
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49903137
score: 1

http://stackoverflow.com/q/49899423
type: Question
has title: How to pass special character in URL in windows authentication?
score: 2
has comment: http://stackoverflow.com/comment/86814267
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86814653
possible better answer: http://stackoverflow.com/a/50044989
has comment: http://stackoverflow.com/comment/87032408
linked to: http://stackoverflow.com/q/45328654
answer count: 3
upvote count: 5
has comment: http://stackoverflow.com/comment/87056203
has answer: http://stackoverflow.com/a/50044989
has comment: http://stackoverflow.com/comment/87053984
downvote count: 3
has comment: http://stackoverflow.com/comment/86814879
accepted answer: http://stackoverflow.com/a/50108880
tagged with: python
has answer: http://stackoverflow.com/a/50108386
has body: To handle windows authentication, one way to handle such scenario is by passing credentials in URL itself as shown below driver.get('http://username:password@abc.com') But in my case since password contains special character, like 'password@123', so now code contains double special character '@' as shown below driver.get('http://username:password@123@abc.com') I tried replacing '@' with '%40' using url encoder/decoder, but it's not working. I am working with python selenium, any idea how to handle such scenario?
has answer: http://stackoverflow.com/a/50108880
has comment: http://stackoverflow.com/comment/86816139
has comment: http://stackoverflow.com/comment/86814523
has comment: http://stackoverflow.com/comment/87050839
has comment: http://stackoverflow.com/comment/86816260
has comment: http://stackoverflow.com/comment/87058361
has comment: http://stackoverflow.com/comment/87050097
tagged with: selenium
has comment: http://stackoverflow.com/comment/87054055
favorite count: 0

http://stackoverflow.com/comment/86802319
score: 0
type: AnswerComment
has text: I tried to use colin's answer but got an error `IOError: [Errno 2] No such file or directory: 'image.png'` even if the file exists.
type: Comment
comment on: http://stackoverflow.com/a/49887718

http://stackoverflow.com/a/49857835
answers question: http://stackoverflow.com/q/49857432
type: Answer
has comment: http://stackoverflow.com/comment/86730685
has comment: http://stackoverflow.com/comment/86732640
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49857432
has body: You can do it this way: pd.crosstab(df.Classified, df.FreqWord) Output FreqWord business crops drought water Classified Negative 1 2 1 0 Positive 0 0 4 1 Or get_dummies: df_out = pd.get_dummies(df'Classified','FreqWord', columns=['FreqWord'])\ .set_index('Classified').sum(level=0) df_out.columns = df_out.columns.str.split('_').str[1] Output: business crops drought water Classified Positive 0 0 4 1 Negative 1 2 1 0 And, if you wish you can reset_index: df_out.reset_index() Classified business crops drought water 0 Positive 0 0 4 1 1 Negative 1 2 1 0
has comment: http://stackoverflow.com/comment/86733973

http://stackoverflow.com/a/49772879
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/49772781
has comment: http://stackoverflow.com/comment/86561932
score: 4
has comment: http://stackoverflow.com/comment/97279464
has body: You can add default permission classes in your settings.py file: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) }

http://stackoverflow.com/a/49777467
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86572694
has comment: http://stackoverflow.com/comment/86596428
has comment: http://stackoverflow.com/comment/86617586
answers question: http://stackoverflow.com/q/49777018
has comment: http://stackoverflow.com/comment/86595460
type: Answer
has comment: http://stackoverflow.com/comment/86596929
has body: 1. why does also greet has to have (self) ? The function greet() is a function of your MyFirstGUI class, you can see that when you bind this function to the greet_button the function is put after self. It means that the function has a link to self (which is MyFirstGUI). This link is made by putting self in the function definition. 2. how do I call (is call the right word here?) greet from another py file? (I'm not sure I understand what you ask) Yes call is right ! If you want to call this function from another file, you would have to import the MyFirstGUI in your main file and create an instance of this object. mainFile.py: from tkinter import * from guiFile import MyFirstGUI root = Tk() my_gui = MyFirstGUI(root) my_guy.greet() root.mainloop() guiFile.py: from tkinter import * class MyFirstGUI(object): def __init__(self, master): self.master = master master.title("A simple GUI") self.label = Label(master, text="This is our first GUI!").pack() self.greet_button = Button(master, text="Greet", command=self.greet).pack() self.close_button = Button(master, text="Close", command=self.quit).pack() def greet(self): print('Hello') def quit(self): self.master.destroy()
score: 2

http://stackoverflow.com/a/49825586
answers question: http://stackoverflow.com/q/49825551
has body: It looks like the coordinates are always in the last line. If this is the case, we can do the following: coords_str = text.splitlines()[-1] to get the last line. Due to a lucky coincidence, it seems that the coordinates are formatted exactly like python tuples. because of that, we can use the ast module to transform it into a python tuple: import ast ast.literal_eval(coords_str)
type: Answer
score: 0

http://stackoverflow.com/q/49880545
type: Question
has body: How to parse a big XML file and process its elements as ObjectifiedElement (using objectify parser). I didn't find any better solution than : from lxml import etree, objectify for event, elt in etree.iterparse('onebigfile.xml', tag='MyTag'): oelt = objectify.fromstring(etree.tostring(elt)) my_process(oelt) How can I avoid this intermediate string representation ?
tagged with: lxml
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86788804
tagged with: python
tagged with: lxml.objectify
score: 2
has title: lxml iterparse with objectify
upvote count: 2
has comment: http://stackoverflow.com/comment/86778531
downvote count: 0
has answer: http://stackoverflow.com/a/49883766
answer count: 1
has comment: http://stackoverflow.com/comment/86781487
has comment: http://stackoverflow.com/comment/86779648
has comment: http://stackoverflow.com/comment/86779368
favorite count: 0

http://stackoverflow.com/a/49863091
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49862782
has comment: http://stackoverflow.com/comment/94592628
type: AcceptedAnswer
has body: EDIT: The old answer is obsolete. As of Bokeh 1.4, you can terminate SSL directly on the Bokeh server (no Nginx required): https://docs.bokeh.org/en/latest/docs/user_guide/server.html#ssl-termination From the docs... https://docs.bokeh.org/en/latest/docs/user_guide/server.html Include in your nginx.conf : # redirect HTTP traffic to HTTPS (optional) server { listen 80; server_name foo.com; return 301 https://$server_name$request_uri; } and run the serve command with --use-x-headers flag bokeh serve myapp.py --port 8000 --use-xheaders This tutorial might be helpful: https://blog.docker.com/2015/04/tips-for-deploying-nginx-official-image-with-docker/
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49862782
downvote count: 1

http://stackoverflow.com/q/49842536
has title: Regex only finds results once
has comment: http://stackoverflow.com/comment/86699728
has comment: http://stackoverflow.com/comment/86699637
tagged with: python
has comment: http://stackoverflow.com/comment/86699753
tagged with: regex
has comment: http://stackoverflow.com/comment/86699843
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49842655
possible better answer: http://stackoverflow.com/a/49842709
upvote count: 1
has answer: http://stackoverflow.com/a/49842655
downvote count: 1
has answer: http://stackoverflow.com/a/49842709
favorite count: 0
type: Question
has body: I'm trying to find any text between a '>' character and a new line, so I came up with this regex: result = re.search("&gt;(.*)\n", text).group(1) It works perfectly with only one result, such as: &gt;test1 (something else here) Where the result, as intended, is test1 But whenever there's more than one result, it only shows the first one, like in: &gt;test1 (something else here) &gt;test2 (something else here) Which should give something like test1\ntest2 But instead just shows test1 What am I missing? Thank you very much in advance.

http://stackoverflow.com/q/49772156
tagged with: python-3.x
has body: When parsing the journelctl file, keywords to look for are : error, boot, warning, traceback Once I encounter the keyword, I need to increment the counter for each of the keyword and print the matching line as well. So, I have tried as below; reading it from a file and using Collections module - Counter object to keep track of the count along with re.findall : import re from collections import Counter keywords = [" error ", " boot ", " warning ", " traceback "] def journal_parser(): for keyword in keywords: print(keyword) # just for debugging word = re.findall(keyword, open("/tmp/journal_slice.log").read().lower()) count = dict(Counter(word)) print(count) Above solution resolves my problem however I am looking forward for much efficient way if any. Please advise.
answer count: 2
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49772363
downvote count: 0
upvote count: 1
has title: Efficient way to parse large journalctl file to match keywords using Python
favorite count: 0
has comment: http://stackoverflow.com/comment/86559522
type: Question
tagged with: linux
tagged with: python
has answer: http://stackoverflow.com/a/49789209

http://stackoverflow.com/q/49823750
has body: def hand(): print("Wrong port format") er() def er(): try: host=input("Host: ") serverPort=(input("Port: ")) try: Port=int(serverPort) except Exception: hand() return (host,int(serverPort)) except Exception: return("Wrong") serverPorti=er() print((serverPorti)) When I run it returns Wrong, I want the user to input the host and the port but if the user inputs a text(letters) in port number it should call back the function er(), it does call back but the return even after I input the right port number returns wrong.
has comment: http://stackoverflow.com/comment/86664006
tagged with: function
has comment: http://stackoverflow.com/comment/86663684
has answer: http://stackoverflow.com/a/49823930
accepted answer: http://stackoverflow.com/a/49823930
type: AnsweredQuestion
score: 0
answer count: 1
has title: Function returning the first initialization of the variables, not the overwritten ones
tagged with: python
type: Question

http://stackoverflow.com/comment/124970283
type: AnswerComment
comment on: http://stackoverflow.com/a/70516709
score: 0
type: Comment
has text: Yes but somehow using both commands at same time worked for me.

http://stackoverflow.com/comment/86823718
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49898476
has text: I don't know what you mean by that. Bottom line, programming is deterministic. There's a reason your code is behaving the way it is. You simply need to step through the code a line at a time to see why it is or isn't calling a function when you think it should or shouldn't. In the code you've posted, you very clearly are running `main` repeatedly, as fast as possible.

http://stackoverflow.com/comment/86604944
comment on: http://stackoverflow.com/q/49795287
type: Comment
type: QuestionComment
score: 0
has text: If the data is messy, consider cooking up some fake data. I would also suggest you post your expected output as well. Good luck.

http://stackoverflow.com/comment/86835691
comment on: http://stackoverflow.com/a/49840320
has text: @eyllanesc Hey thanks for all the help and sorry for bothering you again It works perfectly on mac but when I shared my script with a friend that used windows it no longer saves do you think you could look into this?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/116286719
comment on: http://stackoverflow.com/a/49823164
has text: @pault how would you adopt this if some of the rows are blank for the column with json. Your solution works for me with all the rows have valid json but if I have any rows with a blank column I get an error : AttributeError: 'float' object has no attribute 'items'
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/49866674
has comment: http://stackoverflow.com/comment/86767165
answers question: http://stackoverflow.com/q/49865843
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86768460
accepted answer of: http://stackoverflow.com/q/49865843
has body: The first argument of brenth must be callable (a Python function), representing the objective function. Your equat1 is a SymPy expression (of class exp, since its outermost layer is exp function), and this is not callable. One can use lambdify to make a callable out of a SymPy expression: optimize.brenth(lambdify(y, equat1), 0.11, 0.14) This executes, but with (appropriate) warnings about complex values. brenth expects a real valued function. Generally, one cannot expect both real and imaginary part to vanish at the same point, anyway. Lastly, the function exp never turns to zero, so what do you really expect to obtain? Consider if you meant to equate to zero the real part, or imaginary part, or something else. You don't really need SymPy at all; defining a callable directly allows equat1 = lambda y: (a formula returning the thing to be equated to 0) This way you'd have more control over the handling of complex values; potentially using cmath, or declaring complex dtype in NumPy. As is, there are issues with sqrt of a negative number because NumPy will not automatically cast real to complex data type. Here is a working snippet based on your equation: I used cmath.sqrt so that roots of negative numbers are handled correctly. import cmath from scipy import optimize equat1 = lambda y: cmath.exp(-1.0j*(36.96*y**0.5+1.367*cmath.sqrt(-1.25*y+2.33)+30.996*cmath.sqrt(1.25*y-0.675))).real print(optimize.fsolve(equat1, 0.11)) # array([ 0.1073826]) Aside: using from module import * for multiple modules is not a good idea, as imports will overwrite each other, resulting in a mess.
has comment: http://stackoverflow.com/comment/86773868
type: Answer
has comment: http://stackoverflow.com/comment/86770702
score: 2
upvote count: 2

http://stackoverflow.com/q/49803139
score: 1
upvote count: 1
tagged with: image
favorite count: 0
type: Question
has title: PIL ImageChop giving wrong results:
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86621194
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86621089
has comment: http://stackoverflow.com/comment/86620952
has body: img1_path = r'/Users/siddharth/image1.png' img2_path = r'/Users/siddharth/image2.png' from PIL import Image, ImageDraw, ImageChops im1 = Image.open(img1_path) # original im2 = Image.open(img2_path) # scapred height,width = im1.size for h in range(0,height,height/25): for w in range(0,width,width/20): c_img1 = im1.crop((h,w,height/25,height/25)) c_img2 = im2.crop((h,w,height/25,height/25)) if ImageChops.difference(c_img1, c_img2).getbbox() is None: draw = ImageDraw.Draw(im2) draw.rectangle((h,w,height/25,height/25),outline='red') im2.save('Diff.png') print 'Done' The idea here is two compare two images and mark rectangles in areas where they differ. The problem is despite multiple attempts my results (Diff.img) has rectangles all over as opposed to having just around differences? What is it that I am missing?
answer count: 0
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/86621152

http://stackoverflow.com/a/49841245
upvote count: 4
answers question: http://stackoverflow.com/q/49840767
downvote count: 0
has body: Please read this not as an answer but more like a longer comment ;) So first read into the MVC concept (for example: https://djangobook.com/model-view-controller-design-pattern/) to understand how web interfaces interact with the rest of the code. The classical django way would be to create a form (in forms.py) based on your model. you would write some html to display the form on a website validate the form input in views.py send back an the results and display them (again html) when you would like to do that with AJAX its a little extra work but the result will be worth it. (for example: How to POST a django form with AJAX &amp; jQuery) you will call a specific url which you first initialise in your urls.py file (path('checkForm', views.checkForm, name='checkForm'), in django 2.0) the url points to a function defined in views.py with the name checkForm (same as the url path in this example but you can call it whatever you want). Inside this function you can write your python code or call the functions from there to execute your db quires, validations etc. Send back a response with the results of your code. success: function(data, status) { $('#whatever').html(data); alert("whatever"); } "data" is here the response from the server. I hope I gave you a hint in the right direction. Please ask if you get stuck somewhere. p.s. I have no idea how to send the fingerprint data via http, check if there is some library. x=data.read(12).decode("utf-8") tag_id_in = x this is bad code, please get rid of x. first x is a bad variable name and second its completely redundant. you also want to convert your print statements into logs or whatever but printing won't get you far.
score: 4
has comment: http://stackoverflow.com/comment/86697764
type: Answer

http://stackoverflow.com/q/49797399
has title: Django annotate returned more than one
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
tagged with: django-orm
downvote count: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49799282
has answer: http://stackoverflow.com/a/49797912
score: 2
answer count: 2
has body: user = get_object_or_404( (User.objects .annotate(company_name=F('usercompany__company__company_name')) .annotate(project=F('team__vacancy__name'))), email=request.GET.get('user_email') ) I got errors: proj.models.MultipleObjectsReturned: get() returned more than one User -- it returned 2! How can I change .annotate(project=F('team__vacancy__name'))) to get all.

http://stackoverflow.com/q/49782063
downvote count: 1
favorite count: 0
has title: Loop over multiple elements using Selenium
type: Question
tagged with: python
score: -1
has body: I am trying to scrape the following website: finsight.com/product/us/abs/ee. In particular, for each row, I am trying to extract the type (AUTO or CBMS), the company name, and download the links. Here is an extract of the source code for each row 1. However, when I run the loop, I only get the names and links of the first row (in this case is AUTo CarMax Auto Owner Trust 2018-2). So far, I have the following code: import selenium import time import requests from selenium import webdriver url = "https://finsight.com/product/us/abs/ee" driver = webdriver.Chrome() driver.get(url) time.sleep(1) company_row = driver.find_elements_by_xpath("//div[@class='ee-item portlet box ng-scope']") for row in company_row: RD_element = row.find_element_by_xpath("//a[@class='related-document ng-scope']") company_name = row.find_element_by_xpath("//span[contains(@class,'filing-left filing-issuer ng-binding')]") company_type = row.find_element_by_xpath("//span[contains(@class,'filing-left filing-sector ng-binding')]") RD_link = RD_element.get_attribute('href') print (company_name.text) print (company_type.text) print (RD_link) And the output of my code is the following: DevTools listening on ws://127.0.0.1:12060/devtools/browser/c5d13168-0976-41c7-937c-ff2bd4cd99fe CarMax Auto Owner Trust 2018-2 AUTO https://finsight.com/api/download-csv?file_id=15395 CarMax Auto Owner Trust 2018-2 AUTO https://finsight.com/api/download-csv?file_id=15395 CarMax Auto Owner Trust 2018-2 AUTO https://finsight.com/api/download-csv?file_id=15395 CarMax Auto Owner Trust 2018-2 AUTO https://finsight.com/api/download-csv?file_id=15395 CarMax Auto Owner Trust 2018-2
accepted answer: http://stackoverflow.com/a/49783437
type: AnsweredQuestion
upvote count: 0
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/49783437

http://stackoverflow.com/q/49836933
has answer: http://stackoverflow.com/a/49837722
type: Question
has body: I would like to encode integers stored in a pandas dataframe column into respective 16-bit binary numbers which correspond to bit positions in those integers. I would also need to pad leading zeros for numbers with corresponding binary less than 16 bits. For example, given one column containing integers ranging from 0 to 33000, for an integer value of 20 (10100 in binary) I would like to produce 16 columns with values 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0 and so on across the entire column.
tagged with: numpy
tagged with: binary
answer count: 2
tagged with: pandas
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49837094
has title: Encode integer pandas dataframe column to padded 16 bit binary
tagged with: python

http://stackoverflow.com/a/49839776
type: Answer
accepted answer of: http://stackoverflow.com/q/49839680
has body: In Python2 &gt;&gt;&gt; 3/2 # returns 1 Whereas in Python3 &gt;&gt;&gt; 3/2 # returns 1.5 As you can see one makes integer division and other makes float division. If I were to write &gt;&gt;&gt; 3./2 # returns 1.5 It performs float division no matter of the Python version I choose. Because float / integer can only result in float. Also to make integer division in Python 3, you just write &gt;&gt;&gt; 3//2 See for further info
answers question: http://stackoverflow.com/q/49839680
score: 7
type: AcceptedAnswer
downvote count: 0
upvote count: 7

http://stackoverflow.com/q/49845914
tagged with: http-redirect
has body: Is there a way to automatically follow redirects using the http.client module: def grab_url(host, path = '/'): class Data: pass result = Data() try: con = http.client.HTTPConnection(host) con.request('GET', path) response = con.getresponse() if response.status == 200: result.content = response.read().decode('utf-8') result.headers = response.getheaders() catch Exception as e: print(e) return result The above works as long as the request returns a http response of 200, but I don't know how to handle redirects like 301? Using pyCurl I would simply set the FOLLOWLOCATION to True: def grab_url(host, path = '/'): buffer = BytesIO() c = pyCurl.Curl() c.setopt(c.FOLLOWLOCATION, True) c.setopt(c.URL, host + path) c.setopt(c.WRITEDATA, buffer) c.perform() status = c.getinfo(c.RESPONSE_CODE) if status == 200: return buffer.getvalue().decode('iso-8859-1')
tagged with: python
has comment: http://stackoverflow.com/comment/86707118
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/20475552
has answer: http://stackoverflow.com/a/79529188
favorite count: 0
type: Question
has title: Follow redirect using http.client
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86707018
linked to: http://stackoverflow.com/q/110498
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86706886
tagged with: http.client
upvote count: 5
score: 5

http://stackoverflow.com/q/49881359
downvote count: 0
answer count: 1
has title: How to replace &nbsp with white space
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49882600
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has body: I'm using this to remove but it leaves no spaces between words. I want to replace each &amp;nbsp; with a white space.
has comment: http://stackoverflow.com/comment/86778868
score: 1
has comment: http://stackoverflow.com/comment/86780128

http://stackoverflow.com/comment/86679103
type: Comment
has text: @Lado, don't be, I edited the answer and added the changes need to be made in order for your code to run...
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49831437

pre-trained-model
tag name: pre-trained-model
tags question: http://stackoverflow.com/q/49843345
type: Tag

http://stackoverflow.com/comment/86667336
has text: I got the file thanks.i was testing the code in the python shell thats why i was a bit confused, and where can i get the information about headers
score: 1
comment on: http://stackoverflow.com/a/49825630
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/97920124
type: QuestionComment
type: Comment
score: 0
has text: same problem here, how does python receive the data, is it in json format directly when you use mode json or do you have to call json.loads, also how to read it
comment on: http://stackoverflow.com/q/49848819

http://stackoverflow.com/q/49805746
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49808403
has answer: http://stackoverflow.com/a/49808439
tagged with: list
has answer: http://stackoverflow.com/a/49805836
answer count: 3
has answer: http://stackoverflow.com/a/49808403
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86626518
has comment: http://stackoverflow.com/comment/86626524
has comment: http://stackoverflow.com/comment/86626809
has body: Could you help with an advice or redirect me to related topic.. I am new to python and programming and kinda stack here. I have to get the following output: ..OO.OO.. .OOOOOOO. .OOOOOOO. ..OOOOO.. ...OOO... ....O.... but instead I get: ...... .OO... OOOO.. OOOOO. .OOOOO OOOOO. OOOO.. .OO... ...... grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] for i in range(0, len(grid)): output = "" for j in range(0,len(grid[i])): output += str(grid[i][j]) print(output)
tagged with: python
has title: How to get rotated output of lists?
accepted answer: http://stackoverflow.com/a/49805836

http://stackoverflow.com/q/49881935
tagged with: discord.py
score: 0
has comment: http://stackoverflow.com/comment/86779710
has answer: http://stackoverflow.com/a/49882699
has title: How do I get a random subreddit image to my discord.py bot?
upvote count: 5
downvote count: 5
tagged with: python
tagged with: praw
tagged with: discord
favorite count: 0
has body: I am making a discord bot in async python. I want the bot to post a random picture when I do a command (prefix !) example !meme. This would bring up a random picture from a subreddit, in this case the memes subreddit. I have made the start to what I want, but I need help with the random subreddit bit. import discord import praw from discord.ext import commands bot = commands.Bot(description="test", command_prefix="!") @bot.command() async def meme(): await bot.say(---) #--- WOULD BE THE REDDIT URL bot.run("TOKEN") How would I do this, using discord.py and PRAW?
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/65516078
possible better answer: http://stackoverflow.com/a/65516078
type: Question
accepted answer: http://stackoverflow.com/a/49882699
type: AnsweredQuestion

http://stackoverflow.com/comment/86783008
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49883476
has text: There are many examples on line and on this site that illustrate how to input a series of data. There are many examples of putting a series of data into a list. How did *none* of those get you to a point where you code write any code?
score: 0

http://stackoverflow.com/comment/86766606
type: AnswerComment
score: 0
has text: The admin made the change, but still the same message. However using the following shell command in server A, I was able to make the SQL connection to server B. `ssh -p PORTNUM -CNf -L3307:127.0.0.1:3306 MYID@SERVERB'sIP` then `mysql -u MYID -h 127.0.0.1 -P 3307 -e "use DBNAME; $query;` Wondering what's the difference with flask?
type: Comment
comment on: http://stackoverflow.com/a/49861136

http://stackoverflow.com/comment/86746296
type: Comment
type: QuestionComment
has text: can't follow the link, it is broken for me
comment on: http://stackoverflow.com/q/49865394
score: 0

http://stackoverflow.com/a/49843562
has comment: http://stackoverflow.com/comment/86706957
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49823073
upvote count: 1
has body: Here's one way of doing it: month = df.date - pd.Timedelta('1 day') * (df.date.dt.day - 1) df_exist = df.id.astype(str).str.get_dummies().groupby(month).sum() != 0 def fill_gaps(arr): notnan, = (~np.isnan(arr)).nonzero() return np.nan if not notnan.size else arr[notnan[-1]] date_range = pd.date_range('2018-01-01', '2018-12-31', freq='MS') rolling = df_exist.reindex(date_range).rolling(window=2, min_periods=1) result = rolling.apply(fill_gaps).fillna(False).astype(bool) result[date_range &gt; month.max()] = False The first part should be much faster than doing the joins manually. The second part makes use of rolling API for dataframes. The output looks like this: 1 2 3 2018-01-01 False False False 2018-02-01 True False True 2018-03-01 True False False 2018-04-01 True False False 2018-05-01 True False False 2018-06-01 False True False 2018-07-01 False True False 2018-08-01 False True False 2018-09-01 False True False 2018-10-01 True False False 2018-11-01 True False False 2018-12-01 False False False which seems to match the results in your example.
answers question: http://stackoverflow.com/q/49823073
type: Answer
has comment: http://stackoverflow.com/comment/86704212
has comment: http://stackoverflow.com/comment/86703698

http://stackoverflow.com/a/62998683
has body: I faced similar issue and found out that it is because of \xa1 character which is hex value of ascii 26 (SUB). Openpyxl is not allowing to write such characters (ascii code &lt; 32). I tried xlsxwriter library without any issue it worte this character in xlsx file.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49844925
score: 10
upvote count: 10

http://stackoverflow.com/a/49868099
has body: Either creating an instance an saving it: newAlbum = Album(name="1", Artist=newArtist).save() or using the models manager create method newAlbum = Album.objects.create(name="1", Artist=newArtist) Read more in the docs.
upvote count: 1
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/86912483
type: Answer
answers question: http://stackoverflow.com/q/49867587

http://stackoverflow.com/a/49872262
type: AcceptedAnswer
has body: I don't know if you can do it vectorised, but you can do it with iteration result = pd.DataFrame(None, index=df.index, columns=['X', 'Y']) for row in df.itertuples(): x, y = f'{row.Events}_X', f'{row.Events}_Y' if row.Events == 'nan': result.loc[row.Index, ['X', 'Y']] = [np.nan, np.nan] else: result.loc[row.Index, ['X', 'Y']] = row._asdict()[x], row._asdict()[y] using np.where result = pd.DataFrame(None, index=df.index, columns=['X', 'Y']) for value in df['Events'].unique(): if value == 'nan': continue x, y = f'{value}_X', f'{value}_Y' result'X', 'Y' = np.where(df'Events' == value, dfx, y, result) X Y 0 1 51 22 2 3 11 77 4 104 88 5 29 70 6 7 8 42 13 9 36 70
accepted answer of: http://stackoverflow.com/q/49871890
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49871890
upvote count: 1

aggregate
tags question: http://stackoverflow.com/q/49882714
tags question: http://stackoverflow.com/q/49908004
tag name: aggregate
type: Tag

http://stackoverflow.com/comment/86641485
type: QuestionComment
type: Comment
score: 0
has text: Thank you Wikton!
comment on: http://stackoverflow.com/q/49813447

http://stackoverflow.com/comment/86636683
type: AnswerComment
type: Comment
has text: Looks like the above error is a bug in `dbf`; working on a fix.
score: 0
comment on: http://stackoverflow.com/a/49780950

http://stackoverflow.com/comment/86803461
has text: I mean you could do `new_b = B();` `new_b.value = self.value` but passing the argument is more explicit.
comment on: http://stackoverflow.com/q/49893793
score: 1
type: Comment
type: QuestionComment

rtmp
tag name: rtmp
type: Tag
tags question: http://stackoverflow.com/q/49848011

http://stackoverflow.com/q/49864234
score: 4
has answer: http://stackoverflow.com/a/61220222
tagged with: deep-learning
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/35733917
linked to: http://stackoverflow.com/q/33748552
tagged with: tensorflow
favorite count: 0
type: Question
has title: TensorFlow: Restoring variables from two checkpoints after combining two graphs
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/113711637
tagged with: python
has body: I got an issue with TensorFlow, hope you can help :D My goal: say I got two graphs, Graph A and Graph B, each one composed of three convolutional layers. What I want is to link the second layer of Graph A to the third layer of Graph B. I've successfully combined two graphs using the information given here: Tensorflow: How to replace a node in a calculation graph? This is what I got: The problem comes when I try to load variable weights. I've followed this solution, but didn't work: TensorFlow: Restoring variables from from multiple checkpoints There is no problem when loading the weights of graph A, but this error arises when loading the weights of graph B: INFO:tensorflow:Restoring parameters from ./models/merge_graph_A.ckpt INFO:tensorflow:Restoring parameters from ./models/merge_graph_B.ckpt --------------------------------------------------------------------------- NotFoundError Traceback (most recent call last) &lt;ipython-input-27-1e08224fde39&gt; in &lt;module&gt;() 1 with tf.Session(graph=graphs_merged) as sess: 2 saver_A.restore(sess, './models/merge_graph_A.ckpt') ----&gt; 3 saver_B.restore(sess, './models/merge_graph_B.ckpt') 4 5 outcome = sess.run(output, feed_dict={ /home/solano/.local/lib/python2.7/site-packages/tensorflow/python/training/saver.pyc in restore(self, sess, save_path) 1753 if context.in_graph_mode(): 1754 sess.run(self.saver_def.restore_op_name, -&gt; 1755 {self.saver_def.filename_tensor_name: save_path}) 1756 else: 1757 self._build_eager(save_path, build_save=False, build_restore=True) /home/solano/.local/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata) 903 try: 904 result = self._run(None, fetches, feed_dict, options_ptr, --&gt; 905 run_metadata_ptr) 906 if run_metadata: 907 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) /home/solano/.local/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run…
upvote count: 4

http://stackoverflow.com/q/49864912
upvote count: 1
accepted answer: http://stackoverflow.com/a/49962000
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86745343
type: AnsweredQuestion
score: 0
tagged with: data-analysis
tagged with: pandas
has answer: http://stackoverflow.com/a/49962000
downvote count: 1
tagged with: python
has title: Make line chart with multiple series and error bars
has body: I'm hoping to create a line graph which shows the changes to flowering and fruiting times (phenophases) from year to year. For each phenophase I'd like to plot the average Day of Year and, if possible, show the min and max for each year as an error bar. I've filtered down all the data I need in a few data frames, grouped it all in a sensible way, but I can't figure out how to get it all to plot. Here's a screen grab of where I'm at: Imgur All the examples I've found adding error bars have been based on formulas or other equal amounts over/under, but in my case the max/min will be different so I'm not sure how to integrate that. Possible just create a list of each column's data and feed that to plot? I'm playing with that now but not getting far. Also, if anyone has general suggestions as to better ways to present this data I'm all ears. I've looked into Gantt plots but didn't get far with them, as this seems a bit more straight-forward just using matplotlib. I'm happy to put some demo data or the rest of my notebook up if anyone thinks that would help. Edit: Here's some sample data and the code from my notebook: Gist import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker %matplotlib inline pd.set_option('display.max_columns', 40) tick_spacing = 1 dfClean = df'Site_Cluster', 'Species', 'Phenophase_Name', 'Phenophase_Status', 'Observation_Year', 'Day_of_Year' dfClean = dfClean[dfClean.Phenophase_Status == 1] PhenoNames = ['Open flowers', 'Ripe fruits'] dfLakes = dfClean[(dfClean.Phenophase_Name.isin(PhenoNames)) &amp; (dfClean.Site_Cluster == 'Lakes') &amp; (dfClean.Species == 'lapponica')] dfLakesGrouped = dfLakes.groupby(['Observation_Year', 'Phenophase_Name']) dfLakesReady = dfLakesGrouped.Day_of_Year.agg([np.min, np.mean, np.max]).round(0) dfLakesReady = dfLakesReady.unstack() print(dfLakesReady['mean'].plot())

http://stackoverflow.com/a/49882888
has body: The array contents are written back to alist towards the end of the function, and alist is lefthalf in the level above. I found this really confusing when I switched from C to Python, but in Python, everything is a reference to an object, and so all function calls are effectively pass-by-reference.
has comment: http://stackoverflow.com/comment/86781766
type: Answer
has comment: http://stackoverflow.com/comment/86786103
answers question: http://stackoverflow.com/q/49882807
score: 0
has comment: http://stackoverflow.com/comment/86789971

http://stackoverflow.com/q/49864385
accepted answer: http://stackoverflow.com/a/49864869
has answer: http://stackoverflow.com/a/49864869
has comment: http://stackoverflow.com/comment/86744421
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49864717
has comment: http://stackoverflow.com/comment/86744397
tagged with: strip
has title: Unable to remove line breaks in a text file in python
tagged with: python
has body: At the risk of losing reputation I did not know what else to do. My file is not showing any hidden characters and I have tried every .replace and .strip I can think of. My file is UTF-8 encoded and I am using python/3.6.1 I have a file with the format: &gt;header1 AAAAAAAA TTTTTTTT CCCCCCCC GGGGGGGG &gt;header2 CCCCCC TTTTTT GGGGGG AAAAAA I am trying to remove line breaks from the end of the file to make each line a continuous string. (This file is actually thousands of lines long). My code is redundant in the sense that I typed in everything I could think of to remove line breaks: fref = open(ref) for line in fref: sequence = 0 header = 0 if line.startswith('&gt;'): header = ''.join(line.splitlines()) print(header) else: sequence = line.strip("\n").strip("\r") sequence = line.replace('\n', ' ').replace('\r', '').replace(' ', '').replace('\t', '') print(len(sequence)) output is: &gt;header1 8 8 8 8 &gt;header2 6 6 6 6 But if I manually go in and delete the end of line to make it a continuous string it shows it as a congruent string. Expected output: &gt;header1 32 &gt;header2 24 Thanks in advance for any help, Dennis
has comment: http://stackoverflow.com/comment/86744495
type: Question
tagged with: replace
answer count: 2
has comment: http://stackoverflow.com/comment/86744481
has answer: http://stackoverflow.com/a/49864717
has comment: http://stackoverflow.com/comment/86744206

http://stackoverflow.com/q/49773300
duplicate of: http://stackoverflow.com/q/33224526
has body: The duplicate answer explains how to solve this using $.ajax. I'm using $.post, though I don't understand how to set settings individually for $.post use cases, which I've used 20+ times throughout the project. Yet the documentation hints this is possible and one comment on this thread states that it is. I'm trying to do a post request to my Django view using jQuery's $.post. The elements I'm trying to get to Python are lists (arrays) that I build off of multiple IDs. Here is my jQuery code: var newBaseline = function () { // Initialize arrays each time the function is run var timeArray = []; var parametersArray = []; var runsArray = []; // Cycle through some input elements and get their values, push to array timeRangeInputs.each(function() { timeArray.push($(this).val()); }); // Cycle through some checkboxes and get their data-id values, push to array parameterContainer.find("input:checked").each(function() { parametersArray.push($(this).data("parameter_id")); }); // Cycle through some checkboxes and get their data-id values, push to array runContainer.find("input:checked").each(function() { runsArray.push($(this).data("run_id")); }); // Just a flag for my view so I can do if-else cases in python // as the view handles several forms in the same page var flag = "new-baseline"; $.post("{% url 'my_view %}", { csrfmiddlewaretoken: "{{csrf_token}}", timeArray: timeArray, parametersArray: parametersArray, runsArray: runsArray, flag: flag }, function(data) { // check valid or errors, etc }).done(); }; The problem arises when I go to my Python view. The request.POST QueryDict object comes in fine, but the arrays have additional []'s appended. print(request.POST) &gt;&gt;&gt; &lt;QueryDict: {'runsArray[]': ['3, 7'], 'csrfmiddlewaretoken': ['foobar'], 'parametersArray[]': ['409'], 'timeArray': ['257.5674', '591.8532'], 'flag': ['new-baseline'] }&gt; Why is this happening? Why is 'flag' not behaving the same way? (I outright hard-code flag as a "string" in my JS) Why is the h…
has comment: http://stackoverflow.com/comment/86561772
type: Question
has comment: http://stackoverflow.com/comment/86566215
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2540827
has comment: http://stackoverflow.com/comment/86561950
has title: Django, jQuery $.post: request elements have extra "[]" added
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86567389
tagged with: jquery
has comment: http://stackoverflow.com/comment/86564888
has comment: http://stackoverflow.com/comment/86563906
score: 0
answer count: 0
linked to: http://stackoverflow.com/q/33224526
has comment: http://stackoverflow.com/comment/86584118
has comment: http://stackoverflow.com/comment/86567003

http://stackoverflow.com/a/49770121
score: 3
accepted answer of: http://stackoverflow.com/q/49769562
has comment: http://stackoverflow.com/comment/86555575
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49769562
has body: As Paulo mentioned, you missed off the "gz" flag the second time you opened the tar file. Also, your target for copying the file was the original tarball - I assume you wanted it in a separate directory ("targdir" here) You only need to extract the contents once, so the code becomes: file=my_path+"/"+fil targdir='dest' if file.endswith('.tar.gz'): tarf = tarfile.open(file, "r:gz") tarf.extractall() for info in tarf: if info.name.endswith('.txt'): print(info.name) code=os.system('cp ' + info.name +' '+ targdir) (edit - you don't need 'mypath' in the "cp" command - you have extracted the tarball into the current directory, so "info.name! is the full path to the file)
upvote count: 3

http://stackoverflow.com/comment/86671663
has text: Possible duplicate of [pip install fails for every package ("Could not find a version that satisfies the requirement")](https://stackoverflow.com/questions/49748063/pip-install-fails-for-every-package-could-not-find-a-version-that-satisfies-th)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49762035
score: 0

http://stackoverflow.com/q/49799852
answer count: 2
has body: I am trying to generate PDF through python by using reportlab. (beginner level) Basically, I want to create a table with a checkbox inside. For example, refer to below code: ... data =[ [Paragraph("Option 1",style=custom_para), "anything"], [Paragraph("Option 2",style=custom_para), "anything"] ] t=Table(data, style=style_table, colWidths=[100, 100]) Story.append(t) ... I already tested that the above code can generate table correctly. Now, I want something further, which is something like: ... data =[ [Paragraph("Option 1",style=custom_para), checkbox_1], [Paragraph("Option 2",style=custom_para), checkbox_2] ] t=Table(data, style=style_table, colWidths=[100, 100]) Story.append(t) ... How should I implement the checkbox_1, checkbox_2? What is the most efficient way to achieve this?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/60263123
upvote count: 3
score: 3
tagged with: reportlab
downvote count: 0
has answer: http://stackoverflow.com/a/50043722
favorite count: 0
has title: How to add a checkbox inside Table for Reportlab in python?
type: Question

http://stackoverflow.com/comment/86667009
comment on: http://stackoverflow.com/q/49825444
type: QuestionComment
type: Comment
has text: Actually, it's not even implicit. From the second answer of the dupe target, a comma is all that's required to create a tuple, so my example is just explicitly creating a tuple then returning it.
score: 1

http://stackoverflow.com/comment/86683942
comment on: http://stackoverflow.com/q/49834284
score: 1
type: QuestionComment
type: Comment
has text: It looks like you're not yet familiar with lists and dicts. You should start using them.

http://stackoverflow.com/comment/132095479
comment on: http://stackoverflow.com/a/56932297
type: AnswerComment
has text: sr i forgot to close the stream : `buf.close()` just before `return`
type: Comment
score: 0

http://stackoverflow.com/comment/86787503
type: QuestionComment
has text: I am only only using gevent. It appears that somehow eventlet is involved.
comment on: http://stackoverflow.com/q/49854669
score: 0
type: Comment

http://stackoverflow.com/q/49886607
answer count: 1
downvote count: 0
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49888489
has body: I'm doing a merge in R of my tables using the foverlaps function. But I need to reproduce the same output using python. I did a search and I found the merge function on pandas library. But even using this function, I can't reproduce the same output. First the outputs in R: This is the first table (intervals): V1 V2 intid 1: 1 5 1 2: 4 9 2 3: 6 12 3 4: 11 17 4 5: 18 20 5 This is the second table (decomp): V1 V2 subid 1: 1 4 A 2: 4 5 B 3: 5 6 C 4: 6 9 D 5: 9 11 E 6: 11 12 F 7: 12 17 G 8: 17 18 H 9: 18 20 I The code in R that makes the merge: relations &lt;- foverlaps(decomp, intervals, type='within', nomatch=0) The output (relations): V1 V2 intid i.V1 i.V2 subid 1: 1 5 1 1 4 A 2: 1 5 1 4 5 B 3: 4 9 2 4 5 B 4: 4 9 2 5 6 C 5: 4 9 2 6 9 D 6: 6 12 3 6 9 D 7: 6 12 3 9 11 E 8: 6 12 3 11 12 F 9: 11 17 4 11 12 F 10: 11 17 4 12 17 G 11: 18 20 5 18 20 I Now the outputs I have in python: This is the first table (df_of_pairs): V1 V2 intid 0 1 5 1 1 4 9 2 2 6 12 3 3 11 17 4 4 18 20 5 This is the second table (df_of_adjacent): V1 V2 subid 0 1 4 A 1 4 5 B 2 5 6 C 3 6 9 D 4 9 11 E 5 11 12 F 6 12 17 G 7 17 18 H 8 18 20 I Now is the problem, I did not reproduce the same output in python when I used the pandas merge. I tried it in several ways and I did not succeed with any, here's one of the ways I've used it: df = df_of_pairs.merge(df_of_adjacent, left_on=['V1'], right_on=['V2'] ) The output (df): V1_x V2_x intid V1_y V2_y subid 0 4 9 2 1 4 A 1 6 12 3 5 6 C 2 11 17 4 9 11 E 3 18 20 5 17 18 H This question is very similar to R foverlaps equivalent in Python, but in that case it has different columns.
score: 3
tagged with: pandas
upvote count: 3
linked to: http://stackoverflow.com/q/40247095
has title: How to reproduce the same output of foverlaps in R with merge of pandas in python?
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/30627968

http://stackoverflow.com/comment/86841526
type: AnswerComment
comment on: http://stackoverflow.com/a/49909306
type: Comment
has text: I am still not getting the solution ...I have made separate function for comparing predicted value with the threshold.If it's still not correct, can you please help me how to do the required comparison done.
score: 0

http://stackoverflow.com/q/49911935
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/86839741
downvote count: 2
type: UnansweredQuestion
has title: Use python to control computer
answer count: 1
has body: Do you guys know how to write a program and control a computer (shutdown)? Maybe module OS can answer, but I only know how to use os.path and os.system. I've already try this way: import os os.chdir('C:\Windows\System32') with open('cmd.exe',encoding='utf-8')as f: exec(f.read()) exec(f.write('shutdown -i')) but shows error: Traceback (most recent call last): File "D:\Mystuff\try.py", line 4, in exec(f.read()) File "C:\Users\Vic_Lee\AppData\Local\Programs\Python\Python36-32\lib\codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x90 in position 2: invalid start byte Any ideas?
has comment: http://stackoverflow.com/comment/86839622
favorite count: 0
has answer: http://stackoverflow.com/a/49911978
has comment: http://stackoverflow.com/comment/86839645
has comment: http://stackoverflow.com/comment/86839602
score: -2
tagged with: operating-system
tagged with: python
tagged with: python-3.6

http://stackoverflow.com/q/49847684
tagged with: pandas
has title: matplotlib Y-axis scale does not match data
has comment: http://stackoverflow.com/comment/86743776
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/49848141
type: UnansweredQuestion
tagged with: matplotlib
tagged with: dataframe
tagged with: python
has body: Trying to figure out what I am doing wrong here since the y-axis does not look like the data I am using. The data are coming from a Google sheet and seems to go into the dataframe correctly. df = pd.DataFrame.from_records(values[1:], columns=values[0]) df.set_index('date') print(df) datelist = df.date.tolist() fmt = '%Y-%m-%d' # check the time format of the timestamp in the first column x_axis = [datetime.strptime(dat, fmt) for dat in datelist] plt.style.use('ggplot') plt.plot(x_axis, 'usage', data=df, color='skyblue', linewidth=2, label='Daily Usage') plt.plot(x_axis, 'currenttotal', data=df, color='yellow', linewidth=2, label='Total Usage') plt.xlabel('Date') plt.ylabel('Bandwidth Usage') plt.legend(loc='upper left') plt.savefig('todaysplot.png', dpi=300) Here is the dataframe: ` date usage currenttotal 0 2017-11-08 13 328 1 2017-11-09 12 340 2 2017-11-10 12 359 3 2017-11-11 7 366` If you note in the y-axis ticks I am getting the numbers on the left of the dataframe and want numbers from 0 to 1024 on the left, but have not been able to figure out how to do make this happen.
score: 0

http://stackoverflow.com/a/49828087
accepted answer of: http://stackoverflow.com/q/49828029
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49828029
upvote count: 2
has body: You can pad the hex value to the specified number of digits by using the ljust method. Whenever the string is less than the specified width, it'll append the specified filler character to extend it. In your example example, hex(0x0).ljust(8, '0') == "0x000000". Strings that are already long enough are preserved so that 0xFF0000 will still work. print(hex(0x000000).ljust(8, '0')) # Prints 0x000000 print(hex(0xFF0000).ljust(8, '0')) # Prints 0xFF0000 A couple of important things to note that have bitten me in the past: Make sure your width includes the length of the leading "0x" This is because the ljust function operator operates on raw text and doesn't realize it's a hex string If you give a width value shorter than you need, the strings won't be filled up enough and will have different lengths. In other words len(hex(0xFF0000).ljust(4, '0')) != len(hex(0xFF0000).ljust(4, '0')) because you need a length of 8 characters to fit both cases
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49793220
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86600819
has comment: http://stackoverflow.com/comment/86601844
accepted answer: http://stackoverflow.com/a/49793320
has comment: http://stackoverflow.com/comment/86602031
score: 1
tagged with: port
has answer: http://stackoverflow.com/a/49793320
has comment: http://stackoverflow.com/comment/86602261
tagged with: python
has body: In Python3 I have a program to test the web framework bottle: from bottle import route, run @route('/') def index(): return "olá pessoas" if __name__ == '__main__': run() I am running the programs inside a virtualenv, in the command line. But there is this error: (live-de-python) reinaldo@reinaldo-Inspiron-5567:~/Documentos/Code/live-de-python/repo$ python3 basic_bottle.py Bottle v0.12.13 server starting up (using WSGIRefServer())... Listening on http://127.0.0.1:8080/ Hit Ctrl-C to quit. Traceback (most recent call last): File "basic_bottle.py", line 11, in &lt;module&gt; run() File "/home/reinaldo/Documentos/Code/live-de-python/lib/python3.6/site-packages/bottle.py", line 3127, in run server.run(app) File "/home/reinaldo/Documentos/Code/live-de-python/lib/python3.6/site-packages/bottle.py", line 2781, in run srv = make_server(self.host, self.port, app, server_cls, handler_cls) File "/usr/lib/python3.6/wsgiref/simple_server.py", line 153, in make_server server = server_class((host, port), handler_class) File "/usr/lib/python3.6/socketserver.py", line 453, in __init__ self.server_bind() File "/usr/lib/python3.6/wsgiref/simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "/usr/lib/python3.6/http/server.py", line 136, in server_bind socketserver.TCPServer.server_bind(self) File "/usr/lib/python3.6/socketserver.py", line 467, in server_bind self.socket.bind(self.server_address) OSError: [Errno 98] Address already in use I'm using Ubuntu. Does the error say that port 8080 is already in use? But I have no other program open Please, does anyone know what it can be?
tagged with: bottle
has title: How to avoid port error already used in web framework bottle?
has comment: http://stackoverflow.com/comment/86601437
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86607707
tagged with: web-frameworks
upvote count: 1

http://stackoverflow.com/a/49858693
upvote count: 2
has comment: http://stackoverflow.com/comment/86784134
downvote count: 0
has comment: http://stackoverflow.com/comment/86812227
score: 2
has body: Your code appears incomplete, but what you've shown has two issues. One is that run_until_complete accepts a coroutine object (or other kind of future), not a coroutine function. So it should be: # note parentheses after your_async_function() asyncio.get_event_loop().run_until_complete(your_async_function()) the problem is that no matter what I do it only listen to the first socket I call. I think its the infinite loop, what are my option to solve this? using threads for each sockets? The infinite loop is not the problem, asyncio is designed to support such "infinite loops". The problem is that you are trying to do everything in one coroutine, whereas you should be creating one coroutine per websocket. This is not a problem, as coroutines are very lightweight. For example (untested): async def subscribe_all(self, payload): loop = asyncio.get_event_loop() # create a task for each URL for url in url_list: tasks.append(loop.create_task(self.subscribe_one(url, payload))) # run all tasks in parallel await asyncio.gather(*tasks) async def subsribe_one(self, url, payload): async with websockets.connect(url) as websocket: await websocket.send(payload) while True: msg = await websocket.recv() print(msg)
answers question: http://stackoverflow.com/q/49858021
type: Answer
has comment: http://stackoverflow.com/comment/86799087
has comment: http://stackoverflow.com/comment/86798708
has comment: http://stackoverflow.com/comment/86768178
has comment: http://stackoverflow.com/comment/86769717
has comment: http://stackoverflow.com/comment/86812089

http://stackoverflow.com/a/49763268
type: AcceptedAnswer
downvote count: 1
score: 6
has comment: http://stackoverflow.com/comment/113239820
has comment: http://stackoverflow.com/comment/113261543
has comment: http://stackoverflow.com/comment/86545591
has comment: http://stackoverflow.com/comment/115532135
has body: To find the size of the top-level "folders" in S3 (S3 does not really have a concept of folders, but kind of displays a folder structure in the UI), something like this will work: from boto3 import client conn = client('s3') top_level_folders = dict() for key in conn.list_objects(Bucket='kitsune-buildtest-production')['Contents']: folder = key['Key'].split('/')[0] print("Key %s in folder %s. %d bytes" % (key['Key'], folder, key['Size'])) if folder in top_level_folders: top_level_folders[folder] += key['Size'] else: top_level_folders[folder] = key['Size'] for folder, size in top_level_folders.items(): print("Folder: %s, size: %d" % (folder, size))
has comment: http://stackoverflow.com/comment/115317604
type: Answer
has comment: http://stackoverflow.com/comment/86561779
accepted answer of: http://stackoverflow.com/q/49759940
answers question: http://stackoverflow.com/q/49759940
upvote count: 7

http://stackoverflow.com/comment/86543255
score: 0
comment on: http://stackoverflow.com/q/49762985
type: QuestionComment
has text: Thanks for suggestions, @Y.Luo, I guess I'll have to get rid of Python at all and maybe to try to start it from scratch. I don't remember time, when it python stuff actually worked out of box, it always had its humors... Maybe that's why I never had enough patience to deal with it.
type: Comment

http://stackoverflow.com/comment/86708834
type: AnswerComment
comment on: http://stackoverflow.com/a/49846898
has text: Oops, you mean that the whole problem was about adding `y[i]=yt[i]` in the blocks? Weird and perfect.
type: Comment
score: 0

http://stackoverflow.com/q/49877129
tagged with: pandas
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49878077
type: Question
tagged with: binary
possible better answer: http://stackoverflow.com/a/49877331
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49877331
accepted answer: http://stackoverflow.com/a/49878077
has title: pandas series bits to integer in decimal base
has answer: http://stackoverflow.com/a/49877778
tagged with: timing
has body: I have a pandas Dataframe of dimensions (m,n) that is filled with 0 and 1. If each row of the dataframe is considered as a binary number, I would like to generate a pandas Series with the integer number in base 10 represented by that row. Given the following matrix of dimensions (m,n) filled with 0 and 1: m = int(1e6) n = 5 df = pd.DataFrame(np.random.rand(m,n)).round().astype(int) The method I use right now is this one: df_asstr = df.astype(str) bin_series = df_asstr.sum(axis=1).astype(int).astype(str) def bin_to_int(strnum): return int(strnum, 2) decimal_series = bin_series.astype(str).apply(bin_to_int) My issue here is TIMING. If the dataframe has length on the order of m=1e3, then the whole process takes less than one second. However, when I with m=1e6, it takes about 22 seconds, and I need to run many of these, so I really want to speed it up. I am aware that the steps slowing down the process are those involving conversion of the DataFrame to str, i.e. these lines: df_asstr = df.astype(str) bin_series = df_asstr.sum(axis=1).astype(int).astype(str) decimal_series = bin_series.astype(str).apply(bin_to_int) Does anyone know a more efficient way to create the series of integers in decimal base?? Thanks a lot!
type: AnsweredQuestion
score: 3
tagged with: performance
answer count: 3

http://stackoverflow.com/a/49804131
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86623981
has body: As pointed out in this answer, print is a function in Python 3, which means you need to wrap the arguments to print within parentheses. So this should fix the error in your case: print("employee / supervisor id :" ,k.get_id()," Date joined :" ,k.get_date())
accepted answer of: http://stackoverflow.com/q/49803904
answers question: http://stackoverflow.com/q/49803904
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86623264

http://stackoverflow.com/q/49785756
accepted answer: http://stackoverflow.com/a/49786033
upvote count: 1
has comment: http://stackoverflow.com/comment/86586946
has title: How to find whole string using find()
has comment: http://stackoverflow.com/comment/86587262
has comment: http://stackoverflow.com/comment/86586928
has comment: http://stackoverflow.com/comment/86587006
has answer: http://stackoverflow.com/a/49786033
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86587174
downvote count: 0
has comment: http://stackoverflow.com/comment/86587389
score: 1
answer count: 1
tagged with: python
has body: How to find whole string using find() function? For example my input: word = 'banana' sentence1 = 'Hello, I very like eat banana' &gt;True sentence2 = ' Hello, I very like eat banana1' &gt;False I want to use find() function, because I want get start and end position of this string. For example: loc = sentence1.find(word)
has comment: http://stackoverflow.com/comment/86586982
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86587049

http://stackoverflow.com/comment/86643198
score: 0
has text: @ArtemisFowl, I just edited with code and some comments.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49811533

http://stackoverflow.com/a/49861953
has body: If you don't need to listen to any signals, you can directly update all related answers using F()expressions: from django.db.models import F def question_detail(request, id): my_question = Question.objects.get(id=id) my_question.answer_set.update(answer_views=F('answer_views') + 1)
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86739072
answers question: http://stackoverflow.com/q/49861748
accepted answer of: http://stackoverflow.com/q/49861748
type: Answer

http://stackoverflow.com/a/49787372
upvote count: 1
has body: You can use key word arguments width, and height with a tk.Label import tkinter as tk if __name__ == '__main__': root = tk.Tk() root.geometry("250x50") label_frame = tk.Frame(root) w = tk.Label(label_frame, text="Label UNO", bg="red", fg="white", width=8, height=2) w.pack(side=tk.LEFT) w = tk.Label(label_frame, text="Label2", bg="green", fg="black", width=8, height=2) w.pack(side=tk.LEFT) w = tk.Label(label_frame, text="Label DREI", bg="blue", fg="white", width=8, height=2) w.pack(side=tk.LEFT) label_frame.pack(expand=True) root.mainloop() Notes: tkinter is imported as tk in order to keep the namespace tidy. The tk.Labels are included in a tk.Frame, so once this is built, you do not have to worry about it until you pack the frame in your GUI. The units for width and height are in "text units" when the label contains text.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49787177
downvote count: 0

http://stackoverflow.com/a/49890701
answers question: http://stackoverflow.com/q/49890561
score: 0
upvote count: 1
downvote count: 1
has body: Use ast module literal_eval method for a safer eval import ast input = "[[1,2,3],['c',4,'r']]" output= ast.literal_eval(input) print(output) #[[1, 2, 3], ['c', 4, 'r']] This code is tested in Python 3.6. It works even in 2.7 also.
type: Answer

http://stackoverflow.com/comment/86666649
type: AnswerComment
has text: `parent` isn't the instance of `MainProgram`, it's an instance of a frame inside the main program. Your code won't work because the frame doesn't have the `var1` attribute.
score: 0
comment on: http://stackoverflow.com/a/49825366
type: Comment

http://stackoverflow.com/comment/86681657
has text: @ScottBoston `data.sum()` only gives me 34 and 31 which are the results for the 2nd and the 3rd columns ignoring the first column.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49833151

classification
tags question: http://stackoverflow.com/q/49811533
tag name: classification
tags question: http://stackoverflow.com/q/49844907
tags question: http://stackoverflow.com/q/49805404
tags question: http://stackoverflow.com/q/49837058
type: Tag
tags question: http://stackoverflow.com/q/49777853
tags question: http://stackoverflow.com/q/49804102
tags question: http://stackoverflow.com/q/49849715
tags question: http://stackoverflow.com/q/49806437

http://stackoverflow.com/comment/86575354
comment on: http://stackoverflow.com/a/49779999
type: AnswerComment
score: 1
has text: You can use a `defaultdict` from `collections` for this.
type: Comment

storage
tag name: storage
tags question: http://stackoverflow.com/q/49828956
type: Tag

http://stackoverflow.com/q/49848500
has comment: http://stackoverflow.com/comment/86713059
has comment: http://stackoverflow.com/comment/86713302
linked to: http://stackoverflow.com/q/5287253
has answer: http://stackoverflow.com/a/49848764
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/49848764
has comment: http://stackoverflow.com/comment/86711817
has comment: http://stackoverflow.com/comment/86712161
score: 1
has comment: http://stackoverflow.com/comment/86712435
has comment: http://stackoverflow.com/comment/86712884
has comment: http://stackoverflow.com/comment/86714024
has body: I have a file with MIME type of text/x-python. It shows binary format when I opened it with Vim. The file begins with these bytes, according to a hexdump with xxd: 00000000: 03f3 0d0a f0db af5a 6300 0000 0000 0000 .......Zc....... 00000010: 000e 0000 0040 6001 0073 2f0b 0000 6400 .....@`..s/...d. How to convert this file into text format?
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
has title: How to convert text/x-python to plain text format?
has comment: http://stackoverflow.com/comment/86711776
has comment: http://stackoverflow.com/comment/86712446
has comment: http://stackoverflow.com/comment/86712110
tagged with: python

http://stackoverflow.com/a/49764549
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49763005
score: 1
answers question: http://stackoverflow.com/q/49763005
has body: There are 3 errors in your code: Test equality of variables via == operator. Make sure you bracket individual conditions to avoid chained comparisons. For a date to be within 90 days, check your test data is greater than days90. Combined, the following code will work: df['NewText'] = np.where((df['Text1'] == "abc") &amp; (df['Date1'] &gt; days90), "New", np.nan)
downvote count: 0
type: Answer
type: AcceptedAnswer

http://stackoverflow.com/q/49798902
has comment: http://stackoverflow.com/comment/86612496
has body: I want to assign an imaginary number to a variable: import math a = sqrt(4)j print(a) This results in a SyntaxError: Line 3: SyntaxError: bad input ('j') I can assign an imaginary number to variable like this: a = 2j How do I solve this?
favorite count: 0
has answer: http://stackoverflow.com/a/49798960
type: Question
has title: Return a complex number from function
type: UnansweredQuestion
score: -3
downvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/49798948
answer count: 2
upvote count: 2
linked to: http://stackoverflow.com/q/8370637

http://stackoverflow.com/a/49825412
has comment: http://stackoverflow.com/comment/108883305
has comment: http://stackoverflow.com/comment/99050714
has comment: http://stackoverflow.com/comment/87351156
has comment: http://stackoverflow.com/comment/99173041
has comment: http://stackoverflow.com/comment/127908467
has comment: http://stackoverflow.com/comment/87356579
has body: One way to accomplish this is using morphological operations and contour detection. With the former you essentially "bleed" all characters into a big chunky blob. With the latter, you locate these blobs in your image and extract the ones that seem interesting (meaning: big enough). Script used: import cv2 import sys SCALE = 4 AREA_THRESHOLD = 427505.0 / 2 def show_scaled(name, img): try: h, w = img.shape except ValueError: h, w, _ = img.shape cv2.imshow(name, cv2.resize(img, (w // SCALE, h // SCALE))) def main(): img = cv2.imread(sys.argv[1]) img = img[10:-10, 10:-10] # remove the border, it confuses contour detection gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) show_scaled("original", gray) # black and white, and inverted, because # white pixels are treated as objects in # contour detection thresholded = cv2.adaptiveThreshold( gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 25, 15 ) show_scaled('thresholded', thresholded) # I use a kernel that is wide enough to connect characters # but not text blocks, and tall enough to connect lines. kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (13, 33)) closing = cv2.morphologyEx(thresholded, cv2.MORPH_CLOSE, kernel) im2, contours, hierarchy = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) show_scaled("closing", closing) for contour in contours: convex_contour = cv2.convexHull(contour) area = cv2.contourArea(convex_contour) if area &gt; AREA_THRESHOLD: cv2.drawContours(img, [convex_contour], -1, (255,0,0), 3) show_scaled("contours", img) cv2.imwrite("/tmp/contours.png", img) cv2.waitKey() if __name__ == '__main__': main() Then all you need is to compute the bounding box of the contour, and cut it from the original image. Add a bit of a margin and feed the whole thing to tesseract.
has comment: http://stackoverflow.com/comment/102907112
score: 5
has comment: http://stackoverflow.com/comment/102910619
downvote count: 0
has comment: http://stackoverflow.com/comment/127883941
has comment: http://stackoverflow.com/comment/102879595
has comment: http://stackoverflow.com/comment/127884445
has comment: http://stackoverflow.com/comment/127884023
upvote count: 5
has comment: http://stackoverflow.com/comment/102887283
answers question: http://stackoverflow.com/q/49823451
type: Answer

http://stackoverflow.com/comment/86666515
has text: when you are getting a single object you need send de `pk`, `http://127.0.0.1:8000/stocks/1` , when `1` is the pk, and if the answer is correctly you should be mark this has answer.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49825104

http://stackoverflow.com/q/49910979
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50205063
has answer: http://stackoverflow.com/a/54168668
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/54418483
has body: I see this in programs where people will assign a line/multiple lines of code with "#". I thought this was strictly for commenting. How does this affect an overall program?
favorite count: 0
has title: Besides commenting, does "#" have another other purpose in python 3?
answer count: 3
has comment: http://stackoverflow.com/comment/86838040
has comment: http://stackoverflow.com/comment/86837894
has comment: http://stackoverflow.com/comment/86837924
score: -6
downvote count: 7
has comment: http://stackoverflow.com/comment/86837909
type: Question
has comment: http://stackoverflow.com/comment/86838012
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86837925
has comment: http://stackoverflow.com/comment/86837865

http://stackoverflow.com/a/49775665
score: 4
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49775621
type: AcceptedAnswer
has body: Use list.append Ex: matrix=[] if my conidtion is filled: matrix.append([val1, val2, val3]) print matrix
answers question: http://stackoverflow.com/q/49775621
type: Answer

http://stackoverflow.com/a/49867803
has body: If your project is under D:\Dropbox\Git\Python\Django_projects and env_mysite is the only virtual environment, then open the Django_projects folder in VS Code and the Python extension will simply discover your virtual environment. If your code lives elsewhere then you will want to set "python.pythonPath": "D:\\Dropbox\\Git\\Python\\Django_projects\\Scripts\\python.exe".
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49825728
has comment: http://stackoverflow.com/comment/86935116
answers question: http://stackoverflow.com/q/49825728
type: Answer
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/49830710
answers question: http://stackoverflow.com/q/49830532
upvote count: 1
has comment: http://stackoverflow.com/comment/86676948
has body: You could iterate over columns, plot and show like this: from matplotlib import pyplot as plt for country in df.columns: # Iterate over countries dfcountry.unstack().plot(); # Unstack deaths and rates, plot plt.show(); # Switch to new plot Note the use of pyplot.show. Edit To plot separately deaths and rates, you can use subplot: for country in df.columns: # Iterate over countries country_df = dfcountry.unstack().plot(); # Unstack deaths and rates subplot(2, 1, 1); plot(country_df'Deaths'); subplot(2, 1, 2) plot(country_df'Rates'); plt.show(); # Switch to new plot
has comment: http://stackoverflow.com/comment/86676931
has comment: http://stackoverflow.com/comment/86677327
type: Answer
has comment: http://stackoverflow.com/comment/86676897
has comment: http://stackoverflow.com/comment/86677529
has comment: http://stackoverflow.com/comment/86677454
has comment: http://stackoverflow.com/comment/86677575
score: 1
has comment: http://stackoverflow.com/comment/86677474
downvote count: 0

http://stackoverflow.com/comment/86680973
type: Comment
comment on: http://stackoverflow.com/a/49832818
has text: what if i need to run it in loop? I am rearanging input every epoch
score: 0
type: AnswerComment

http://stackoverflow.com/q/49837857
has answer: http://stackoverflow.com/a/49931951
has title: Tensorflow MNIST with TFRecord and Dataset low accuracy
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49837974
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/86709736
has comment: http://stackoverflow.com/comment/86709084
tagged with: python
has answer: http://stackoverflow.com/a/49862023
accepted answer: http://stackoverflow.com/a/49931951
has body: I converted the MNIST dataset using the script here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/how_tos/reading_data/convert_to_records.py Below is the code that I use to read the TFRecord, build the model, and train. import tensorflow as tf BATCH_SIZE = 32 epoch = 20 n_hidden_1 = 256 # 1st layer number of neurons n_hidden_2 = 256 # 2nd layer number of neurons num_input = 784 # MNIST data input (img shape: 28*28) num_classes = 10 # MNIST total classes (0-9 digits) def parse_func(serialized_data): keys_to_features = {'image_raw': tf.FixedLenFeature([],tf.string), 'label': tf.FixedLenFeature([], tf.int64)} parsed_features = tf.parse_single_example(serialized_data, keys_to_features) prices = tf.decode_raw(parsed_features['image_raw'],tf.float32) label = tf.cast(parsed_features['label'], tf.int32) return prices,tf.one_hot(label - 1, 10) def input_fn(filenames): dataset = tf.data.TFRecordDataset(filenames=filenames) dataset = dataset.map(parse_func,num_parallel_calls=8) dataset = dataset.batch(BATCH_SIZE).prefetch(50) # dataset = dataset.shuffle(2000) return dataset.make_initializable_iterator() weights = { 'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, num_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_hidden_2])), 'out': tf.Variable(tf.random_normal([num_classes])) } # Create model def neural_net(x): # Hidden fully connected layer with 256 neurons layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) # Hidden fully connected layer with 256 neurons layer_1 = tf.nn.relu(layer_1) layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) layer_2 = tf.nn.relu(layer_2) # Output fully connected layer with a neuron for each class out_layer = tf.matmul(layer_2, weights['out']) + biases['out'] return out_layer def inference(input): input = tf.res…
possible better answer: http://stackoverflow.com/a/49837974
type: AnsweredQuestion

http://stackoverflow.com/comment/86644143
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49814927
type: Comment
has text: You do it explicitly with rs.fit(x_train, y_train). RandomSearchCV itself just choses the best parameters with CV.

http://stackoverflow.com/comment/86734490
comment on: http://stackoverflow.com/a/49856409
score: 0
type: Comment
type: AnswerComment
has text: Agree, it looks consistent. Can you further output the distribution of `trainY` and `testY`

http://stackoverflow.com/comment/86676910
type: AnswerComment
comment on: http://stackoverflow.com/a/49826415
score: 0
has text: @mypetion basically it creates the instances for him as he needs. btw, __init__ isn't mandatory to define the class in python
type: Comment

http://stackoverflow.com/comment/99429135
comment on: http://stackoverflow.com/a/49892796
type: AnswerComment
score: 0
type: Comment
has text: What is the difference between "\s+|-" and "\W+"

http://stackoverflow.com/comment/86843277
comment on: http://stackoverflow.com/q/49913887
score: 3
type: Comment
type: QuestionComment
has text: Mentioning what have you tried could help.

http://stackoverflow.com/comment/86752780
type: Comment
comment on: http://stackoverflow.com/q/49868611
has text: Yes, please share your attempt. And format your code, please.
type: QuestionComment
score: 5

http://stackoverflow.com/comment/86709352
has text: @Benjin is right, i would like to send a message when i click OK on a GUI, not from discord.
type: Comment
comment on: http://stackoverflow.com/a/49837064
type: AnswerComment
score: 1

http://stackoverflow.com/comment/86606062
comment on: http://stackoverflow.com/a/49795849
type: Comment
score: 0
type: AnswerComment
has text: Do not forgot to accept your answer in a few days if no one posts anything better.

http://stackoverflow.com/q/49796254
downvote count: 0
has answer: http://stackoverflow.com/a/68604768
accepted answer: http://stackoverflow.com/a/49797554
favorite count: 0
has body: I am running this code in Python: es = Elasticsearch([{'host': 'localhost', 'port': 9200}]).ping() print (es) if es: r = requests.get('http://localhost:9200') es.indices.delete(index='test_twitter', ignore=[400, 404]) connected = True print('Connected to ES..') else: print('Not connected to ES...') When Elasticsearch is running, there is no problem with ping. The problem is when ES is not running, ping() is returning FALSE after a Traceback error is printed as below: HEAD http://localhost:9200/ [status:N/A request:2.007s] Traceback (most recent call last): ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it During handling of the above exception, another exception occurred: Traceback (most recent call last): urllib3.exceptions.NewConnectionError: &lt;urllib3.connection.HTTPConnection object at 0x000001E2ECBD45F8&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it HEAD http://localhost:9200/ [status:N/A request:2.003s] Traceback (most recent call last): ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it During handling of the above exception, another exception occurred: Traceback (most recent call last): urllib3.exceptions.NewConnectionError: &lt;urllib3.connection.HTTPConnection object at 0x000001E2ECBD44E0&gt;: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it HEAD http://localhost:9200/ [status:N/A request:2.016s] Traceback (most recent call last): ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it During handling of the above exception, another exception occurred: Traceback (most recent call last): urllib3.exceptions.NewConnectionError: &lt;urllib3.connection.HTTPConnection object at 0x000001E2ECBD4668&gt;: Faile…
possible better answer: http://stackoverflow.com/a/49797801
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49797554
has answer: http://stackoverflow.com/a/49797801
tagged with: elasticsearch
tagged with: python
score: 4
answer count: 4
has answer: http://stackoverflow.com/a/75765930
has title: Test elasticsearch connection in Python
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/86608605

http://stackoverflow.com/comment/86622022
comment on: http://stackoverflow.com/q/49803562
score: 1
type: Comment
has text: Hist returns the counts and the bins. Maybe you can use that to filter? `n, bins, patches = plt.hist(points, bins=100)`
type: QuestionComment

http://stackoverflow.com/a/49915663
type: Answer
has body: You may use re.sub(r'(?&lt;! ) (?! )', '', content) Or, to handle any whitespace: re.sub(r'(?&lt;!\s)\s(?!\s)', '', content) See the regex demo. To match a single occurrence not enclosed with the same chars you need a lookbehind/lookahead based approach like above. The (?&lt;! ) makes sure there is no space immediately to the left of the current location, and (?! ) makes sure there is no space immediately to the right of the current location.
score: 3
accepted answer of: http://stackoverflow.com/q/49915501
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49915501
downvote count: 0

http://stackoverflow.com/comment/86667317
comment on: http://stackoverflow.com/a/49823979
type: Comment
type: AnswerComment
has text: its just for getting myself better in this topic. I want to understand it.
score: 0

http://stackoverflow.com/q/49853578
has comment: http://stackoverflow.com/comment/86729050
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49862767
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86741912
tagged with: python
has body: I wish to build a sparse real matrix using the intermediate scipy.sparse.dok_matrix storage format, then convert the matrix into the scipy.sparse.csc_matrix storage format and perform computations with the resulting matrix. However, the size of the intermediate matrices greatly exceeds my estimates and available memory. My environment $ python3 -V Python 3.4.2 $ pip freeze | grep -E 'scipy|numpy' numpy==1.14.2 scipy==1.0.1 Using numpy When I build a 20,000 × 20,000 numpy array of 16bit integers as follows, I would estimate the size would be 20000 ** 2 * 16 / 8 / 2 ** 20 ≈ 763M. The process has a Resident Set Size (RSS) of 815M as reported by the htop unix tool, which matches my estimate. import numpy as np n = 20000 M = np.ones((n, n), dtype=np.uint16) Using dict When I build a 20,000 × 20,000 scipy.sparse.dok_matrix using 16bit integers as keys and values as follows, I would estimate the size would be 20000 ** 2 * (16 * 3) / 8 / 2 ** 30 ≈ 2.24G plus some minor overhead of the hash table. However, the process has a RSS of 66.4G, which shows that I made a grave error in my estimate. import numpy as np n = 20000 M = dict() for i in range(n): i = np.uint16(i) for j in range(n): j = np.uint16(j) M[(i, j)] = np.uint16(1) Using scipy.sparse.dok_matrix When I build a 20,000 × 20,000 scipy.sparse.dok_matrix using 16bit integers as keys and values as follows, I would estimate the size would be again 20000 ** 2 * (16 * 3) / 8 / 2 ** 30 ≈ 2.24G plus some minor overhead of the hash table. However, the process has a RSS of 81.3G, which is even farther from my estimate than the dict example. from scipy.sparse import dok_matrix import numpy as np n = 20000 M = dok_matrix((n, n), dtype=np.uint16) for i in range(n): i = np.uint16(i) for j in range(n): j = np.uint16(j) M[i, j] = 1
tagged with: sparse-matrix
has comment: http://stackoverflow.com/comment/86725304
has comment: http://stackoverflow.com/comment/86741729
score: 0
has title: How to reduce the storage size of scipy.sparse.dok_matrix
answer count: 1
upvote count: 1
tagged with: scipy

http://stackoverflow.com/q/49907613
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49907848
has body: Using Python 2 I have a list of list list_of_list = [[a5, abc, xyz], [a1, abc, def],[a2, 4, 2, 3], [a3, 1, 2]] I have to sort the list so all all the items that has numbers in the 2nd to later position comes after the items that has letter in those position. The output should be sorted_list = [[a1, abc, def], [a5, abc, xyz], [a3, 1, 2], [a2, 4, 2, 3]] How do I do that? Using below code doesn't do it exactly as the sorting is not only based on the 2nd item in the inner list. from operator import itemgetter sorted(list_of_list, key=itemgetter(1)) Any suggestion?
upvote count: 0
has title: python - sort a list of list based on items from index 1 to the rest
has comment: http://stackoverflow.com/comment/86831223
downvote count: 1
answer count: 1

http://stackoverflow.com/a/49823811
answers question: http://stackoverflow.com/q/49823714
upvote count: 1
has body: For Python2.7 you can use map with None instead of zip, which will give you the longest zip. &gt;&gt;&gt;map(None, EmployeeID_List, EmployeeFirstName_List, managerID_List, managerFirstName_List) [(111, 'a', 888, 'f'), (222, 'b', 777, 'g'), (333, 'c', 666, 'h'), (444, 'd', None, None), (555, 'e', None, None)] and then convert to a dictionary using dict comprehension. result = { tup[0]:tup[1:] for tup in map(None, EmployeeID_List, EmployeeFirstName_List, managerID_List, managerFirstName_List) } Result: &gt;&gt;&gt; result {555: ('e', None, None), 444: ('d', None, None), 333: ('c', 666, 'h'), 222: ('b', 777, 'g'), 111: ('a', 888, 'f')} Note: a result is a dictionary to a tuple. If you want list just replace tup[1:] with list(tup[1:]).
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/49911255
has title: Cannot findword in each line python
answer count: 1
tagged with: python
type: AnsweredQuestion
score: 0
has body: My text file is something like this. RT @Vevo The @5SoS world is turned upside down in Want You Back the first release in 2 years by the Aussie poppunk band RT @Jeff__Benjamin Congratulations to @Stray_Kids for making their debut on @Billboard's Social 50 chart this week at No 45 Very promisi RT @Vevo The @5SoS world is turned upside down in Want You Back the first release in 2 years by the Aussie poppunk band RT @thesheetztweetz Fun fact @relativityspace CEO Tim Ellis shared The song is by @bassnectar and when he saw this video he told Relat RT @Jeff__Benjamin Congratulations to @Stray_Kids for making their debut on @Billboard's Social 50 chart this week at No 45 Very promisi RT @fringeflowers What a Beautiful Way to Express Your Spirituality with this #SterlingSilver Fancy Vented Band with #Sanskrit The Langua My code file is like below. import re wordlist = ["soundigest","vile","paris" ,"carlyaquilino","chrispolanco13","bimbo's","mcr","jack","lauren_hoggs","siriusxm","force","7th","muz4now","christ","orchestra","100","rampb","gla"] data = "" counter=0 with open("musicData.txt","w") as fout: print "hi" with open("temp.txt") as fin: for line in fin: for term in line.split(): term = term.lower() term= re.sub('[\n]+', ' ', term) # Remove not alphanumeric symbols white spaces term = re.sub(r'[^\w]', ' ', term) # Replace #word with word term = re.sub(r'#([^\s]+)', r'\1', term) # Remove :( or :) term = term.replace(':)', '') term = term.replace(':(', '') # trim term = term.strip('\'"') if term in wordlist: data = data + term + "," print data if data !="": fout.write(data) #print "data to write :", data fout.write("\n") data ="" My goal is, I want to find each line array which has the word from the wordlist. so suppose for first line it will have two words from wordlist then it will print the array in new file like [vile, paris]. I'm not able to do with the current code
accepted answer: http://stackoverflow.com/a/49911583
has answer: http://stackoverflow.com/a/49911583
type: Question

web-scraping
tags question: http://stackoverflow.com/q/49772590
tags question: http://stackoverflow.com/q/49909852
tags question: http://stackoverflow.com/q/49853247
tags question: http://stackoverflow.com/q/49890130
tags question: http://stackoverflow.com/q/49908284
tags question: http://stackoverflow.com/q/49818249
tags question: http://stackoverflow.com/q/49902433
tags question: http://stackoverflow.com/q/49775502
tags question: http://stackoverflow.com/q/49860379
tags question: http://stackoverflow.com/q/49891759
tags question: http://stackoverflow.com/q/49809777
tags question: http://stackoverflow.com/q/49899506
tag name: web-scraping
tags question: http://stackoverflow.com/q/49900644
tags question: http://stackoverflow.com/q/49836555
tags question: http://stackoverflow.com/q/49907917
tags question: http://stackoverflow.com/q/49778415
tags question: http://stackoverflow.com/q/49850523
tags question: http://stackoverflow.com/q/49789877
tags question: http://stackoverflow.com/q/49869971
tags question: http://stackoverflow.com/q/49844650
tags question: http://stackoverflow.com/q/49907823
tags question: http://stackoverflow.com/q/49891688
tags question: http://stackoverflow.com/q/49904532
tags question: http://stackoverflow.com/q/49804906
tags question: http://stackoverflow.com/q/49828707
tags question: http://stackoverflow.com/q/49908884
type: Tag
tags question: http://stackoverflow.com/q/49888300
tags question: http://stackoverflow.com/q/49806786
tags question: http://stackoverflow.com/q/49766150
tags question: http://stackoverflow.com/q/49805467
tags question: http://stackoverflow.com/q/49910982
tags question: http://stackoverflow.com/q/49857296
tags question: http://stackoverflow.com/q/49793196
tags question: http://stackoverflow.com/q/49799160
tags question: http://stackoverflow.com/q/49758944
tags question: http://stackoverflow.com/q/49792061
tags question: http://stackoverflow.com/q/49797957
tags question: http://stackoverflow.com/q/49782514
tags question: http://stackoverflow.com/q/49916452
tags question: http://stackoverflow.com/q/49908158
tags question: http://stackoverflow.com/q/49763597
tags question: http://stackoverflow.com/q/49895956
tags question: http://stackoverflow.com/q/49830115
tags question: http://stackoverflow.com/q/49794946
tags question: http://stackoverflow.com/q/49825610
tags question: http://stackoverflow.com/q/49897413
tags question: http://stackoverflow.com/q/49806884
tags question: http://stackoverflow.com/q/49765898
tags question: http://stackoverflow.com/q/49770315
tags question: http://stackoverflow.com/q/49768214
tags question: http://stackoverflow.com/q/49864056
tags question: http://stackoverflow.com/q/49786893
tags question: http://stackoverflow.com/q/49831540
tags question: http://stackoverflow.com/q/49844084
tags question: http://stackoverflow.com/q/49861147
tags question: http://stackoverflow.com/q/49847901
tags question: http://stackoverflow.com/q/49881728
tags question: http://stackoverflow.com/q/49786254
tags question: http://stackoverflow.com/q/49848175
tags question: http://stackoverflow.com/q/49854807
tags question: http://stackoverflow.com/q/49868937

http://stackoverflow.com/comment/86841461
type: Comment
comment on: http://stackoverflow.com/a/49912765
type: AnswerComment
has text: People want to see that you have put effort yourself before posting the question. Hope it makes sense. See you around :)
score: 0

http://stackoverflow.com/a/49837097
answers question: http://stackoverflow.com/q/49836891
has body: There's no need to use bindings. You can associate a StringVar with the widget, and put a trace on the StringVar. The trace will call your function whenever the value changes, no matter if it changes from the keyboard or the mouse or anything else. Here's your code, modified to use a variable with a trace: from tkinter import * root = Tk() def callback(*args): result = searchbox.get() print(result) #do stuff with result here var = StringVar() searchbox = Entry(root, textvariable=var) searchbox.pack() var.trace("w", callback) root.mainloop() For information about the arguments passed to the callback see What are the arguments to Tkinter variable trace method callbacks? For a better understanding of why your bindings seem to always be one character behind, see the accepted answer to Basic query regarding bindtags in tkinter
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49836891
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/86698687
comment on: http://stackoverflow.com/a/49840640
type: Comment
has text: I still get an error saying: driver.find_element_by_xpath('//a[contains(text(), "Black")' | '//a[contains(text(), "MLK")]').click() TypeError: unsupported operand type(s) for |: 'str' and 'str'
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86706874
has text: Yes, mutate(1, 2) is probably the cause since it makes Python exit with code -1073740940. My guess is that by mutating an integer, we may have mutated the exit code
type: Comment
comment on: http://stackoverflow.com/a/49845506
type: AnswerComment
score: 1

http://stackoverflow.com/comment/86752202
comment on: http://stackoverflow.com/a/49868308
type: AnswerComment
score: 2
has text: There's a small error in your output. You get: ['line1\tline1\tline1', 'line2\tline2\tline2', 'line3\tline3\tline3', '\t\t\t\tline4']. There is too much tabs in the last one. fillvalue='' should fix it.
type: Comment

http://stackoverflow.com/comment/86813049
comment on: http://stackoverflow.com/q/49894823
score: 0
type: Comment
has text: yes it works with Selenium. Though `/deep/` is supported by Chrome only. Try `driver.find_element_by_css_selector("* /deep/ #details-button")`. If you want all the data from the extension page: `driver.execute_async_script("chrome.management.getAll(arguments[0])")`.
type: QuestionComment

http://stackoverflow.com/comment/86834299
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49905909
type: QuestionComment
has text: give cv::distanceTransform a try

http://stackoverflow.com/q/49863164
tagged with: api
has body: I am working on a bulk url shortener which uses the google shortener api. Since it has a limit on how much links you can create, it will create an error at some point. If a Error is detected it should go back and to everything inside the for loop again, until it does work again. The problem is that when it detects an ERROR it just runs onward, which causes skipping of links which should be shorted. I marked the desired outcome with comments. Only the if name == 'main': part of the code is important but I provided my whole code to give it a context. #!/usr/bin/python from sys import argv import httplib2 import simplejson as json inputfile = argv[1] outputfile = argv[2] API_KEY = "KEY" def shurl(longUrl): try: API_KEY except NameError: apiUrl = 'https://www.googleapis.com/urlshortener/v1/url' else: apiUrl = 'https://www.googleapis.com/urlshortener/v1/url?key=%s' % API_KEY headers = {"Content-type": "application/json"} data = {"longUrl": longUrl} h = httplib2.Http('.cache') try: headers, response = h.request(apiUrl, "POST", json.dumps(data), headers) short_url = json.loads(response)['id'] errorcode = 0 except Exception, e: errorcode = 1 return (short_url, errorcode) if __name__ == '__main__': infile = open(inputfile, "r") outfile = open(outputfile, "a+") with infile as f: for line in f: # Go back to here longUrl = line outputS = shurl(longUrl) shorturl = outputS[0] errorcode = outputS[1] if errorcode == 0: print(shorturl) outfile.write(shorturl + "\n") else: print("ERROR, trying again.") # Go back outfile.close()
has comment: http://stackoverflow.com/comment/86741536
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49863300
type: UnansweredQuestion
has title: Repeat For Loop if condition is not met
tagged with: python
has answer: http://stackoverflow.com/a/49863581
score: 0

http://stackoverflow.com/q/49785225
tagged with: python
has body: Someone please tell me there is a cleaner way to write this!? I want to remove all instances of 'Features &amp; Benefits'. There must be a cleaner way to do this for strings in a list. lov_headers = [x.find('displayname').text for x in soup.find_all('attributedefinition')] if 'Part number' in lov_headers: lov_headers.remove('Part number') if 'Product Features' in lov_headers: lov_headers.remove('Product Features') if 'Packaging' in lov_headers: lov_headers.remove('Packaging') if 'Features &amp; Benefits' in lov_headers: lov_headers.remove('Features &amp; Benefits') if 'Features &amp; Benefits' in lov_headers: lov_headers.remove('Features &amp; Benefits') if 'Features &amp; Benefits' in lov_headers: lov_headers.remove('Features &amp; Benefits') if 'Features &amp; Benefits' in lov_headers: lov_headers.remove('Features &amp; Benefits') if 'Features &amp; Benefits' in lov_headers: lov_headers.remove('Features &amp; Benefits') if 'Features &amp; Benefits' in lov_headers: lov_headers.remove('Features &amp; Benefits') if 'Features &amp; Benefits' in lov_headers: lov_headers.remove('Features &amp; Benefits') if 'Features &amp; Benefits' in lov_headers: lov_headers.remove('Features &amp; Benefits') if 'Features &amp; Benefits' in lov_headers: lov_headers.remove('Features &amp; Benefits') if 'Features &amp; Benefits' in lov_headers: lov_headers.remove('Features &amp; Benefits') if 'Features &amp; Benefits' in lov_headers: lov_headers.remove('Features &amp; Benefits')
has title: Remove all occurrences of strings from list
has answer: http://stackoverflow.com/a/49785264
score: -1
upvote count: 0
answer count: 2
linked to: http://stackoverflow.com/q/1157106
has comment: http://stackoverflow.com/comment/86585905
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86585912
has answer: http://stackoverflow.com/a/49785263
duplicate of: http://stackoverflow.com/q/1157106
type: Question
type: UnansweredQuestion

function
tags question: http://stackoverflow.com/q/49839332
tags question: http://stackoverflow.com/q/49840934
tags question: http://stackoverflow.com/q/49889383
tags question: http://stackoverflow.com/q/49820999
tags question: http://stackoverflow.com/q/49794054
tags question: http://stackoverflow.com/q/49878566
tags question: http://stackoverflow.com/q/49844397
tags question: http://stackoverflow.com/q/49900087
tags question: http://stackoverflow.com/q/49880980
tags question: http://stackoverflow.com/q/49891620
type: Tag
tag name: function
tags question: http://stackoverflow.com/q/49774630
tags question: http://stackoverflow.com/q/49902306
tags question: http://stackoverflow.com/q/49909039
tags question: http://stackoverflow.com/q/49879758
tags question: http://stackoverflow.com/q/49856024
tags question: http://stackoverflow.com/q/49895423
tags question: http://stackoverflow.com/q/49809264
tags question: http://stackoverflow.com/q/49837871
tags question: http://stackoverflow.com/q/49836243
tags question: http://stackoverflow.com/q/49901079
tags question: http://stackoverflow.com/q/49888276
tags question: http://stackoverflow.com/q/49882807
tags question: http://stackoverflow.com/q/49823750
tags question: http://stackoverflow.com/q/49905843
tags question: http://stackoverflow.com/q/49759618
tags question: http://stackoverflow.com/q/49792746
tags question: http://stackoverflow.com/q/49837373
tags question: http://stackoverflow.com/q/49760649
tags question: http://stackoverflow.com/q/49835213
tags question: http://stackoverflow.com/q/49821424
tags question: http://stackoverflow.com/q/49874447
tags question: http://stackoverflow.com/q/49764718
tags question: http://stackoverflow.com/q/49889593
tags question: http://stackoverflow.com/q/49775610
tags question: http://stackoverflow.com/q/49905053
tags question: http://stackoverflow.com/q/49828902
tags question: http://stackoverflow.com/q/49859183
tags question: http://stackoverflow.com/q/49861600
tags question: http://stackoverflow.com/q/49777905
tags question: http://stackoverflow.com/q/49776109
tags question: http://stackoverflow.com/q/49916401
tags question: http://stackoverflow.com/q/49783331

http://stackoverflow.com/comment/86958484
has text: your output looks like exactly what I'm after... but for some reason I can't get your code to run (problem is likely between my keyboard and my chair). I was able to get some output by adding print (p) at the end, but it's not the correct result: [[(3,), (1, 2)], [(3, 5), (1, 2, 5), (1, 3, 4)]]
comment on: http://stackoverflow.com/a/49911979
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/49823263
has answer: http://stackoverflow.com/a/49823873
possible better answer: http://stackoverflow.com/a/49823583
score: 2
type: AnsweredQuestion
tagged with: matplotlib
downvote count: 0
has answer: http://stackoverflow.com/a/49823583
has body: I have a financial dataset that contains measures for some markets during some time periods. market date metric1 metric2 metric3 ASX 2000 ASX 2001 ASX 2002 ASX 2003 TSX 2000 TSX 2001 TSX 2002 TSX 2003 TSX 2004 NYSE 2000 NYSE 2001 NYSE 2002 NYSE 2003 NYSE 2004 Metric1 to metric3 contains numerical values. I would like to draw some line or bar graphs that group by market and between some date values, say 2000 and 2002 in this example. my date variable could be yearmonth (e.g. 200101, 200102). Is there a way to tell python that it is yearmonth so there is no gap between 200112 and 200201? I am using matplotlib and pandas.
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
answer count: 2
tagged with: dataframe
tagged with: python
has title: drawing graphs from a dataframe by group and between certain values
accepted answer: http://stackoverflow.com/a/49823873
has comment: http://stackoverflow.com/comment/86662885
tagged with: pandas

http://stackoverflow.com/a/54672690
has comment: http://stackoverflow.com/comment/113602108
has comment: http://stackoverflow.com/comment/100131699
has comment: http://stackoverflow.com/comment/102971600
has comment: http://stackoverflow.com/comment/105805094
has comment: http://stackoverflow.com/comment/132228300
has comment: http://stackoverflow.com/comment/113580555
type: Answer
answers question: http://stackoverflow.com/q/49772151
has comment: http://stackoverflow.com/comment/100127643
has comment: http://stackoverflow.com/comment/114169724
upvote count: 106
accepted answer of: http://stackoverflow.com/q/49772151
has body: quick and dirty but it works: import boto3 import os def downloadDirectoryFroms3(bucketName, remoteDirectoryName): s3_resource = boto3.resource('s3') bucket = s3_resource.Bucket(bucketName) for obj in bucket.objects.filter(Prefix = remoteDirectoryName): if not os.path.exists(os.path.dirname(obj.key)): os.makedirs(os.path.dirname(obj.key)) bucket.download_file(obj.key, obj.key) # save to same path Assuming you want to download the directory foo/bar from s3 then the for-loop will iterate all the files whose path starts with the Prefix=foo/bar.
type: AcceptedAnswer
downvote count: 2
score: 104

http://stackoverflow.com/a/69483584
answers question: http://stackoverflow.com/q/49785108
has comment: http://stackoverflow.com/comment/126548306
upvote count: 14
has body: A simple way: from pyspark.sql import SparkSession import pyspark.sql.functions as f spark = SparkSession.builder.getOrCreate() df = spark.range(10) df.withColumn("uuid", f.expr("uuid()")).show(truncate=False)
has comment: http://stackoverflow.com/comment/126548996
has comment: http://stackoverflow.com/comment/122985129
downvote count: 0
type: Answer
score: 14

http://stackoverflow.com/a/49761160
has comment: http://stackoverflow.com/comment/86542484
answers question: http://stackoverflow.com/q/49761056
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49761056
type: Answer
has body: If you want to pass a command with arguments to Popen(), you have to pass it as a list, like so: subprocess.Popen(['/bin/ls', '-lat']) If you just pass a single string as in your example, it assumes the entire thing is the command name, and obviously there is no command literally named pwdx $(pgrep -U $USER -f SimpleHTTPServer).
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86752644
type: Comment
comment on: http://stackoverflow.com/a/49868454
type: AnswerComment
score: 0
has text: 1. `alias python3='python3 -q'` 2. `python3`

http://stackoverflow.com/q/49818392
tagged with: encryption
possible better answer: http://stackoverflow.com/a/49818681
has answer: http://stackoverflow.com/a/49818681
has comment: http://stackoverflow.com/comment/86655915
favorite count: 0
has comment: http://stackoverflow.com/comment/86652791
type: Question
accepted answer: http://stackoverflow.com/a/49823973
tagged with: math
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/49823973
tagged with: cryptography
has comment: http://stackoverflow.com/comment/86651699
has comment: http://stackoverflow.com/comment/86651822
tagged with: modulus
has comment: http://stackoverflow.com/comment/86652621
has comment: http://stackoverflow.com/comment/86651330
has title: How to find reverse of pow(a,b,c) in python?
type: AnsweredQuestion
answer count: 2
score: 3
has body: pow(a,b,c) operator in python returns (a**b)%c . If I have values of b, c, and the result of this operation (res=pow(a,b,c)), how can I find the value of a?
downvote count: 2

http://stackoverflow.com/a/52147221
has body: You probably need some kind of visitor function to search recursively. The following snippet works as a self-contained example for me: import xml.etree.ElementTree as ET data = """ <element name="value1" /> <element name="value2" /> <element name="value3" /> <element maxOccurs="1" minOccurs="1" name="Attribute1" /> <element maxOccurs="1" minOccurs="0" name="Attribute2" /> <element maxOccurs="1" minOccurs="0" name="Attribute3" /> <c><d><e><f> <element maxOccurs="1" minOccurs="1" name="Attribute4" /> <element maxOccurs="1" minOccurs="0" name="Attribute5" /> <element maxOccurs="1" minOccurs="0" name="Attribute6" /> </f></e></d></c> """ root = ET.fromstring(data) attributes = [] def visit(node): if node.tag == "element": name = node.attrib.get("name") if name is not None: attributes.append(name) for child in node: visit(child) visit(root) print(attributes)
score: 0
answers question: http://stackoverflow.com/q/49783071
type: Answer

http://stackoverflow.com/comment/86643525
type: Comment
comment on: http://stackoverflow.com/q/49801029
type: QuestionComment
has text: It's not necessary. I'm new to programing, i didnt realize this could be a problem, now i can see it, thank you for you question.
score: 0

http://stackoverflow.com/comment/86683160
has text: I wonder whether this will be very useful. A few (hundred) iterations on a complex task that can't be fully 'cythonized' (no Python calls) won't show a big speed increase. I'd suggest programming the simplest case (e.g. a bunch of identical arrays of known size), and see if it helps enough to do more work on it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49833200
score: 0

http://stackoverflow.com/q/49790194
has comment: http://stackoverflow.com/comment/86600016
has comment: http://stackoverflow.com/comment/86606559
tagged with: sockets
has body: I received data via TCP socket, it should be "12345678901" as value. I tried also to convert it by int.from_bytes in byteorder ='big' and 'littel' ,struct.unpack... However it didn't work well. Actual value I got is b'\xd2\x04.\x16\xc5"'( &lt;&lt; data == conn.recv(2048)) Which kind of way should I use for converting it to integer? EDIT: on Server side(really typical) TCP_IP = '192.168.3.50' TCP_PORT = 8000 BUFFER_SIZE = 2048 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr = s.accept() print('Connection address:', addr) data_dummy = 0 while 1: data = conn.recv(BUFFER_SIZE) if not data: break if data_dummy != data or data_dummy == 0: print("received data:", data) print("converted(big)", int.from_bytes(data, byteorder='big')) print("converted(little)", int.from_bytes(data, byteorder='little')) on Client side(it is came from PLC) I'll put command line. NEXT&gt;&gt; 8 received data: b'\xd2\x04\x00\x00\x00\x00' converted(big) 230914621702144 converted(little) 1234 It works, if is only 1234. NEXT&gt;&gt; 9 received data: b'\xd2\x04\x01\x00\x00\x00' converted(big) 230914638479360 converted(little) 66770 It doesn't work, in this case 12340001. NEXT&gt;&gt; 11 received data: b'\xd2\x044\x12\x00\x00' converted(big) 230915495297024 converted(little) 305398994 it doesn't work and structure itself is strange.
has comment: http://stackoverflow.com/comment/86595593
accepted answer: http://stackoverflow.com/a/49799195
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86597391
has title: Python Socket:Converting bytes object
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49799195
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86595306
has comment: http://stackoverflow.com/comment/86595821
has comment: http://stackoverflow.com/comment/86606188
tagged with: byte
has comment: http://stackoverflow.com/comment/86597012

http://stackoverflow.com/comment/86760117
score: 1
type: QuestionComment
type: Comment
has text: @ArturMüllerRomanov It seems that you do not know how to implement my solution, besides that, thanks to your question I have been able to solve some compatibility problems between PyQt4 and PyQt5, the solution for your case is as follows: https://gist.github.com/eyllanesc/c4c75c8b717fbb521b51567b0901b9ae/archive/a097a555a8854caeb1cef1da4f1b849391e08c44.zip
comment on: http://stackoverflow.com/q/49859670

http://stackoverflow.com/comment/86631249
type: AnswerComment
score: 0
type: Comment
has text: Tf and a number of it's dependencies require compilation of C, Fortran and Cython code prior to use. The packages from the "unofficial" binaries website are pre-compiled and are widely utilized by the Python community developing on windows.
comment on: http://stackoverflow.com/a/49787718

http://stackoverflow.com/q/49795683
tagged with: pandas
linked to: http://stackoverflow.com/q/17071871
accepted answer: http://stackoverflow.com/a/49796021
score: 1
has answer: http://stackoverflow.com/a/49796021
tagged with: python
possible better answer: http://stackoverflow.com/a/49796088
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49796088
has comment: http://stackoverflow.com/comment/86606313
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49796529
has title: if statement with condition in python
type: AnsweredQuestion
answer count: 3
has body: The idea is the user will be able to extract a certain row under a certain condition. The condition is to return the last 'Pass' encountered before fail. For example, the user inserts the value 5, the if statement should print out 3. As this is the last time he passed. if the user would insert 0, it would also return 3, as this is the last time he passed before he failed. So basically the idea is to return the last pass encountered before he failed. Another example on the same dataset, if the user passes 7, it would return 7. As this is the last 'pass' before he failed. --------------------------- #dataSet Index Result 0 Pass 1 Pass 2 Pass 3 Pass 4 Fail 5 Fail 6 Pass 7 Pass 8 Fail --------------------------- result = 'Result' if df.loc[index_value,result] == 'Pass': else:

http://stackoverflow.com/comment/86728102
type: Comment
comment on: http://stackoverflow.com/q/49856706
type: QuestionComment
has text: I have already mentioned in the question that communicate() is also not working.
score: 0

http://stackoverflow.com/q/49881907
accepted answer: http://stackoverflow.com/a/49893748
possible better answer: http://stackoverflow.com/a/76859842
has comment: http://stackoverflow.com/comment/86783418
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49893748
score: 0
has answer: http://stackoverflow.com/a/76859842
tagged with: opencv3.0
has comment: http://stackoverflow.com/comment/86779743
has comment: http://stackoverflow.com/comment/86780290
has comment: http://stackoverflow.com/comment/86780416
has comment: http://stackoverflow.com/comment/86779961
type: Question
tagged with: video-streaming
answer count: 2
has comment: http://stackoverflow.com/comment/86779928
has comment: http://stackoverflow.com/comment/86783094
has title: Python OpenCV stream video error in executable
tagged with: python
has body: In my python application I'm using OpenCV, among other things, to stream a Video from an IP camera: cap = cv2.VideoCapture("http://usr:psw@192.168.1.1/video.cgi") and everithing works fine. But i needed to obtain an executable, and so I used PyInstaller. In the resulting .exe the stream doesn't work anymore. Instead if I change the capture with this: # works with camera_num = 0 (pc's webcam) and = 1 (external USB webcam) cap = cv2.VideoCapture(camera_num) capturing from webcam of my pc, or with and external USB webcam, everything works. Any suggestions?

http://stackoverflow.com/a/49888303
upvote count: 2
answers question: http://stackoverflow.com/q/49888090
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49888090
type: Answer
has body: This seems like an uninformative exercise because there are many ways of writing the creation of a singleton tuple. For example: tuple(["I'm a tuple"]) tuple({"I'm a tuple"}) # ... etc. for other sequence types ("I'm a tuple",) # or even def single_value(): yield "I'm a tuple" tuple(value for value in single_value()) # or something ludicrous next(map(tuple, "I'm a tuple")) Or even a criminally insane idea like this: In [43]: class TuplePiper(object): ...: def __init__(self, value): ...: self.value = value ...: ...: def __rshift__(self, other): ...: return other([self.value]) ...: In [44]: TuplePiper("I'm a tuple") &gt;&gt; tuple Out[44]: ("I'm a tuple",) Unless the exercise comes with an identifying assumption or constraint that explains which from among these possibilities is supposed to satisfy the test, then it would seem to be just a matter of preference.
score: 2

http://stackoverflow.com/comment/86695266
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49839406
type: Comment
has text: Is it because it's immutable?

http://stackoverflow.com/a/49778753
has body: Use instead: \]([^A-Z]*) Online Demo Your regex \](.*)[^A-Za-z] matches first a closing bracket ] (that's OK) and then some number of anychar followed by one char that is non letter. Because .* is greedy, it takes as many chars, as possible. In your case it reaches end of the string and then backracks once to match ) with [^A-Za-z]
answers question: http://stackoverflow.com/q/49778697
score: 0
type: Answer

http://stackoverflow.com/comment/86568477
has text: Possible duplicate of [Python Access Data in Package Subdirectory](https://stackoverflow.com/questions/779495/python-access-data-in-package-subdirectory)
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49773125

http://stackoverflow.com/comment/125274458
comment on: http://stackoverflow.com/a/56696013
type: Comment
score: 0
type: AnswerComment
has text: Should be using the Python extension default interpreter configuration (using something like `pipenv`) https://code.visualstudio.com/docs/python/environments#_manually-specify-an-interpreter

http://stackoverflow.com/comment/86685073
type: Comment
comment on: http://stackoverflow.com/q/49834380
score: 0
type: QuestionComment
has text: @MatiasValdenegro I think you are right. Thank you very much! I will try to find how to build a symbolic tensor that is connected to the graph. Or can you give me some hints about how to it?

http://stackoverflow.com/q/49836084
has title: Wrong longitude calculation in pyorbital
tagged with: satellite
has comment: http://stackoverflow.com/comment/86688274
has comment: http://stackoverflow.com/comment/86688018
has comment: http://stackoverflow.com/comment/86688177
type: Question
accepted answer: http://stackoverflow.com/a/49836359
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49836359
downvote count: 0
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86688029
has comment: http://stackoverflow.com/comment/86687899
favorite count: 0
type: AnsweredQuestion
has body: While playing a bit with pyorbital I noticed that the function get_lonlatalt() does not seem to return a correct longitude value to me. So I have compared the returned Lon/Lat/Alt to other tracking software: The returned Altitude and Latitude are spot on but the Longitude seems to be off (using the below code example the function returns about 15deg less than what the real position of the ISS is right now). The below code prints the Lat/Lon/Alt of the ISS once per second to the console and can be used to compare the position to e.g. http://www.n2yo.com/?s=25544 Does anyone have any suggestions how to fix this/why this is happening ? P.S. Unfortunately stackoverflow doesnt allow me to create the Tag "pyorbital" before 1500 reputation.. from pyorbital.orbital import Orbital from datetime import datetime import time tle_object_name = "ISS (ZARYA)" sat = Orbital(tle_object_name) #Fetches TLE from the internet by itself while True: now = datetime.utcnow() lon, lat, alt = sat.get_lonlatalt(now) print "{} UTC at {}E, {}N, {}km".format(now, round(lon, 3), round(lat, 3), round(alt, 3)) time.sleep(1)
tagged with: orbital-mechanics

http://stackoverflow.com/comment/86833217
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49908385
score: 0
has text: I do not know why you come out this question. if any size is 2 , which row from foo, you want to select?

http://stackoverflow.com/q/49826305
has answer: http://stackoverflow.com/a/49826415
accepted answer: http://stackoverflow.com/a/49826415
tagged with: python
has comment: http://stackoverflow.com/comment/86668430
has title: How can I automate the creation of instances of a class?
upvote count: 2
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86668615
downvote count: 2
has body: So in python 3 I am having trouble creating multiple instances of a class automatically. I am trying to make monopoly and here is the code sample that is giving me problems. def numplayer(): numplayer = int(input('How many players would you like? (up to four)')) while numplayer &gt; 4 or numplayer &lt; 1: numplayer = int(input('How many players would you like? (up to four)')) for i in range(numplayer): PlayerMoney.append(1500) What I want to do is also add something that will create the number of players that numplayers equals to in the for i in range(numplayer) function. I have the player as a class but I don't want to manually create every single class for every player. If there is a solution to this, please do tell. Thanks! EDIT: So I think this might be bad wording in the title but I'm trying to create multiple instances of a single class (the player). Here is the code for the player class: class Player: def __init__(self, name, money, position): self.name = name self.money = money self.position = position def DiceRoll(self): x = random.randint(1, 6) y = random.randint(1, 6) sum = x + y return [sum, x, y] def getName(self): return sef.name def getMoney(self): return self.money def getPosition(self): return self.position
has comment: http://stackoverflow.com/comment/86668623
possible better answer: http://stackoverflow.com/a/49826466
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49826466
has comment: http://stackoverflow.com/comment/86668309
tagged with: oop
has comment: http://stackoverflow.com/comment/86668358

http://stackoverflow.com/q/49780018
has comment: http://stackoverflow.com/comment/86576159
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/86575434
has answer: http://stackoverflow.com/a/49780063
accepted answer: http://stackoverflow.com/a/49780259
possible better answer: http://stackoverflow.com/a/49780060
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86576080
has comment: http://stackoverflow.com/comment/86575985
upvote count: 0
tagged with: oop
has answer: http://stackoverflow.com/a/49780077
downvote count: 3
has body: I am a python newbie and I’m trying to write simple project using OOP way. The first function waits for user interface to enter the user first name. The second function waits for user interface to enter the user last name. THEN The third function prints the full name. But When I tried to initiate these functions, it gives me errors. Here is the code: class UserFullName: def __init__(self, FirstName, LastName, FullName): self.FirstName = FirstName self.LastName = LastName self.FullName = FullName def FirstName(self): FirstName = input("enter your first name:\n".title()) return FirstName def LastName(self): LastName = input("enter your last name:\n".title()) return LastName def FullName(self, FirstName, LastName): print('welcome', "{} {}".format(FirstName, LastName).title()) return UserFullName.FirstName() UserFullName.LastName() UserFullName.FullName() Here is the error: Traceback (most recent call last): File "E:/Tutorial/pan.py", line 20, in UserFullName.FirstName() TypeError: FirstName() missing 1 required positional argument: 'self'
has title: python class functions error
has comment: http://stackoverflow.com/comment/86575502
has answer: http://stackoverflow.com/a/49780060
has answer: http://stackoverflow.com/a/49780259
answer count: 4
has comment: http://stackoverflow.com/comment/86575738
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86575880
has comment: http://stackoverflow.com/comment/86576026
has comment: http://stackoverflow.com/comment/86576011

http://stackoverflow.com/q/49804287
tagged with: pandas
type: UnansweredQuestion
has title: Pandas - Looping over columns for assignment optimization
has comment: http://stackoverflow.com/comment/86624139
has body: I'm making a program that assigns volume to providers based on their rank. The data is like this: Origin Dest Provider Vol_A Vol_B Vol_C Capacity rank NYC AMS A 90 1300 2500 4000 1 NYC AMS B 150 600 1700 3000 2 NYC BRI A 105 700 100 2300 1 NYC BRI C 300 1300 200 2800 2 The goal is to assign all the volume to the #1 ranked provider until their Capacity is met. In the first example, NYC to AMS, Provider A will be assigned 240 units of Vol_A because 90+150 = 240. The desired output looks like this: Origin Dest Provider Vol_A Vol_B Vol_C Capacity rank assg_a assg_b assg_c NYC AMS A 90 1300 2500 4000 1 240 1900 1980 NYC AMS B 150 600 1700 3000 2 0 0 2220 NYC BRI A 105 700 100 2300 1 405 1895 0 NYC BRI C 300 1300 200 2800 2 0 105 300 In the NYC-AMS example, Provider A was not able to fill all of the Vol_C so some of it spilled over to Provider B. My code is as follows: def assign(): vol_sim = pd.DataFrame(columns=['Origin','Dest','Provier','rank','Vol_E','Vol_C','Vol_U','Capacity','assg_e','assg_c','assg_u']) for key,lane in inputs.groupby(['Origin','Dest']) for col,out in zip(['Vol_E','Vol_C','Vol_U'],['assg_e','assg_c','assg_u']): to_assg = lane[col].sum() assg = 0 remain = to_assg for idx,row in lane.iterrows(): if assg &gt;= to_assg: row[out] = 0 row_temp = pd.DataFrame(row'Origin','Dest','Provider','rank',col,'Capacity',out) row_temp2 = row_temp.T vol_sim = vol_sim.append(row_temp2) else: if row['Capacity'] &lt;= to_assg: row[out] = row['Capacity'] assg = assg + row[out] remain = remain - assg row_temp = pd.DataFrame(row'Origin','Dest','Provider','rank',col,'Capacity',out) row_temp2 = row_temp.T vol_sim = vol_sim.append(row_temp2) else: row[out] = remain assg = assg + row[out] remain = remain - assg row_temp = pd.DataFrame(row'Origin','Dest','Provider','rank',col,'Capacity',out) row_temp2 = row_temp.T vol_sim = vol_sim.append(row_temp2) return vol_sim The result I'm getting (shown below) seems to have duplicates for each iteration over the columns. I'd li…
type: Question
has comment: http://stackoverflow.com/comment/86625603
has comment: http://stackoverflow.com/comment/86625663
tagged with: python
has comment: http://stackoverflow.com/comment/86623406
score: 0
answer count: 0

http://stackoverflow.com/q/49862316
has answer: http://stackoverflow.com/a/49862627
tagged with: python
has body: When a user-defined type is called to create a new object, type_call is called. Its first parameter is PyObject *type. Then, type-&gt;tp_new is called to create the object. I'm reading Eli Bendersky's article (And following along CPyton's source code) where it is explained that in such case, calling tp_new invokes object_new. Here's how it works (Joe is a user-defined type; Italic is added): Since the type parameter passed to type_call in our case is Joe, and Joe does not define a custom __new__ method, then type-&gt;tp_new defers to the tp_new slot of the base type. The base type of Joe [...] is object. The object.tp_new slot is implemented in CPython by the object_new function in Objects/typeobject.c. So, if I understand this correctly, it follows that if type-&gt;tp_new references object_new, then the runtime type of type must be PyBaseObject_Type* (Because only PyBaseObject_Type.tp_new references object_new). My question: What are the steps - preceding the invocation of type_call - that makes type point to a PyBaseObject_Type variable?
has title: When a user-defined type is called, what causes tp_new to reference object_new?
type: AnsweredQuestion
score: 1
tagged with: types
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: language-implementation
accepted answer: http://stackoverflow.com/a/49862627
upvote count: 2
tagged with: cpython

http://stackoverflow.com/a/49875777
has comment: http://stackoverflow.com/comment/86767213
accepted answer of: http://stackoverflow.com/q/49875667
answers question: http://stackoverflow.com/q/49875667
type: Answer
has body: The columns look fine to me. You can use: df.drop_duplicates('thread_id').thread_length.plot.hist() drop_duplicates identifies duplicates by considering the thread_id column only, keeping the first occurrence (by default). I then take the thread_length column, which gives you a Series that you can plot with method hist to get a histogram.
has comment: http://stackoverflow.com/comment/86773729
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86588649
type: QuestionComment
comment on: http://stackoverflow.com/q/49786624
score: 0
has text: What format are you reading this in from?
type: Comment

average
tags question: http://stackoverflow.com/q/49844496
tags question: http://stackoverflow.com/q/49880210
tags question: http://stackoverflow.com/q/49843184
type: Tag
tag name: average

http://stackoverflow.com/q/49823091
tagged with: django
favorite count: 0
has answer: http://stackoverflow.com/a/49824673
has comment: http://stackoverflow.com/comment/86664118
has title: inserting data in two database at the same time
tagged with: python
type: Question
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86664675
downvote count: 0
type: UnansweredQuestion
has body: I have two Models in my application in Django The Change model is only for storing the change logs made in Model Ip My models.py class Change(models.Model): author = models.ForeignKey('auth.User', null=False, on_delete=models.CASCADE, default='auth.User') ip = models.ForeignKey('Ip', on_delete=models.CASCADE, default='') old_cluster = models.ForeignKey('Cluster', on_delete=models.CASCADE, default='') old_status = models.ForeignKey('Status', on_delete=models.CASCADE, default='') new_cluster = models.CharField(max_length=20) new_status =models.CharField(max_length=20) change_date = models.DateTimeField(default=timezone.now) class Ip(models.Model): author = models.ForeignKey('auth.User', null=False, on_delete=models.CASCADE, default='auth.User') number = models.CharField(max_length=20, unique=True, default='') status = models.ForeignKey('Status', on_delete=models.CASCADE, default='') cluster = models.ForeignKey('Cluster', on_delete=models.CASCADE, default='') created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.number class Meta: ordering = ('number',) my views.py def ip_edit(request, id): ip_edit = get_object_or_404(Ip, id=id) form = EditManagementForm(request.POST, instance=ip_edit) change_form = ChangeLogsForm() if request.method == "POST": if form.is_valid(): ip_edit = form.save(commit=False) ip_edit.save() change_form = ChangeLogsForm(request.POST) if change_form.is_valid(): ip_change = change_form.save(commit=False) ip_change.author = request.user ip_change.ip = request.number ip_change.save() return redirect('/app/management') else: form = EditManagementForm(instance=ip_edit) args = { 'form': form, } return render(request, 'app/ip_edit.html', args and my forms.py class EditManagementForm(forms.ModelForm): class Meta: model = Ip fields = ( 'number', 'status', 'cluster', ) widgets = { 'number': TextInput(attrs={'class': 'ls-form-text'}), } class ChangeLogsForm(forms.ModelForm): class Meta: model = Change fields = ( 'ip', 'old_cl…
answer count: 1

http://stackoverflow.com/a/49888880
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49853567
type: Answer
has body: EDIT: OK I just realized (I think) that you are asking a different question. To find out the indices of the original points in each tile, you will have to basically recreate what hexbin does itself: In [8]: from bokeh.util.hex import cartesian_to_axial In [8]: import pandas as pd In [9]: q, r = cartesian_to_axial(x, y, 0.5, "pointytop") In [10]: df = pd.DataFrame(dict(r=r, q=q)) In [11]: groups = df.groupby(['q', 'r']) In [12]: groups.groups Out[12]: {(-4, -3): Int64Index([272], dtype='int64'), (-4, 0): Int64Index([115], dtype='int64'), (-4, 3): Int64Index([358], dtype='int64'), (-4, 4): Int64Index([480], dtype='int64'), (-3, -1): Int64Index([323], dtype='int64'), (-3, 2): Int64Index([19, 229, 297], dtype='int64'), ... (11, -5): Int64Index([339], dtype='int64'), (12, -7): Int64Index([211], dtype='int64')} Here each key for each entry in the groups dict is the (q,r) axial hex coordinate of the tile, and the value is a list of the indices of the points that were in that tile. Old Answer That information is in the bins DataFrame that is returned: In [3]: bins.head() Out[3]: q r counts 0 -4 -3 1 1 -4 0 1 2 -4 3 1 3 -4 4 1 4 -3 -1 1 Here q and r are Axial Hex Grid Coordinates. If you want the Cartesian x and y coordinates of the hex tile centers, you can use the axial_to_cartesian function.
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49853567

http://stackoverflow.com/comment/86806244
has text: Can you provide a short snippet of both the input files and expected output of the same
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49895423
score: 2

http://stackoverflow.com/q/49774480
has answer: http://stackoverflow.com/a/49775109
has title: shifting dictionaries in nested dictionaries
has comment: http://stackoverflow.com/comment/86566778
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/107836276
downvote count: 0
has body: I have the following list of nested dictionaries and lists. I want to create a new parent (L0) category called 'food', and shift all the values in the fruit and vegs dictionaries one step down (so that 'L0': 'fruit' becomes 'L1': 'fruit', 'L1': 'banana' becomes 'L2': 'banana', etc). D = [{ "L0": "fruit", "L1_list": [ { "L1": "banana" }, { "L1": "apple", "L2_list": [ { "L2": "Green apple" }, { "L2": "Red apple" } ] }, { "L1": "kiwi" } ] }, { "L0": "vegs", "L1_list": [ { "L1": "potato" }, { "L1": "carrot" } ] }] The excepted output should look like this: Expected_output = [ { "L0": "food", "L1_list": [ { "L1": "fruit", "L2_list": [ { "L2": "banana" }, { "L2": "apple", "L3_list": [ { "L3": "Green apple" }, { "L3": "Redapple" } ] }, { "L2": "kiwi" } ] }, { "L1": "vegs", "L2_list": [ { "L2": "potato" }, { "L2": "carrot" } ] } ] } ] Now, because my dictionaries can vary in size and how deep they can go, I need a programmatic solution. So I thought I would create a recursive function that iterates util it reaches the end of the tree. As the function reaches the end of a particular branch, it would add 1 to the key (L0 --> L1, L1_list --> L2_list). Although the process does indeed shift everything one level down, I can't figure out how to rebuild the initial structure. In particular, I can't bring the children back into their respective list. Final_list = [] def digger(list_to_dig): import re for x in list_to_dig: for k,v in x.items(): if isinstance(v, list): print("keep digging") digger(v) elif isinstance(x, dict): new_D = {} new_k = "L" + str(int(re.sub("L", "", k)) + 1) new_D[new_k] = v temp = re.sub("L", "", k) new_child_list = "L" + str(int(re.sub("_list", "", temp)) + 2) + "_list" new_D[new_child_list] = "" Final_list.append(new_D) else: print("no dictionary avail") pass print("_________") print(Final_list) print("_________") test = digger(D) Any suggestions on how I should tackle this? Many thanks Following the suggestion of @running.t I have tried to use the dict.po…
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/16475384
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/60952400
upvote count: 5
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86564322

http://stackoverflow.com/comment/122985129
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/69483584
has text: This is actually faster than @PavithranRamachandran answer

http://stackoverflow.com/comment/86924888
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49787860
has text: @TarunLalwani: It's 9.0.1
score: 0

http://stackoverflow.com/comment/86621499
comment on: http://stackoverflow.com/q/49803339
type: Comment
type: QuestionComment
has text: It really seems an [XY problem](https://mywiki.wooledge.org/XyProblem).What are you trying to achieve? *If the list1 contains the char in list2 in that order*? `"".join(list2) in "".join(list1)`. *If list2 element are in list1*? `all([x in list1 for x in list2])` or what else?
score: 1

http://stackoverflow.com/comment/86766305
type: QuestionComment
comment on: http://stackoverflow.com/q/49875431
score: 1
type: Comment
has text: I think you forget `return df`

http://stackoverflow.com/comment/86606194
has text: I have edited the links. Kindly check the links for the problem.
comment on: http://stackoverflow.com/q/49795825
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49908714
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/1782843
has body: When I put a class method under a decorator it hides the method description ("""x""") in help(class_name). How can I fix that please ?
upvote count: 2
tagged with: python
duplicate of: http://stackoverflow.com/q/1782843
accepted answer: http://stackoverflow.com/a/49908754
has title: Decorator hide method description
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49908754
score: 1
answer count: 1
tagged with: decorator
downvote count: 1
favorite count: 0

pygobject
type: Tag
tags question: http://stackoverflow.com/q/49786357
tags question: http://stackoverflow.com/q/49836499
tag name: pygobject

http://stackoverflow.com/a/78928895
answers question: http://stackoverflow.com/q/49820173
has comment: http://stackoverflow.com/comment/140077157
has body: This max-recursion error arose in the context of a Flask app when I upgraded the requests library to version 2.32.2. The app seemed to work fine but my automated tests started failing. I took the suggestion offered above and extended my project's conftest.py file with the gevent import/patch_all() lines. Then the problem no longer occurred when running tox. Hope this helps someone out there.
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/49833144
accepted answer: http://stackoverflow.com/a/49834589
type: Question
tagged with: numpy
has body: I have this code: for index, row in df.iterrows(): for index1, row1 in df1.iterrows(): if df['budget'].iloc[index] == 0: if df['production_companies'].iloc[index] == df1['production_companies'].iloc[index1] and df['release_date'].iloc[index].year == df1['release_year'].iloc[index1] : df['budget'].iloc[index] = df1['mean'].iloc[index1] It works, but it would take too long to finish. How can I make it run faster? I also tried: df.where((df['budget'] != 0 and df['production_companies'] != df1['production_companies'] and df['release_date'] != df1['release_year']), other = pd.replace(to_replace = df['budget'], value = df1['mean'], inplace = True)) It should be faster but it doesn't work. How do I achieve this? Thank you! df looks like this: budget; production_companies; release_date ;title 0; Villealfa Filmproduction Oy ;10/21/1988; Ariel 0; Villealfa Filmproduction Oy ;10/16/1986; Shadows in Paradise 4000000; Miramax Films; 12/25/1995; Four Rooms 0; Universal Pictures; 10/15/1993; Judgment Night 42000; inLoops ;1/1/2006; Life in Loops (A Megacities RMX) ... and df1: production_companies; release_year; mean; Metro-Goldwyn-Mayer (MGM); 1998; 17500000 Metro-Goldwyn-Mayer (MGM); 1999; 12500000 Metro-Goldwyn-Mayer (MGM); 2000; 12000000 Metro-Goldwyn-Mayer (MGM) ;2001 ;43500000 Metro-Goldwyn-Mayer (MGM); 2002 ;12000000 Metro-Goldwyn-Mayer (MGM) ;2003; 36000000 Metro-Goldwyn-Mayer (MGM); 2004 ;27500000 ... I want to replace the value 0 from df with the "mean" vealue from df1 if the year and the production company is the same.
has title: Efficient way of replacing values from a data set with values from another one
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49834589
type: AnsweredQuestion
tagged with: performance
answer count: 3
has answer: http://stackoverflow.com/a/49833239
tagged with: pandas
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86681452
has answer: http://stackoverflow.com/a/49834243
downvote count: 0
possible better answer: http://stackoverflow.com/a/49834243
favorite count: 0

http://stackoverflow.com/comment/86706706
comment on: http://stackoverflow.com/q/49845712
score: 0
type: Comment
type: QuestionComment
has text: https://pexpect.readthedocs.io/en/stable/

http://stackoverflow.com/comment/86792364
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49888090
has text: Yeah, it seems like "Fill in the blank for `self.assertEqual(__, tuple(["I'm a tuple"]))`" would have made for a more interesting exercise.
score: 0

http://stackoverflow.com/a/65123238
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/49852241
has comment: http://stackoverflow.com/comment/131318506
score: 7
type: Answer
has body: Subtracting the patience value from the total number of epochs - as suggested in this comment - might not work in some situations. For instance, if you set epochs=100 and patience=20, if the best accuracy/loss value is found at epoch 90, the training will stop at epoch 100. So with this approach you would get a wrong number (100-20 = 80). Moreover, as noted in this comment, using EarlyStopping.stopped_epoch only gives you the epoch when the training has been stopped, but NOT the epoch when the best weights are saved. This is particularly useful when you set save_best_weights=True or rely on ModelCheckpoint to save the best model before stopping the training. Therefore my solution is to get the index of model history array, with the best value. Assuming that the metric used is the validation accuracy, relying on numpy, here is some code: import numpy as np model.fit(...) hist = model.history.history['val_acc'] n_epochs_best = np.argmax(hist)

http://stackoverflow.com/q/49889855
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/75944157
answer count: 8
has answer: http://stackoverflow.com/a/49898117
has answer: http://stackoverflow.com/a/51499112
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53096699
has answer: http://stackoverflow.com/a/53276910
downvote count: 0
has answer: http://stackoverflow.com/a/50993644
has title: Error of Installing dlib in anaconda
score: 4
tagged with: python
tagged with: dlib
has answer: http://stackoverflow.com/a/75920436
tagged with: anaconda
has body: I'm trying to install Dlib in anaconda python with this line: conda install -c menpo dlib and I'm getting error like this: UnsatisfiableError: The following specifications were found to be in conflict: - dlib - xlwt Use "conda info &lt;package&gt;" to see the dependencies for each package. How can I solve this problem?
has comment: http://stackoverflow.com/comment/87124955
has answer: http://stackoverflow.com/a/64531944
favorite count: 0

http://stackoverflow.com/comment/86732462
comment on: http://stackoverflow.com/q/49858760
type: Comment
type: QuestionComment
score: 0
has text: To debug cron issues, add this at the end of your line `>/tmp/out1 2>/tmp/out2`. Then you will see exactly what it is doing.

http://stackoverflow.com/comment/86627203
score: 2
type: Comment
has text: This worked for me! I had to add `sudo` at the front because of permission denied errors. Thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/49769015

http://stackoverflow.com/comment/86681239
score: 0
comment on: http://stackoverflow.com/a/49832818
type: Comment
type: AnswerComment
has text: Try to visit [this](https://stackoverflow.com/questions/4930524/how-can-i-set-the-backend-in-matplotlib-in-python/4930867?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa). It might help you.

http://stackoverflow.com/comment/86676735
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49830657
has text: Don't make photos of your screen. Paste the text instead.
score: 0

http://stackoverflow.com/comment/86843007
comment on: http://stackoverflow.com/a/49909306
has text: Good news, just please still post those actual data. Show us (say) the first ten values of `y_pred`. Make sure those are acting sane before you try to measure accuracy, or anything higher up. Always check your assumptions.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86590886
comment on: http://stackoverflow.com/a/49787914
has text: https://crypto.stackexchange.com/questions/20941/why-shouldnt-i-use-ecb-encryption
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/49848167
has title: python and Django export mssql query to excel
tagged with: django-views
answer count: 3
score: 1
has answer: http://stackoverflow.com/a/49850520
tagged with: python
tagged with: sqlalchemy
type: Question
type: UnansweredQuestion
has body: i have build an app in django to extract data from an mssql server and display the results on a table on a template. what i want to do now is to export the same sql query results to an excel file. I have used pymssql driver to connect to the db and pysqlalchemy.
downvote count: 0
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/49870724
has answer: http://stackoverflow.com/a/49849457
favorite count: 0
tagged with: sql-server

http://stackoverflow.com/q/49853623
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
tagged with: django-rest-framework
tagged with: jwt
tagged with: django-views
answer count: 0
has title: Submit a POST request from a Django View and send response to a template
score: 1
has body: I'm working on a Django(1.10) project and now creating a rest API for my project using Django Rest Framework.I have setup JWT token and now I want to provide a template to the user where he can generate a token. Here's the URL for auth token: url(r'^api-token-auth/', obtain_jwt_token) And I want to send a post request to this URL from a view which loads to generate a token but it required user's username and password. How can i pass current user's username and password ? Here's my view: class GetApiAuthToken(LoginRequiredMixin, CreateView): def get(self, request, *args, **kwargs): return render(request, 'dockerDep/getApiAuthToken.html', {}) def post(self, request, *args, **kwargs): if request.method == 'POST': post_data = request.POST.copy() post_data.update({'user': request.user.pk}) payload = {'username': request.user.username, 'password': request.user.password} r = requests.post('http://127.0.0.1:8000/api-token-auth/', params=payload) return HttpResponse('Get token auth request and data is as: {}'.format(r.text)) and here's the template from which user can click on a button to generate a token: Get your Authorization Token to use REST Api : {% csrf_token %} casino Generate Api Token! and here's i'm sending a an AJAX POST reuqest to the view: $(document).on('submit', '#getTokenForm', function (e) { e.preventDefault(); $.ajax({ url: '{% url 'users:getApiAuthToken' %}', type: 'POST', data: { csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function (data) { console.log(data); } }); }); How can I pass user's credentials? or is there a better approach to allow a user to generate a token?
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/q/49908236
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/52426788
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
has body: I have a wxPython GUI packaged into an executable with Pyinstaller. It works correctly on OS X 10.13.4, but doesn't initialize on OS X 10.12.6. This is the error output when my executable is run from the command line: [4693] Error loading Python lib '/var/folders/9_/5d_4dfcs4lj11bdjq4twtl5w0000gp/T/_MEIYsEh11/Python': dlopen: dlopen(/var/folders/9_/5d_4dfcs4lj11bdjq4twtl5w0000gp/T/_MEIYsEh11/Python, 10): Symbol not found: _futimens Referenced from: /var/folders/9_/5d_4dfcs4lj11bdjq4twtl5w0000gp/T/_MEIYsEh11/Python (which was built for Mac OS X 10.13) Expected in: /usr/lib/libSystem.B.dylib in /var/folders/9_/5d_4dfcs4lj11bdjq4twtl5w0000gp/T/_MEIYsEh11/Python I have no idea what this error message means. I've tried googling some pieces of it, but I'm not getting any meaningful results. I'm looking for any clue to get me going in the right direction -- what might be wrong, or how to debug. Unfortunately I don't have access to OS X 10.12.6, so I'm having to troubleshoot for a user remotely. This is my version of Pyinstaller: pyinstaller 3.4.dev0+g07ab024c This seems to happen with brew-installed Python or Anaconda.
has title: Pyinstaller executable fails on old OS X
upvote count: 3
answer count: 1
downvote count: 0
tagged with: macos

enaml
tags question: http://stackoverflow.com/q/49871342
tag name: enaml
type: Tag

http://stackoverflow.com/q/49866551
tagged with: pandas
upvote count: 0
has answer: http://stackoverflow.com/a/49866660
answer count: 1
has body: I have a reference dataframe: ex: time latitude longtitude pm2.5 0 . 0 0 0 1 . 0 5 1 ...... And I have a query with ex: time latitude longtitude 0 . 1 3 1 . 0 5 ....... I want to get the pm2.5 which matches the rows in query. I have used the iteration of rows but it seems very slow. predications_phy = [] for index, row in X_test.iterrows(): Y = phyDf[(phyDf["time"] == row["time"]) &amp; (phyDf["latitude"] == row["latitude"]) &amp; (phyDf["longtitude"] == row["longtitude"])] predications_phy.append(Y) What is the efficient and correct way to get the rows?
tagged with: scikit-learn
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
score: -1
has title: Pandas get rows by its values from dataframes
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49866660

http://stackoverflow.com/comment/86798406
type: Comment
has text: Thanks a lot, but I want to register the base User model (auth.user) here, as instructed on document.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49886363

http://stackoverflow.com/comment/86712276
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49842901
type: QuestionComment
has text: Try connect one of your board to your PC,use a serial debug tool to see which one's fault it is.

http://stackoverflow.com/q/49817726
downvote count: 0
has answer: http://stackoverflow.com/a/49826845
has comment: http://stackoverflow.com/comment/86649908
favorite count: 0
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/86650229
has body: Running Python 3.6.4 (64 bit) on Windows 10, AMD Threadripper 16 core CPU, 64 GB RAM, fast SSD. Nothing else is running (&lt;2% CPU) or using RAM (55GB Free) before I start this test. Everything runs fast except calling mp.Pool() to setup the worker processes. Once setup, running pool.map() is fast as expected. Notes: Running local and tested with and w/o virtual env. Any fixes, workarounds, ideas or explanations would be appreciated. Thanks. import multiprocessing as mp import time for x in range(2,15): t0 = time.perf_counter() with mp.Pool(processes=x) as pool: pass print('Done {0} processes in {1:.2f}s'.format(x, time.perf_counter() - t0)) Done 2 processes in 0.79s Done 3 processes in 1.34s Done 4 processes in 2.18s ... Done 12 processes in 6.44s Done 13 processes in 5.45s Done 14 processes in 5.73s
has comment: http://stackoverflow.com/comment/86650055
tagged with: windows
tagged with: python
has title: python 3.6 multiprocessing.Pool() very slow to start using Windows
linked to: http://stackoverflow.com/q/38236211
score: 2
upvote count: 2
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/49787472
answers question: http://stackoverflow.com/q/49787325
has body: You could use 2 consecutive merges, first on df_a and df_b, and then on df_c: In [49]: df_temp = df_a.merge(df_b, how='outer', left_on=['type_1', 'id_1'], right_on=['type_2', 'id_2']) In [50]: df_temp.merge(df_c, how='outer', left_on=['type_2', 'id_2'], right_on=['type_3', 'id_3']) Out[50]: type_1 id_1 name_1 type_2 id_2 name_2 type_3 id_3 name_3 0 0.0 3 Alex NaN NaN NaN NaN NaN NaN 1 1.0 4 Amy 1 4 Bill 1.0 4 School 2 1.0 5 Allen 1 5 Brian NaN NaN NaN 3 1.0 5 Allen 1 5 Joe NaN NaN NaN 4 1.0 5 Jane 1 5 Brian NaN NaN NaN 5 1.0 5 Jane 1 5 Joe NaN NaN NaN 6 NaN NaN NaN 0 7 Bryce 0.0 7 White
type: Answer
upvote count: 4
score: 4
downvote count: 0

http://stackoverflow.com/q/49828554
has title: How to replace NaN values?
linked to: http://stackoverflow.com/q/5124376
tagged with: python
answer count: 4
possible better answer: http://stackoverflow.com/a/49828602
has comment: http://stackoverflow.com/comment/86672597
has comment: http://stackoverflow.com/comment/86672492
has comment: http://stackoverflow.com/comment/86672479
has answer: http://stackoverflow.com/a/49828622
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/13301262
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49828607
accepted answer: http://stackoverflow.com/a/49828642
has comment: http://stackoverflow.com/comment/86672474
has comment: http://stackoverflow.com/comment/86672628
has answer: http://stackoverflow.com/a/49828642
upvote count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/86672601
has comment: http://stackoverflow.com/comment/86672549
linked to: http://stackoverflow.com/q/27968236
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49828602
has comment: http://stackoverflow.com/comment/86672525
has body: I have a feature called smoking_status it has 3 different values : 1) smokes 2) formerly smoked 3) never smoked The feature column (smoking_status) has above 3 values as well as lot of NaN values how can I treat the NaN values because my data is not numerical, if it was numerical I could have replaced it using median or mean. How can I replace NaN values in my case ?

http://stackoverflow.com/comment/86676742
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49830446
type: Comment
has text: Thank you, I've tried. the same speed (2% faster probably)

http://stackoverflow.com/comment/86783530
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49883682
type: AnswerComment
has text: How will you check without using if? Number of ifs have been reduced. Isn't that what you asked for?

http://stackoverflow.com/q/49916660
has comment: http://stackoverflow.com/comment/86849127
tagged with: python
tagged with: virtualenv
has body: I haven't found a question that specifically addresses this issue, if someone can find one that'll be much appreciated. Running vs code using a virtualenv on Windows 10. I've configured my user settings as such: "python.pythonPath": "C:/virtualenv/NNvenv/Scripts/python.exe" And in the bottom left it shows that the Python executable is from this path. However, I'm using F12 to navigate through my keras module, say for example with the following code: from keras import Sequential model = Sequential() model.fit_generator() And if I press F12 on fit_generator(), it doesn't go to the definition within C:\virtualenv\NNvenv\Lib\site-packages\keras\models.py, rather going to C:\Users\%USER%\AppData\Roaming\Python\Python35\site-packages\keras\models.py. Why is it not navigating to the virtualenv site packages, and how would I configure it to go to the correct library? This is pretty essential as I'm debugging keras code and want to edit the correct files when doing so. I could change the PythonPath system environment variable, but then what's the point of even using the virtual environment. Is there some vs code configuration option I'm missing?
has comment: http://stackoverflow.com/comment/86868559
has title: Navigation in Windows 10 vs code not going to virtualenv library when the same library is installed at user level
score: 0
has comment: http://stackoverflow.com/comment/86857512
type: Question
tagged with: python-3.x
tagged with: visual-studio-code
answer count: 0
has comment: http://stackoverflow.com/comment/86849823
has comment: http://stackoverflow.com/comment/86853252
type: UnansweredQuestion

rows
tags question: http://stackoverflow.com/q/49886660
tag name: rows
type: Tag

http://stackoverflow.com/comment/86838952
comment on: http://stackoverflow.com/a/49816225
type: AnswerComment
score: 0
has text: Here's the problem now: https://stackoverflow.com/questions/49911525/using-a-frozen-savedmodel-graph-in-android-causes-a-shape-issue
type: Comment

http://stackoverflow.com/q/49785904
accepted answer: http://stackoverflow.com/a/49793781
tagged with: python
upvote count: 11
favorite count: 0
has answer: http://stackoverflow.com/a/49803398
has answer: http://stackoverflow.com/a/66440775
downvote count: 0
has answer: http://stackoverflow.com/a/49793781
tagged with: scikit-learn
score: 11
has title: how to set threshold to scikit learn random forest model
possible better answer: http://stackoverflow.com/a/49803398
type: Question
has body: After seeing the precision_recall_curve, if I want to set threshold = 0.4, how to implement 0.4 into my random forest model (binary classification), for any probability &lt;0.4, label it as 0, for any >=0.4, label it as 1. from sklearn.ensemble import RandomForestClassifier random_forest = RandomForestClassifier(n_estimators=100, oob_score=True, random_state=12) random_forest.fit(X_train, y_train) from sklearn.metrics import accuracy_score predicted = random_forest.predict(X_test) accuracy = accuracy_score(y_test, predicted) Documentation Precision recall
type: AnsweredQuestion
answer count: 3

http://stackoverflow.com/q/49819706
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86654423
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86654408
has title: How to get an age column through date of birth in pandas?
accepted answer: http://stackoverflow.com/a/49819962
tagged with: python
tagged with: date
has answer: http://stackoverflow.com/a/49819962
has body: Need to get the age from a datetime64[ns] date of birth column. Tried: now = pd.Timestamp(DT.datetime.now()) clients["age"] = ((now - clients["date_of_birth"])/365) clients["age"].astype(int) But following error appeared: TypeError: cannot astype a timedelta from [timedelta64[ns]] to [int32] clients["age"] 0 NaT 1 22624 days 11:35:15.057887 2 18579 days 11:35:15.057887 3 14918 days 11:35:15.057887 4 21680 days 11:35:15.057887 5 11090 days 11:35:15.057887 6 19346 days 11:35:15.057887 7 11535 days 11:35:15.057887 8 12224 days 11:35:15.057887 9 11431 days 11:35:15.057887
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/86752531
score: 2
comment on: http://stackoverflow.com/q/49868167
type: Comment
has text: Actually, the last line of the traceback suggest it is trying to allocate a sparse result, `nnz` standing for "number of non zeros".
type: QuestionComment

http://stackoverflow.com/q/49868862
has body: I am transferring some legacy posts into a new Django blog. In my script, I have the following code: Entry.objects.create( title=['title'], slug=['slug'], chron_date=['chron_date'], clock='23:59:59', content=['content']) The problem is that the date, time, and datetime fields all refuse to take a variable, or, they all treat the intended variable as a literal string, which generates errors. The only solution I’ve found is the one you see for clock, where I have to hard code a literal string. This means I have to go back through the posts one at a time to manually correct the dates and times. Questions: Why do the date and time objects work this way? Is this the only workaround, or am I missing something that would allow me to use a variable and loop through all the actual dates and get them imported? Thanks.
answer count: 2
type: UnansweredQuestion
tagged with: datetime
has comment: http://stackoverflow.com/comment/86809512
has comment: http://stackoverflow.com/comment/86817615
tagged with: django
tagged with: python
tagged with: variables
score: 0
has title: Python Django Datetime objects and literal strings vs variables
has answer: http://stackoverflow.com/a/49870195
has comment: http://stackoverflow.com/comment/86755187
type: Question
has answer: http://stackoverflow.com/a/50107213

http://stackoverflow.com/a/49758689
upvote count: 3
has comment: http://stackoverflow.com/comment/86532773
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49758549
has body: We can using cumsum with groupby df['recent']=df.finishing_position.astype(str)+'/' df['recent']=df.groupby('horse_id').recent.apply(lambda x : x.cumsum().shift().str[:-1].fillna('')) df Out[140]: finishing_position horse_id race_id recent 0 1 K01 2014011 1 2 K02 2014011 2 3 M01 2014011 3 4 K01 2014012 1 4 2 K01 2014021 1/4 5 3 K01 2014031 1/4/2 6 1 M01 2015011 3 7 2 K01 2016012 1/4/2/3 8 1 K02 2016012 2 9 3 M01 2016012 3/1 10 4 J01 2016012
has comment: http://stackoverflow.com/comment/86533028
has comment: http://stackoverflow.com/comment/86532546
type: Answer
accepted answer of: http://stackoverflow.com/q/49758549
has comment: http://stackoverflow.com/comment/86532933

http://stackoverflow.com/q/49816429
has comment: http://stackoverflow.com/comment/86649042
tagged with: python
tagged with: computer-vision
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86648837
accepted answer: http://stackoverflow.com/a/49816559
has answer: http://stackoverflow.com/a/49816559
has comment: http://stackoverflow.com/comment/86648011
has comment: http://stackoverflow.com/comment/86649303
type: Question
score: 2
has title: Unable to write a valid binary threshold image in opencv (python)
upvote count: 2
has body: I am trying to convert an RGB image to YUV space and then I am trying to add color thresholds to create a binary image. I am doing this as below: img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV) b_channel = cv2.cvtColor(img, cv2.COLOR_RGB2Lab)[:, :, 2] l_channel = cv2.cvtColor(img, cv2.COLOR_RGB2LUV)[:, :, 0] s_channel = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)[:, :, 2] s_binary = np.zeros_like(s_channel) s_binary[(s_channel &gt; s_thresh_min) &amp; (s_channel &lt;= s_thresh_max)] = 1 b_binary = np.zeros_like(b_channel) b_binary[(b_channel &gt; b_thresh_min) &amp; (b_channel &lt;= b_thresh_max)] = 1 l_binary = np.zeros_like(l_channel) l_binary[(l_channel &gt; l_thresh_min) &amp; (l_channel &lt;= l_thresh_max)] = 1 combined_binary = np.zeros_like(b_binary) combined_binary[(l_binary == 1) | (b_binary == 1) | (s_binary == 1)] = 1 f, ax1 = plt.subplots(1, 1, figsize=(10, 5)) ax1.imshow(combined_binary) This all works well and I can see the binary image on the screen. However, when I try to save it on the disk using cv2.imwrite, I get a black image. cv2.imwrite(file_name, combined_binary) I am really confused why this change between the imshow and imwrite. Any hints? Thanks
has comment: http://stackoverflow.com/comment/86648948
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49906127
tagged with: base64
tagged with: python
tagged with: http://stackoverflow.com/tag/png
has comment: http://stackoverflow.com/comment/86830804
answer count: 0
has comment: http://stackoverflow.com/comment/86835720
has body: Hello I'm new to the concept of base64 images. I was trying to convert base64 "links" in a HTML to png files in Python, but the png generated seems to be damaged and I don't know why... Here is my code (in python 3.6) encoded = (string2[0].split(",")[1]).encode("utf-8") with open(r"myDirectory\example1.png", "wb") as fh: fh.write(base64.decodebytes(encoded)) string2[0] is the full base64 string which I copied from the HTML. i.e. something like data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA0gAA...K5C%0AYII= The problem is essentially the following: A png file will be generated, but when I open it, windows says "the file appears to be damaged, corrupted". However strangely when I open this base64 string in google chrome, the photo can be shown. Anyone has encountered similar situation before? p.s. I was thinking to provide the full base64 string, but it's very very long. Anyone knows how to paste such a long string to the question? e.g. a "dragable box of code" similar to what the OP has done in this question Edit: The base64 string can be found here. My first time sharing documents in google drive - let me know if you guys can access it.
type: UnansweredQuestion
score: 1
has title: Strange behaviour when converting base64 string to png in Python
downvote count: 0
has comment: http://stackoverflow.com/comment/86828566
upvote count: 1
has comment: http://stackoverflow.com/comment/86835515
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/19395649

http://stackoverflow.com/q/49855172
answer count: 2
has answer: http://stackoverflow.com/a/49855884
possible better answer: http://stackoverflow.com/a/49855884
has answer: http://stackoverflow.com/a/49856210
accepted answer: http://stackoverflow.com/a/49856210
has comment: http://stackoverflow.com/comment/86725150
has body: I understand that to use a global variable from a function, you Need to execute the function first: def f(): global s s = 'Hello' f() print(s) But how do I use variable s globally in following example: import sys from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, QLineEdit, QLabel, QComboBox, QProgressBar, QFileDialog from PyQt4.QtCore import QSize, pyqtSlot class App(QMainWindow): def __init__(self): super(App, self).__init__() self.setGeometry(500, 300, 820, 350) self.setWindowTitle("Widget") self.initUI() def initUI(self): #Buttons btnposx = 30 btnposy = 50 self.btn4 = QPushButton('GetValue', self) self.btn4.move(btnposx,btnposy+220) self.btn4.clicked.connect(self.cb_get) self.cb = QComboBox(self) self.cb.move(btnposx+120,btnposy+150) self.cb.resize(80,22) self.cb.setMaximumSize(QSize(80,1000000)) self.cb.addItem('A') self.cb.addItem('B') self.cb.addItem('C') self.cb.addItem('D') self.cb.addItem('E') self.show() @pyqtSlot() def cb_get(self): global s cbtext = str(self.cb.currentText()) s = cbtext print(s) if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_()) This code shows a PyQt4 Widget. Function cb_get acquires the Value of a QcomboBox and can be used within the class App(). The Value is saved to variable s. How do I use variable s globally?
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/86725551
has comment: http://stackoverflow.com/comment/86725673
type: Question
has comment: http://stackoverflow.com/comment/86725047
has title: PyQt4 using global variable from function in class
has comment: http://stackoverflow.com/comment/86725875
tagged with: python
has comment: http://stackoverflow.com/comment/86724933
has comment: http://stackoverflow.com/comment/86725269
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49766176
has body: You can use the getText method instead of the .text attribute, since it has an optional separator argument which allows you to replace separations with whatever you want ("\n" here) like this: browser[0].find("div",{"class":"pin_info"}).getText(separator="\n") Result: A Level 2 : 2 DC Fast : 12 Level 2 : 2 Then you can do string manipulation with that until you get to your desired result, something like this: info = browser[0].find("div",{"class":"pin_info"}).getText(separator="\n")[5:].split("\n\n") '\n'.join(map(lambda x: x.replace("\n", " "), info)) Output: Level 2 : 2 DC Fast : 12 Level 2 : 2
accepted answer of: http://stackoverflow.com/q/49765898
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49765898

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/49858708
tags question: http://stackoverflow.com/q/49887049
tags question: http://stackoverflow.com/q/49865999
tags question: http://stackoverflow.com/q/49759897
tags question: http://stackoverflow.com/q/49848375
tags question: http://stackoverflow.com/q/49764367
tags question: http://stackoverflow.com/q/49759326
tags question: http://stackoverflow.com/q/49842247
tags question: http://stackoverflow.com/q/49798741
tags question: http://stackoverflow.com/q/49804018
tags question: http://stackoverflow.com/q/49803159
type: Tag
tags question: http://stackoverflow.com/q/49910238
tags question: http://stackoverflow.com/q/49769229
tags question: http://stackoverflow.com/q/49761746

http://stackoverflow.com/comment/86666592
has text: Not sure if you saw my question update. Let's stick with `int` first. I want to have the *counting* functionality of `Counter` but without the 2x overhead. `defaultdict(int)` does not share the property with `Counter` because querying it adds keys. If we're querying keys frequently with `defaultdict(int)` the dictionary blows up in size (not so with `Counter`). I was hoping there was a way to *mimic* what `Counter` is doing by *not* adding keys automatically.
type: Comment
comment on: http://stackoverflow.com/a/49824929
type: AnswerComment
score: 0

http://stackoverflow.com/a/51510374
upvote count: 4
answers question: http://stackoverflow.com/q/49854190
downvote count: 0
type: Answer
score: 4
has body: The problem has been solved; the right code should be look like below: contractAddress = '0x345ca3e014aaf5dca488057592ee47305d9b3e10' contract = w3.eth.contract(address=contractAddress, abi=abiJson['abi']) accounts = w3.eth.accounts def handle_event(event): receipt = w3.eth.waitForTransactionReceipt(event['transactionHash']) result = contract.events.greeting.processReceipt(receipt) print(result[0]['args']) def log_loop(event_filter, poll_interval): while True: for event in event_filter.get_new_entries(): handle_event(event) time.sleep(poll_interval) block_filter = w3.eth.filter({'fromBlock':'latest', 'address':contractAddress}) log_loop(block_filter, 2)

http://stackoverflow.com/a/49915763
answers question: http://stackoverflow.com/q/49914882
downvote count: 0
has body: You have to run the conda info tensorflow and conda info numba to see each dependencies for each package and then you have to install those package like conda install package=version to fix the problem.
score: 3
type: Answer
upvote count: 3

http://stackoverflow.com/a/49831021
score: 1
answers question: http://stackoverflow.com/q/49830757
has body: If you are open to using a 3rd party library, you can use pandas: import pandas as pd d = {'09-04-2018' : {1: 11, 2: 5, 3: 1, 4: 1, 5: 0}, '10-04-2018' : {1: 5, 2: 1, 3: 1, 4: 1, 5: 0}} # create dataframe from dictionary df = pd.DataFrame.from_dict(d).reset_index().rename(columns={'index': 'count'}) # write dataframe to csv file df.to_csv('file.csv', index=False) print(df) # count 09-04-2018 10-04-2018 # 0 1 11 5 # 1 2 5 1 # 2 3 1 1 # 3 4 1 1 # 4 5 0 0
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49799578
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86614087
linked to: http://stackoverflow.com/q/49748063
tagged with: pip
tagged with: macos
has body: I'm currently using MacOS (10.13.4) and Python 2.7.14. I can't get pip to install any packages at all. All I get is the following error Collecting scrapy Could not fetch URL https://pypi.python.org/simple/scrapy/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:661) - skipping Could not find a version that satisfies the requirement scrapy (from versions: ) No matching distribution found for scrapy Just for reference here is another packages error message: Collecting dateutil Could not fetch URL https://pypi.python.org/simple/dateutil/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:661) - skipping Could not find a version that satisfies the requirement dateutil (from versions: ) No matching distribution found for dateutil Not sure if this is relevant but heres this as well: $ which openssl /usr/bin/openssl $ openssl version LibreSSL 2.2.7 And from Python: &gt;&gt;&gt; import ssl &gt;&gt;&gt; print ssl.OPENSSL_VERSION OpenSSL 0.9.8zh 14 Jan 2016 Any help at this point would be appreciated.
type: Question
duplicate of: http://stackoverflow.com/q/49748063
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86613859
has title: Python: pip install won't work on any packages

http://stackoverflow.com/a/49767434
has comment: http://stackoverflow.com/comment/86552172
accepted answer of: http://stackoverflow.com/q/49767227
downvote count: 0
score: 1
has body: Create helper Series for distinguish consecutive values in A column and then filter by boolean indexing with inverted (~) boolean mask created by duplicated chained with another mask for compare value df: s = df['A'].ne(df['A'].shift()).cumsum() df = df[~((df['A'] == 'df') &amp; (s.duplicated()))] print (df) A B C D E 0 qw 1 3 1 1 1 er 2 4 2 6 2 ew 4 8 44 4 3 df 34 34 34 34 7 we 2 5 5 2 8 we 4 4 4 4 9 df 34 9 34 34 11 we 4 7 4 4 12 qw 2 2 7 2
answers question: http://stackoverflow.com/q/49767227
has comment: http://stackoverflow.com/comment/86552126
type: AcceptedAnswer
type: Answer
upvote count: 1

http://stackoverflow.com/a/49825354
downvote count: 0
answers question: http://stackoverflow.com/q/49805928
type: Answer
has body: You're really close. Three changes: Don't open the html file in binary mode. Read the file directly into the html string report_file = open('export.html') html = report_file.read() remove the subsequent assignment to html var html = """\ """ send the msg object as constructed server.sendmail(me, you, msg.as_string()) That worked for me. Also keep in mind that by default gmail settings may not allow your script to send mail. If so you'll need to update your settings to allow "insecure" (meaning non-Google) apps to send mail.
score: 4
upvote count: 4

http://stackoverflow.com/q/49900116
favorite count: 0
has body: For example: for i range(1,9999): #foo() is an operation that has varying execution time. foo(i); check_number_of_foo_executed_last_60_sec(); In the middle of the for loop, how to check how many foo() has been executed in, say last 60 seconds? Apart from storing the time that each foo() was executed in a list, are there any other ways?
type: Question
tagged with: time
answer count: 2
has title: How to check the number of executed operations in the past x minutes in Python?
downvote count: 0
type: UnansweredQuestion
tagged with: python
tagged with: performance
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49900486
has answer: http://stackoverflow.com/a/49900554

http://stackoverflow.com/q/49772991
score: 0
has comment: http://stackoverflow.com/comment/86632919
has comment: http://stackoverflow.com/comment/86560766
has body: I want import a class from other python file. project └───src │ │ main.py │ │ │ └───spam │ │ __init__.py │ │ spamEmail.py │ │ ... Now, I want to import a class named spamEmailBayes from spamEmail.py in main.py Which one is the correct import? This one: from .spam.spamEmail import spamEmailBayes or this one: from spam.spamEmail import spamEmailBayes
has comment: http://stackoverflow.com/comment/86561054
tagged with: import
duplicate of: http://stackoverflow.com/q/14132789
has title: about python relative import, which is right?
type: Question
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/14132789
tagged with: python
has comment: http://stackoverflow.com/comment/86561309

http://stackoverflow.com/comment/86632268
comment on: http://stackoverflow.com/q/49808686
type: Comment
type: QuestionComment
has text: Related / maybe a dup: [What is the purpose of self](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self)
score: 0

http://stackoverflow.com/comment/86753807
type: QuestionComment
has text: Have you tried this answer to a similar question: https://stackoverflow.com/a/33001877/3700867
type: Comment
comment on: http://stackoverflow.com/q/49869185
score: 0

http://stackoverflow.com/comment/86743144
comment on: http://stackoverflow.com/a/49850304
has text: Hi Bill, thanks so much for your help on this! I understand now that the (x,y) Cartesian meshgrid I was passing before was just a transformation of the polar points and needed to be re-gridded on a normally spaced plane. Thank you for discovering and correcting that. You are right that the nearest neighbor interpolation is acting strangely. If I re-run with linear interpolation (and also reverse the values in order to get the orientation right) then this is my result: https://i.imgur.com/LEh0xdS.png This looks great, but I should use the nearest neighbor method. Any tips going forward?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49888809
score: -1
answers question: http://stackoverflow.com/q/49888482
has body: I recommend you try using a ModelSerializer - it is the standard means to taking data submitted to your API, validating it, and creating an instance in your database.
has comment: http://stackoverflow.com/comment/86839686
downvote count: 1
has comment: http://stackoverflow.com/comment/86837399
has comment: http://stackoverflow.com/comment/86794052
upvote count: 0
type: Answer

http://stackoverflow.com/a/49844538
has comment: http://stackoverflow.com/comment/86705327
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86705521
has body: You can just write In [16]: d = {z:z**z if z%2 else z for z in range(5)} In [17]: d Out[17]: {0: 0, 1: 1, 2: 2, 3: 27, 4: 4} which is easier to read if you supply parentheses: In [18]: d = {z:(z**z if z%2 else z) for z in range(5)} In [19]: d Out[19]: {0: 0, 1: 1, 2: 2, 3: 27, 4: 4} The enclosed part is a Python ternary expression for the value, not for the (key, value) pair. @timgeb but what if he also wants to change the key too in the else? (Let's assume we want z*10.) In cases like this, you could write something like In [24]: d = {(z*10 if z%2 else z):(z**z if z%2 else z) for z in range(5)} In [25]: d Out[25]: {0: 0, 10: 1, 4: 4, 2: 2, 30: 27} but this is inefficient because z%2 is computed twice. It is better to make use of the fact that the dict constructor takes an iterable of two-element iterables: In [26]: dict((z*10, z**z) if z%2 else (z, z) for z in range(5)) Out[26]: {0: 0, 10: 1, 4: 4, 2: 2, 30: 27}
accepted answer of: http://stackoverflow.com/q/49844432
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49844432
has comment: http://stackoverflow.com/comment/86707087
has comment: http://stackoverflow.com/comment/86705358

http://stackoverflow.com/comment/86602000
type: QuestionComment
comment on: http://stackoverflow.com/q/49793830
score: 0
type: Comment
has text: Because , the form can be anything , so if you do no Convert it in the case of danger input will crash your machine or inject your DB ..

http://stackoverflow.com/comment/126548306
score: 0
comment on: http://stackoverflow.com/a/69483584
type: AnswerComment
has text: Missing the `asNondeterministic`
type: Comment

git
tags question: http://stackoverflow.com/q/49897168
tags question: http://stackoverflow.com/q/49812697
type: Tag
tags question: http://stackoverflow.com/q/49796691
tags question: http://stackoverflow.com/q/49816577
tag name: git
tags question: http://stackoverflow.com/q/49800612
tags question: http://stackoverflow.com/q/49869977

http://stackoverflow.com/a/49770815
type: Answer
has comment: http://stackoverflow.com/comment/86556579
upvote count: 46
has comment: http://stackoverflow.com/comment/86556730
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49770344
score: 46
answers question: http://stackoverflow.com/q/49770344
has body: The default decimal representation in Django REST framework is string. To disable this behavior, add following to your settings.py file: REST_FRAMEWORK = { 'COERCE_DECIMAL_TO_STRING': False, # Your other settings ... } See details in the documentation.
type: AcceptedAnswer

http://stackoverflow.com/comment/86595996
has text: The value of `collatz(n)` is the value `collatz` returns. You have to do something with it. `collatz(n)` on its own line is like `2 + 3` on its own line – it makes 5 and… throws it away.
type: Comment
comment on: http://stackoverflow.com/q/49790545
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86695759
type: Comment
comment on: http://stackoverflow.com/q/49801169
has text: @Aprillion The magic number is easier for me and my team to read and to use (I can see why a dict would be better in some instances, but not on this one). And I did explicitly explain why I need nested over flat, each layer is an instance by it self regardless of its entities (Has its own parameters and functionality in addition to containing entities). Also there is a certain connectivity between entities (certain hardware commands will affect a group of entities and not one entity directly).
score: 0
type: QuestionComment

http://stackoverflow.com/a/49874502
has body: I managed to get it working. As there was little response to this post originally, I believe it would be very useful to leave this fix for future visitors. Use pip install comtypes to install the library. It is a lot more cooperative and less janky than python's native comtype implementation. import comtypes.client speak = comtypes.client.CreateObject("SAPI.SpVoice") filestream = comtypes.client.CreateObject("SAPI.spFileStream") filestream.open("out.wav", 3, False) speak.AudioOutputStream = filestream speak.Speak("test") filestream.close()
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/49871252
type: Answer
score: 4

http://stackoverflow.com/comment/86804850
has text: don't need a while loop : Exactly just use break and move forward. While loop can create problem when there will be no values that are matching. No condition is breaking loop (as `loggedin` is always false)
score: 0
comment on: http://stackoverflow.com/a/49894506
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86558276
score: 0
comment on: http://stackoverflow.com/q/49769623
type: Comment
type: QuestionComment
has text: oh sorry ,that's it my command to run laravel php artisan serv

http://stackoverflow.com/q/49807449
downvote count: 0
has title: How to check if a function was called in a unit test using pytest-mock?
has comment: http://stackoverflow.com/comment/86633469
tagged with: unit-testing
favorite count: 0
possible better answer: http://stackoverflow.com/a/69620212
type: Question
answer count: 2
tagged with: python
has body: I have a unit test where I want to check if a function was called. How do I do this withpytest and pytest-mock libraries? For example, here is a unit test test_hello.py. In this test I call the function my_function and want to verify that it called hello with a given argument. def hello(name): return f'Hello {name}' def my_function(): hello('Sam') def test_hello(mocker): mocker.patch('hello') my_function() hello.assert_called_once_with('Sam') The code above returns the following error: target = 'hello' def _get_target(target): try: &gt; target, attribute = target.rsplit('.', 1) E ValueError: not enough values to unpack (expected 2, got 1) /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py:1393: ValueError During handling of the above exception, another exception occurred: mocker = &lt;pytest_mock.MockFixture object at 0x109c5e978&gt; def test_hello(mocker): &gt; mocker.patch('hello') test_hello.py:8: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pytest_mock.py:156: in __call__ return self._start_patch(self.mock_module.patch, *args, **kwargs) /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pytest_mock.py:134: in _start_patch p = mock_func(*args, **kwargs) /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py:1544: in patch getter, attribute = _get_target(target) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ target = 'hello' def _get_target(target): try: target, attribute = target.rsplit('.', 1) except (TypeError, ValueError): raise TypeError("Need a valid target to patch. You supplied: %r" % &gt; (target,)) E TypeError: Need a valid target to patch. You supplied: 'hello' /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py:1396: TypeError
accepted answer: http://stackoverflow.com/a/49808218
linked to: http://stackoverflow.com/q/3829742
has answer: http://stackoverflow.com/a/49808218
tagged with: mocking
tagged with: pytest
has answer: http://stackoverflow.com/a/69620212
score: 31
upvote count: 31
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/122899060

http://stackoverflow.com/q/49825873
linked to: http://stackoverflow.com/q/20449427
has answer: http://stackoverflow.com/a/49825903
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/20449427
answer count: 1
has title: Product of two input numbers ( TypeError: can't multiply sequence by non-int of type 'str')
accepted answer: http://stackoverflow.com/a/49825903
has body: a=input('user enters the first number') b=input('user enters the second number') print(a*b) when I finally print out the product of a*b it gives me an error (TypeError: can't multiply sequence by non-int of type 'str') any idea how I can sort out this issue
type: Question
type: AnsweredQuestion
score: 0
tagged with: python

http://stackoverflow.com/comment/86698997
type: Comment
type: QuestionComment
score: 0
has text: Yes - the point of Cython is that it translates the code to C which lets it run faster and access C functions directly. This means it needs to be compiled. It's likely the repository you downloaded it from has some installation instructions, and so you should follow them.
comment on: http://stackoverflow.com/q/49837155

http://stackoverflow.com/comment/86635956
type: Comment
has text: Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful.
score: 1
comment on: http://stackoverflow.com/q/49810707
type: QuestionComment

http://stackoverflow.com/comment/86824250
score: 0
comment on: http://stackoverflow.com/q/49903923
type: QuestionComment
has text: yea, I changed `DEBUG = False`, I can't get it to take effect either, Im not sure how to reload the uwsgi
type: Comment

http://stackoverflow.com/comment/86714096
comment on: http://stackoverflow.com/q/49848517
has text: I’m using Windows 10 and Jupyter notebook. I tried using python 2.7 and get same ‘no module ‘ error.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49832548
answer count: 1
has comment: http://stackoverflow.com/comment/86681235
has comment: http://stackoverflow.com/comment/86680388
has comment: http://stackoverflow.com/comment/86680426
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86680603
has comment: http://stackoverflow.com/comment/86680810
has comment: http://stackoverflow.com/comment/86681092
has comment: http://stackoverflow.com/comment/86680725
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86680467
has comment: http://stackoverflow.com/comment/86680737
has comment: http://stackoverflow.com/comment/86681196
has title: Format Time stamp in Python
upvote count: 1
tagged with: python
has body: I'm getting a formatting error.. My code: date,bid,ask = np.loadtxt('EURUSDH1_1week1.csv', unpack=True, delimiter=',', converters={0:mdates.strpdate2num('%Y%m%d%H%M%S')}) error: ValueError: time data '20180406,00:48.9,1.22394,1.22417,,"' does not match format '%Y%m%d%H%M%S' The data in the csv file is shown as (four columns): 20180406 00:48.9 1.22394 1.22417 20180406 00:48.9 1.22394 1.22417 20180406 00:53.3 1.2239 1.22421 20180406 00:54.6 1.22391 0 20180406 01:51.8 0 1.2241 20180406 02:19.4 1.22396 1.22404 20180406 02:49.8 1.22391 1.22399 how do i remove the colons and period from the time stamp?
has comment: http://stackoverflow.com/comment/86680510
has comment: http://stackoverflow.com/comment/86680966
has comment: http://stackoverflow.com/comment/86680411
has comment: http://stackoverflow.com/comment/86680499
has answer: http://stackoverflow.com/a/49835201
score: 1
has comment: http://stackoverflow.com/comment/86681313
downvote count: 0

http://stackoverflow.com/comment/86989773
type: Comment
has text: I will verify and let you know.
comment on: http://stackoverflow.com/a/49902764
type: AnswerComment
score: 0

http://stackoverflow.com/q/49913275
has comment: http://stackoverflow.com/comment/86922766
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86922729
tagged with: scipy
has comment: http://stackoverflow.com/comment/86922651
has comment: http://stackoverflow.com/comment/86842132
has comment: http://stackoverflow.com/comment/86922577
has body: I fit a nonlinear function with several parameters using scipy.optimize.minimize to minimize the least-squares error. How do I find the variance of the parameters? I tried using the diagonal of the inverse of the Hessian, but the values are 100 times larger than the expected variances. I saw in this question on Cross Validated that the person rescaled the covariance matrix using the "number of measurements" but I don't know what that means. I realise this question is basically a duplicate of a previous question, but that answer is not sufficient for me. In particular, the first answer says that the scipy.optimize.least_squares function returns the error on the parameters, which is untrue. The second answer does not address the case of least-squares minimization.
tagged with: curve-fitting
tagged with: python
has title: Parameter uncertainties for scipy.optimize.minimize
duplicate of: http://stackoverflow.com/q/43593592
tagged with: optimization
type: Question
tagged with: numpy
score: 0
linked to: http://stackoverflow.com/q/43593592
answer count: 0

http://stackoverflow.com/comment/86716599
type: Comment
score: 0
type: AnswerComment
has text: It's not form. It's just on of the columns in a datatable and set as a variable. like on the previous page, `item = Item.query.filter_by(id=item_id).first()` Item is defined like this and one of the column representing the price. I want to get it from the specific item
comment on: http://stackoverflow.com/a/49850378

http://stackoverflow.com/a/49995630
answers question: http://stackoverflow.com/q/49890551
has body: As an example of a project that does what you're looking to do, you can see the airflow start its webserver with gunicorn: https://github.com/apache/incubator-airflow/blob/v1-9-stable/airflow/bin/cli.py#L675 Update I admit this concrete example still uses a subprocess but if the config files in directories are your issue you can change your working directory of the process with the cwd= argument to Popen. There is a documented example of extending the gunicorn BaseApplication with a class that loads its own config and then handing off execution to the run() method of the subclass, which seems to be the thing you wanted to do over 4 years ago.
has comment: http://stackoverflow.com/comment/129167373
type: Answer
upvote count: 0
score: -1
downvote count: 1

http://stackoverflow.com/a/49763298
upvote count: 1
has body: Look at this line in the loop: difference = difference[i+1] - difference[i] Here, you set the variable difference to an integer. So, on the second loop, you try to index an integer. Eg, you try to say that difference = 1[2] - 1[1], which makes no sense whatsoever. This is what the error "Integer is not subscriptable" means. You need to make a new list, which is what the list comprehension does before changing your variable. That's why it doesn't give a type error. I think your code should be: for i in range(len(difference)-1): difference[i] = difference[i+1] - difference[i] difference = difference[:-1] # drop last element.
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49763225

http://stackoverflow.com/a/49802762
has comment: http://stackoverflow.com/comment/86620513
answers question: http://stackoverflow.com/q/49802727
score: 3
has body: One way is to use pd.Series.value_counts: res = df.loc[df['days_old'] &gt; 3, 'fruit'].value_counts() # apple 2 # orange 1 # Name: fruit, dtype: int64 Using pd.DataFrame.apply is inadvisable as this will result in an inefficient loop.
type: Answer
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49802727
type: AcceptedAnswer

http://stackoverflow.com/a/49860609
type: Answer
has comment: http://stackoverflow.com/comment/86739103
accepted answer of: http://stackoverflow.com/q/49860092
answers question: http://stackoverflow.com/q/49860092
has comment: http://stackoverflow.com/comment/86756969
type: AcceptedAnswer
score: 0
has body: Re 1: You can use a callable that returns all group. Example: def getGroupNames(): return Group.objects.all().values_list('name', flat=True) You will still need to convert this to a tuple of ('short-name', 'human-readable-name') If you want the same full names as short and human readable names in the tuple, you can do: def getGroupNames(): groups = Group.objects.all().values_list('name', flat=True) return zip(groups, groups) And then use the same in the choice field editor = models.CharField(max_length=350, default=0, choices=getGroupNames(), verbose_name='Responsibility') Re 2: You can filter your query def getGroupNames(): return Group.objects.filter(name__starts_with='staff').values_list('name', flat=True) Using choices is a presentation convenience. There is no restriction of the value that can be sent to the database, even coming from the front-end. For example, if you use the browser's inspect feature, you can edit the drop-down list, change one of the values and submit it. The back-end view will then happily consume it and save it to the database. Meaning you will still be able to do this obj = SomeModel.objects.get(pk=1) obj.editor = 'Random Value not part of choices' obj.save() Re 3: The callable technique mentioned above is as static or as dynamic as you write it to be; this function will be evaluated when you make migrations and the values will be added as choices in the migration file. However, any serializers or forms that you write around this model will evaluate the choices time and time again. Reference: https://zindilis.com/blog/2017/05/04/django-backend-validation-of-choices.html

http://stackoverflow.com/comment/86752485
type: Comment
has text: i added export PYTHONSTARTUP=$HOME/.pythonrc.py to my .bash_profile( i have a mac). I just found this doing research and then the pythonrc.py will contain the script that edits the info.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49868454

http://stackoverflow.com/a/49762181
accepted answer of: http://stackoverflow.com/q/49761727
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49761727
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Here is an alternative way. It is not a one-liner, but it avoids the need to effectively calculate the maximum twice. import pandas as pd df = pd.DataFrame({'yield': [0, 1, 3, 5, 1, 9, 5]}) s = df.loc[df['yield'] == df['yield'].max(), 'yield'] res = next(zip(s.index, s)) print(res) # (5, 9) Alternatively: s = df.loc[df['yield'].argmax()] res = (s.name, s.iloc[0])

http://stackoverflow.com/q/49811982
score: -1
upvote count: 0
tagged with: cidr
has body: I have 2 files that contain subnets in cidr format (212.234.96.0/24, 80.10.0.0/24, ...) liny by line. I will like you to create a python script that will tell me overlapping subnets. Input are file1 (list of subnets, more than 4000) and file2 (list that I want to check with file1). I want the output in file3 with the file2 subnets without overlapping. For the other hand, I did this work in a shell script but the processing time is too long (for the +4000 subnets processing). Some people recommended that I should do this work in python. The problem is I'm new in python. Thank you.
tagged with: subnet
tagged with: overlap
answer count: 1
downvote count: 1
has title: Checking overlapped subnets
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49815337
has comment: http://stackoverflow.com/comment/86638840
tagged with: python

http://stackoverflow.com/q/49851545
favorite count: 0
type: Question
tagged with: numpy
score: 3
type: UnansweredQuestion
tagged with: arrays
tagged with: python
has body: While learning NumPy, I came across its advantage that, NumPy requires less memory than traditional list. import numpy as np import sys # Less Memory l = range(1000) print(sys.getsizeof(l[3])*len(l)) p = np.arange(1000) print(p.itemsize*p.size) this looks convincing, but than when I try, print(sys.getsizeof(p[3])*len(p)) It shows higher memory size than list. Can someone help me out understanding this behavior.
has title: Memory Efficiency of NumPy
tagged with: list
has answer: http://stackoverflow.com/a/49862066
answer count: 2
has comment: http://stackoverflow.com/comment/86717685
has answer: http://stackoverflow.com/a/49851987
upvote count: 3
linked to: http://stackoverflow.com/q/49751000
downvote count: 0
has comment: http://stackoverflow.com/comment/86717711

http://stackoverflow.com/q/49887961
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
tagged with: data-analysis
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49888279
has comment: http://stackoverflow.com/comment/86792113
tagged with: python
has body: So, I have a large data frame with customer names. I used the phone number and email combined to create a unique ID key for each customer. But, sometimes there will be a typo in the email so it will create two keys for the same customer. Like so: Key | Order # 555261andymiller@gmail.com 901345 555261andymller@gmail.com 901345 I'm thinking of combining all the keys based on the phone number (partial string) and then assigning all the keys within each group to the first key in every group. How would I go about doing this in Pandas? I've tried iterating over the rows and I've also tried the groupby method by partial string, but I can't seem to assign new values using this method.
tagged with: data-science
has comment: http://stackoverflow.com/comment/86792202
has comment: http://stackoverflow.com/comment/86792046
has comment: http://stackoverflow.com/comment/86792245
has title: Pandas: fix typos in keys within a dataframe

http://stackoverflow.com/comment/86828132
type: QuestionComment
comment on: http://stackoverflow.com/q/49906101
has text: Before posting, consider copying <your question title> and pasting it into google search bar.
score: 0
type: Comment

http://stackoverflow.com/comment/86734488
has text: take a look at django formsets : https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/#model-formsets. This is a tutorial I like: https://medium.com/@adandan01/django-inline-formsets-example-mybook-420cc4b6225d
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49859689
type: Comment

http://stackoverflow.com/q/49809438
tagged with: bins
has comment: http://stackoverflow.com/comment/86634141
has title: Dimension issue when using .apply(value_counts, bin=x)
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49809863
answer count: 2
has answer: http://stackoverflow.com/a/49809555
possible better answer: http://stackoverflow.com/a/49809555
accepted answer: http://stackoverflow.com/a/49809863
has comment: http://stackoverflow.com/comment/86634127
downvote count: 0
has comment: http://stackoverflow.com/comment/86634269
tagged with: pandas
has comment: http://stackoverflow.com/comment/86634354
has comment: http://stackoverflow.com/comment/86634108
has comment: http://stackoverflow.com/comment/86634370
has comment: http://stackoverflow.com/comment/86634330
has comment: http://stackoverflow.com/comment/86634173
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86634303
tagged with: python
has body: I am trying to apply value_counts to the following dataframe using bins df2 = pd.DataFrame(np.random.randint(0,100,size=(1000, 4)), columns=list('ABCD')) df2.apply(pd.value_counts, normalize=True, bins=[0,25,50,75,101]).sort_values(by=['A'], ascending=False) However when I do this i get the following error: ValueError: could not broadcast input array from shape (5) into shape (4) The code works fine when I am not trying to use bins.
tagged with: apply

http://stackoverflow.com/q/49847272
linked to: http://stackoverflow.com/q/533905
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/86709583
has title: Alternative to Nested for loop in python
accepted answer: http://stackoverflow.com/a/49847343
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49847343
downvote count: 1
has comment: http://stackoverflow.com/comment/86709591
favorite count: 0
type: AnsweredQuestion
tagged with: performance
has body: I am processing the Cartesian product of a list of entities. For e.g. a_list = ['a','b'] The expected output is: "a";"a"&amp;"a";"b"&amp;"b";"a"&amp;"b";"b" Each entity in the entity pair is separated by semicolon ";" and each enitity pair is separated by "&amp;". I used following nested for loop to achieve the output. entity_set = ['a','b'] domain_text = '' count = 0 for entity1 in entity_set: for entity2 in entity_set: count += 1 domain_text += '"' + entity1 + '"' + ';' + '"' + entity2 + '"' if count &lt; (len(entity_set)*len(entity_set)): domain_text += '&amp;' print domain_text However, the process gets too slow as the size of a_list increases to thousands of entities. Is there any elegant solutions that can be used alternatively?
tagged with: nested
tagged with: python
score: -1

http://stackoverflow.com/comment/86721492
has text: Yes, but only the first case prevents you from plotting y as a function of x.
score: 0
comment on: http://stackoverflow.com/q/49810123
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/92005288
comment on: http://stackoverflow.com/a/52532726
type: Comment
score: 0
type: AnswerComment
has text: Pleas include relevant parts of the document in the answer, so that it the link ever breaks, the answer remains meaningful.

http://stackoverflow.com/comment/86594863
has text: Thank you wwii for your answer, I've read again and again all my production code as you advised, exposing the issue helped me to fix it.
type: QuestionComment
comment on: http://stackoverflow.com/q/49784739
score: 0
type: Comment

http://stackoverflow.com/q/49824027
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86663958
accepted answer: http://stackoverflow.com/a/49824175
tagged with: pandas
has comment: http://stackoverflow.com/comment/86664059
has title: Isnan is not supported for the input types Python Imputer
has answer: http://stackoverflow.com/a/49824175
has body: import numpy as np import matplotlib.pyplot as plt import pandas as pd #Import Data set dataset= pd.read_csv('Data.csv') X = dataset.iloc[:,:-1].values Y = dataset.iloc[:,3].values #Taking Care of The Missing Data from sklearn.preprocessing import Imputer imputer = Imputer(missing_values='nan',strategy='mean',axis=0) imputer = imputer.fit(X[:,1:3]) X[:,1:3] = imputer.transform(X[:,1:3]) I was following this tutorial series and did exactly as he tutor did with me of course having this error as mentioned in the code. A potential solution would be of course very helpful. Thanks in advance. Error : if value_to_mask == "NaN" or np.isnan(value_to_mask): TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
tagged with: python
linked to: http://stackoverflow.com/q/36000993
has comment: http://stackoverflow.com/comment/86664230
has comment: http://stackoverflow.com/comment/86664317
upvote count: 2
has comment: http://stackoverflow.com/comment/86664019
score: 1
answer count: 1
tagged with: scikit-learn
downvote count: 1
has comment: http://stackoverflow.com/comment/86664150
favorite count: 0
type: Question

http://stackoverflow.com/comment/86551139
type: Comment
has text: This is the POST being made: https://imgur.com/a/syt64.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49767872

http://stackoverflow.com/q/49764143
linked to: http://stackoverflow.com/q/26957831
tagged with: excel
has comment: http://stackoverflow.com/comment/86561081
score: 0
has comment: http://stackoverflow.com/comment/86544020
answer count: 0
has comment: http://stackoverflow.com/comment/86555384
has body: Why am I am getting this error message when I run my code? AttributeError: 'Workbook' object has no attribute 'get' using xlutils My code is for a kind of questions and answers and I need to write those answers into Excel. The questions are written in Portuguese but I don't believe makes any important difference.. My Code from xlutils.copy import copy import xlwt import xlrd nome = input('Fale seu nome: ') idade = input('Qual a sua idade? ') qe = 0 q = 2 wb = xlrd.open_workbook("Tabela de desempenho.xls") wb_copy = copy(wb) wb_copy.get.sheet(0) print("Olá ", nome, "Vamos começar o teste.") print("") p1 = int(input("Qual é o valor de 2+2? ")) if p1 == 4: print("Você acertou!") p1 = True else: p1 = False if p1 == False: print("Reprovado") else: print("Aprovado!") p2 = str(input("Qual o nome da instituição? (APENAS SIGLA)")) if p2 == "APAE": print("Correto") p2 = True else: p2 = False if p2 == False: print("errado") else: print("Pelo certo") if p1 == True: qe += 1 else: qe += 0 if p2 == True: qe += 1 else: qe + 0 porc = qe / q * 100 print("Seu desempenho foi: ", porc, "%") if porc == 100: print("Você está entre os mais adaptados!") elif porc == 50: print("Você está na metade, quase lá!") else: print("burrokkkkkkkkkkkkkkkkkkkkkk") w_sheet.write(0,0,'Nome') w_sheet.write(0,1,'Idade') w_sheet.write(0,2,'Desempenho') w_sheet.write(1,0, nome) w_sheet.write(1,1, idade) w_sheet.write(1,2, porc) wb.save("Tabela de desempenho.xls")
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86555232
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86612232
tagged with: python
has title: AttributeError: 'Workbook' object has no attribute 'get' using xlutils

http://stackoverflow.com/q/49817590
type: Question
has body: I was installing pip for python3. I used the following command for that: sudo apt-get install python3-pip But after installation it still says pip is not installed. I have python 3.5.2 installed.
tagged with: python-3.x
tagged with: python
tagged with: ubuntu
possible better answer: http://stackoverflow.com/a/49817642
has answer: http://stackoverflow.com/a/49817642
accepted answer: http://stackoverflow.com/a/49817617
type: AnsweredQuestion
has title: Installing pip on ubuntu 16.04
has answer: http://stackoverflow.com/a/49817617
answer count: 3
has answer: http://stackoverflow.com/a/50461114
upvote count: 2
score: 1
tagged with: pip
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/49785780
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49785461
has body: Python doesn't save the column number information you want, whether in the frame object or the code object. You'd have to retrieve the source code, examine the last executed bytecode instruction, and figure out what column of the source code to match that instruction to. That's probably going to be a lot of work.

http://stackoverflow.com/comment/86779124
score: 0
comment on: http://stackoverflow.com/q/49880980
has text: @Lundin: That proves I have a human brain. All those years of doubting are over!
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49788723
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/68811498
possible better answer: http://stackoverflow.com/a/68811498
score: 1
downvote count: 3
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49788784
answer count: 2
has body: x = np.linspace(0,10, 5) y = 2*x points = np.array([x, y]).T.reshape(-1, 1, 2) What's the mean of the third line?I know the mean of reshape(m,n), but what does reshape(-1, 1, 2) means?
tagged with: python
has title: what's the mean of "reshape(-1,1,2)"
upvote count: 4
has answer: http://stackoverflow.com/a/49788784

http://stackoverflow.com/a/49823483
type: Answer
has body: Colab is run in the cloud. It cannot send display to a window on your computer. So, you cannot use Pygame. Or you need some clever hacking like VNC.
accepted answer of: http://stackoverflow.com/q/49792820
score: 5
upvote count: 5
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49792820
downvote count: 0

http://stackoverflow.com/comment/86761045
comment on: http://stackoverflow.com/q/49872843
score: 0
type: Comment
has text: As you wish it to be the ouput, I can think of many json structures. Which one will you want?
type: QuestionComment

http://stackoverflow.com/a/49883888
downvote count: 0
upvote count: 2
has body: This might work for you: import pandas as pd dataset = pd.read_csv('MyData.csv', delimiter = ',') # Set filter conditions beforehand. condition_1 = (18 &gt;= dataset['StartLat']) &amp; (20 &lt;= dataset['StartLat']) condition_2 = (72.5 &gt;= dataset['StartLng']) &amp; (75 &lt;= dataset['StartLng']) # Filter based on conditions. filtered_dataset = dataset[condition_1 &amp; condition_2] # Export filtered dataset. filtered_dataset.to_csv(...)
type: Answer
has comment: http://stackoverflow.com/comment/86789470
score: 2
answers question: http://stackoverflow.com/q/49882581
has comment: http://stackoverflow.com/comment/86785224

http://stackoverflow.com/comment/86794502
score: 0
type: Comment
type: QuestionComment
has text: I'm pretty sure it doesn't have to do with the version because the problem occurred before updating to 3.2.8. Oddly enough, other students in my class are not having the same issue even using the same version and their own conda environments.
comment on: http://stackoverflow.com/q/49889137

http://stackoverflow.com/q/49838900
has title: How to write entry_points argument for multiple Click CLI functions?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49842965
tagged with: python
tagged with: command-line-interface
has body: I'm trying to configure setuptools and Click module for multiple functions. Click documentation instructs in Nesting Commands section to use click.group(). How do you write the entry_points for multiple CLick CLI functions? I was toying with they syntax, and I managed to get something working but I can't recreate it. I was something like this, entry_points=''' [console_scripts] somefunc=yourscript:somefunc morefunc=yourscript:morefunc ''' Following the sample given below, I converted the syntax to a dictionary: entry_points= {'console_scripts': ['somefunc = yourscript:somefunc', 'morefunc = yourscript:morefunc' ]}, After I reinstalled, calling the script raised this error: (clickenv) &gt; somefunc Traceback (most recent call last): [...] raise TypeError('Attempted to convert a callback into a ' TypeError: Attempted to convert a callback into a command twice. The way I made this work the first time, was I installed the script, and then gradually changed the code through the various examples. At one point, just as described in the docs, I called the script with $ yourscript somefunc. However, when I recreated the pattern in my project I got that error. Here I've uninstalled and reinstalled (even though its advertised as unnecessary, pip install -e .) and removed the second entrypoint. Here's my testing example. The function morefunc requires a .txt input file. # yourscript.py import click @click.command() @click.group() def cli(): pass @cli.command() def somefunc(): click.echo('Hello World!') @cli.command() @click.argument('input', type=click.File('rb')) @click.option('--saveas', default='HelloWorld.txt', type=click.File('wb')) def morefunc(input, saveas): while True: chunk = input.read(1024) if not chunk: break saveas.write(chunk) # setup.py from setuptools import setup setup( name='ClickCLITest', version='0.1', py_modules=['yourscript'], install_requires=[ 'Click', ], entry_points= {'console_scripts': ['somefunc = yourscript:somefunc']}, )
tagged with: python-click
upvote count: 2
score: 1
tagged with: setuptools
answer count: 1
downvote count: 1
favorite count: 0
type: Question

octave
tags question: http://stackoverflow.com/q/49810184
tag name: octave
type: Tag

http://stackoverflow.com/a/49821850
upvote count: 3
score: 3
downvote count: 0
has body: This is because you’re looping twice. Remove the second forloop: {% for x in block.value %}. value should be accessible without the extra loop. You can get the image in your template using value.image instead of x.image
type: Answer
has comment: http://stackoverflow.com/comment/98681717
answers question: http://stackoverflow.com/q/49819776
has comment: http://stackoverflow.com/comment/86659337

http://stackoverflow.com/comment/86703028
has text: Output of encoded after the second Conv2D becomes (None, 60, 60, 32). For concatenate to merge the two outputs together they must same shape except in 1 axis. 60*32 is reshaped into (14, 60, 32), which lets us concat on axis 1. If this solution answers your question, please consider marking it as accepted.
comment on: http://stackoverflow.com/a/49833549
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86732429
score: 0
comment on: http://stackoverflow.com/q/49858760
type: Comment
type: QuestionComment
has text: pfff. Sigh. Thanks!

http://stackoverflow.com/comment/86590482
type: AnswerComment
has text: if a == b & a==20 then the first acomputation will be b & a(11110 & 10100 = 10100) 20. the if condition cheks a == 20 == 20 so the condition becomes true. if b == a & a==20 then the first action will be a & a( 10100 & 10100 = 10100). the if condition checks b == 20 == 20 so the condition becomes false
comment on: http://stackoverflow.com/a/49767532
score: 1
type: Comment

http://stackoverflow.com/q/49842999
has comment: http://stackoverflow.com/comment/86700900
has comment: http://stackoverflow.com/comment/86701158
has comment: http://stackoverflow.com/comment/86700697
has comment: http://stackoverflow.com/comment/86702397
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/32185411
has comment: http://stackoverflow.com/comment/86700751
has title: Matplotlib: multiple boxplot with (multiple) broken axis
score: 0
answer count: 2
has body: First of all I show you what I need: I need a boxplot with broken x-axis, possibily more than a single break. An example is this figure Now: I have two list of the form X and Y ( X = float, Y = int). First I group Y in sublists according to the integer part of X (X and Y are the same length): number_of_units = int(max(X)) + 1 my_data = [] for i in range(number_of_units): my_data.append([]) for i in range(len(X)): j = int(X[i] ) my_data[j].append(Y[i]) In this way my_data is a list of lists, with number_of_units sublists. The k-th subslist contains all the X values that are associated to Y values whose integer part is k. Here the problem: most of the subslists are empty: Y spans many orders of magnitude and typical values of number_of_units is 10^5, but most of the Y have integer part in [1,10] so that most of the sublists in my_data are empty. The direct consequence is that if I do fig, ax = plt.subplots() ax.boxplot(my_data, 'options') I obtain something like the following figure (note the "upper-right" red point): This is due to the emptyness of most of the sublists in my_data: most of the plot shows "zero-frequency". So what I need is to break the x-axis of the plot whenever the frequency is zero. Note that: The points where the ax has to be broken must be found dynamically, since they change with the data. There are very high chances that the ax has to be broken multiple times Theoretical idea Split the list my_data into M lists of lists, where the split has to be done according to the emptyness of my_data: if my_data[k] is the first empty sublist, than my_data[0],...,my_data[k-1] is the first group; then find the first non empty sublist with index &gt;k and there the second group begins. When I find another empty sublists, the second group is formed and so on. I hope I was clear. Do a ax.boxplot() for each of the new list of lists. This time none of the sublists will be empty. Plot each ax as subplots and join all the subplots as suggested here. This approach h…
linked to: http://stackoverflow.com/q/4842956
has comment: http://stackoverflow.com/comment/86701335
has comment: http://stackoverflow.com/comment/86701348
has comment: http://stackoverflow.com/comment/86701403
has comment: http://stackoverflow.com/comment/86702227
has answer: http://stackoverflow.com/a/49945698
has answer: http://stackoverflow.com/a/49848255
possible better answer: http://stackoverflow.com/a/49848255
accepted answer: http://stackoverflow.com/a/49945698
has comment: http://stackoverflow.com/comment/86701180
has comment: http://stackoverflow.com/comment/86700829
type: Question
tagged with: matplotlib
tagged with: boxplot
tagged with: python
has comment: http://stackoverflow.com/comment/86701001
linked to: http://stackoverflow.com/q/12319796

http://stackoverflow.com/q/49833346
answer count: 1
upvote count: 1
downvote count: 1
tagged with: jetbrains-ide
favorite count: 0
has body: This is my code def position_list(db,limit=10): """Return a list of positions ordered by date db is a database connection return at most limit positions (default 10) Returns a list of tuples (id, timestamp, owner, title, location, company, description) """ cursor = db.cursor() sql = "Select id, timestamp, owner, title, description From positions order by timestamp desc limit 10" cursor.execute(sql) result =[] for row in cursor: result.append(row[0]) result.append(row[1]) result.append(row[2]) result.append(row[3]) result.append(row[4]) return result This is the test I have to pass: def test_position_list(self): """Test that position_list returns positions""" # first get all positions positions = interface.position_list(self.db, limit=1000) self.assertEqual(len(self.positions), len(positions)) # validate the returned values self.assertEqual(1, positions[0][0]) self.assertEqual('2018-03-07 22:36:19', positions[0][1]) # can't check owner as it is randomly assigned self.assertEqual('Staff Site Reliability Engineer ', positions[0][3]) def test_position_list_limit(self): """Test that position_list returns positions using the limit argument""" # now look at the limit argument positions = interface.position_list(self.db, limit=3) self.assertEqual(3, len(positions)) positions = interface.position_list(self.db, limit=1) self.assertEqual(1, len(positions)) # limit higher than number of positions positions = interface.position_list(self.db, limit=100) self.assertEqual(50, len(positions)) When I try to run the unit test I get Type error: 'int' object is not subscriptable. This is due to the row[0] value of id which is an integer. How do I fix this?. Also can someone tell me how can I pass the def test_position_list_limit(self)?
type: AnsweredQuestion
tagged with: database
tagged with: python
has title: I am getting an error in Python which goes like 'int' object not subscriptable error in JetBrains PyCharm
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/49836148
has answer: http://stackoverflow.com/a/49836148

http://stackoverflow.com/comment/86700929
has text: Im afraid I dont really understand what you want to do. How would you reduce the length of the variable if it needs to contain a certain amount of elements?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49843170

http://stackoverflow.com/q/49800659
tagged with: pandas
has answer: http://stackoverflow.com/a/49800757
answer count: 1
has title: Convert dataframe to dict?
linked to: http://stackoverflow.com/q/26716616
type: Question
duplicate of: http://stackoverflow.com/q/26716616
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86616160
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86616310
has comment: http://stackoverflow.com/comment/86616155
tagged with: dictionary
has body: I have the following data structure (called df): x Fx Fxcum 0 -1.192809 0.888734 0.888734 1 -1.182809 0.483803 1.372537 2 -1.172809 -0.318153 1.054384 3 -1.162809 -0.966345 0.088038 4 -1.152809 -1.512387 -1.424349 The titles x, Fx, and Fxcum are dynamic. If I apply the function tolist(): dict(y=df['x'].tolist()) I get: {'x': [-1.192809, -1.182809, -1.172809, -1.162809, -1.152809]} First of all I need to read the titles that are not always x, Fx, and Fxcum and get the following list: {'x': [-1.192809, -1.182809, -1.172809, -1.162809, -1.152809], 'Fx': [-1.192809, -1.182809, -1.172809, -1.162809, -1.152809], 'Fxcum': [-1.192809, -1.182809, -1.172809, -1.162809, -1.152809]} Can you point me in the right direction. Do I need to create a loop or are there some libraries that can help me out?
score: 0

http://stackoverflow.com/comment/86708298
score: 0
type: AnswerComment
has text: Sir, is there a way we can assign the `id` of Question as slug or we can redirect user without saving the form if `slug = ' '` ?
type: Comment
comment on: http://stackoverflow.com/a/49845966

http://stackoverflow.com/a/49800895
score: 1
has body: Try using a dictionary, heres is an example code: Here i'm entering values to my dictionary my_dict = {'Ariel':578.9, 'Callisto': 2410.3, 'Ceres':481.5} You can also insert values to the dictionary as follows: my_dict['Chairos'] = 6.2 And you can access them by specifying the desire key: primary_body_radius = my_dict['Ariel'] &gt;&gt; print(primary_body_radius) &gt;&gt; 578.9
type: Answer
answers question: http://stackoverflow.com/q/49800701
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49884072
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/86784302
has comment: http://stackoverflow.com/comment/86784237
favorite count: 0
linked to: http://stackoverflow.com/q/27517425
type: Question
upvote count: 2
score: 2
possible better answer: http://stackoverflow.com/a/49884339
downvote count: 0
has answer: http://stackoverflow.com/a/49884339
has comment: http://stackoverflow.com/comment/86784368
has comment: http://stackoverflow.com/comment/86784453
has answer: http://stackoverflow.com/a/49884553
accepted answer: http://stackoverflow.com/a/49884553
has title: python pandas find transacctions of the same amount
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86784300
tagged with: pandas
has body: I have a pandas dataframe as below. d = {'emp': ['a', 'a', 'a', 'b', 'b', 'b'], 'vendor': ['x', 'x', 'y', 'z', 'z', 'z'], 'date': [1,1,2,3,3,3], 'amount': [4.9, 4.8, 1, 6, 5.6, 5.4]} df = pd.DataFrame(data=d) df["rounds"]=np.ceil(df['amount']) df amount date emp vendor rounds 0 4.9 1 a x 5.0 1 4.8 1 a x 5.0 2 1.0 2 a y 1.0 3 6.0 3 b z 6.0 4 5.6 3 b z 6.0 5 5.4 3 b z 6.0 I want to create the example column which would have a unique number if the same emp has spent the same amount (column rounds) at the same vendor on the same day. an employee could have multiple transactions matching this criteria or they could have 0 transactions matching this criteria how could i proceed? example 1 1 2 2 2 when a number is same in the example column, it indicates that all transactions that fall in one group update 1 another example if my dataframe is like below d = {'emp': ['a', 'a', 'a', 'a', 'b', 'b'], 'vendor': ['x', 'x', 'y', 'y', 'z', 'z'], 'date': [1,1,2,2,3,3], 'amount': [4.9, 4.8, 1, 1, 5.6, 5.4]} then column example should have values '1,1,2,2,3,3'
has comment: http://stackoverflow.com/comment/86784439
has answer: http://stackoverflow.com/a/49884672
has answer: http://stackoverflow.com/a/49884395

http://stackoverflow.com/a/49881067
answers question: http://stackoverflow.com/q/49879976
type: Answer
score: 0
has body: This would require multiple assigns but it does the job: values = ['val1', 'val2', 'val3'] results = df.val1 * df.val2 * df.val3 df = df.assign(Issue=np.where(mask, 'sth', '')).assign(Type=np.where(mask, 'sth', '')).assign(Value=np.where(mask, results, '')) Value will be str automatically due to value of other argument in np.where.

http://stackoverflow.com/q/49905171
type: Question
answer count: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/49906599
downvote count: 0
accepted answer: http://stackoverflow.com/a/49905229
tagged with: python
has title: python - extract a part of each line from text file
has answer: http://stackoverflow.com/a/49905229
score: 2
type: AnsweredQuestion
tagged with: file
has body: I have a test.txt file that contains: yellow.blue.purple.green red.blue.red.purple And i'd like to have on output.txt just the second and the third part of each line, like this: blue.purple blue.red Here is python code: with open ('test.txt', 'r') as file1, open('output.txt', 'w') as file2: for line in file1: file2.write(line.partition('.')[2]+ '\n') but the result is: blue.purple.green blue.red.purple How is possible take only the second and third part of each line? Thanks
has answer: http://stackoverflow.com/a/49906599
favorite count: 0

http://stackoverflow.com/q/49854214
has comment: http://stackoverflow.com/comment/86731439
accepted answer: http://stackoverflow.com/a/49980800
tagged with: python
score: -1
has body: i want my program to capture image after countdown ends. But during the countdown, i want it to show me the live cam. This is my code. import cv2 import time cam = cv2.VideoCapture(0) countdown=3 img_counter = 0 cv2.namedWindow("test") ret, frame = cam.read() cv2.imshow("test", frame) img_name = "example.png" while countdown &gt;0: time.sleep(1) print(countdown) countdown -=1 if countdown == 0: cv2.imwrite(img_name, frame) print("{} written!".format(img_name)) cam.release() cv2.destroyAllWindows()
downvote count: 1
has answer: http://stackoverflow.com/a/49980800
tagged with: opencv
type: AnsweredQuestion
tagged with: python-2.7
has title: Python, Capture image after countdown ends using webcam
has comment: http://stackoverflow.com/comment/86731084
favorite count: 0
type: Question
upvote count: 0
answer count: 1

http://stackoverflow.com/a/49820326
type: Answer
downvote count: 0
has body: This answer is not about string concatenation, but about simple problem solution... Instead of clicking particular link on pagination you can click "Next" button: pages_number = 10 for _ in range(pages_number): driver.find_element_by_xpath("//a[@title='Go to next page']").click() time.sleep(30) If you need to open specific page you can use below: required_page = 3 driver.find_element_by_link_text(required_page).click() P.S. I assumed you are talking about this site
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49819714

http://stackoverflow.com/q/49830020
has title: Syntax error from handling write to new file from a list
possible better answer: http://stackoverflow.com/a/49830298
type: Question
has answer: http://stackoverflow.com/a/49830298
has comment: http://stackoverflow.com/comment/86675171
tagged with: python
accepted answer: http://stackoverflow.com/a/49830038
has answer: http://stackoverflow.com/a/49830038
type: AnsweredQuestion
score: 0
has body: So I want to write a program that writes 10 random numbers into a text file: import random SIZE = 10 for i in range (0, SIZE, 1): y = random.randrange(0,100) x = open("data.txt","w+") x.write("\n") for i in range (0, SIZE, 1): x.write("Results: %d", %(y)) x.close() I got a syntax error in the "%(y)". But I have no idea what causes it.
answer count: 2

http://stackoverflow.com/a/49834103
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/86683547
accepted answer of: http://stackoverflow.com/q/49833874
score: 1
has body: You're accessing the entire column px['first'] from inside the loop that's intended to access only one entry at a time. To fix your current loop, it might be enough just to change px['first'] to row['first'], and also px['second'] to row['second']. Better would be to replace this manual looping with equivalent pandas expressions, which will be much faster and readable. If you post the full code (edit into question, not as comments!), we might be able to help.
has comment: http://stackoverflow.com/comment/86683697
answers question: http://stackoverflow.com/q/49833874
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49846661
has title: KeyError 3 in python when more dictionaries are added
tagged with: keyerror
has comment: http://stackoverflow.com/comment/86708597
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49846898
accepted answer: http://stackoverflow.com/a/49846898
tagged with: python
score: -1
has body: I wrote the following code. The code is running well. But when I add yt[i]=y[i-1]+delta(R1,R2) it gets an error: yt[i]=y[i-1]+delta(R1,R2) KeyError: 1 the function a is just an example and is not the real one. import numpy as np import math from math import * x = { 0: 0.3 } xt = {} N=10 y = { 0: 0.2 } yt = {} def a(z,s): return sqrt(z)+s def delta(r1,r2): sig=0.055 d=sig*(np.sqrt(-2*np.log(r1))*np.cos(np.radians(r2))) return d for i in range(1,N): R1=np.random.uniform(0,1) R2=np.random.uniform(0,1) R3=np.random.uniform(0,1) xt[i]=x[i-1]+delta(R1,R2) yt[i]=y[i-1]+delta(R1,R2) if a(xt[i],yt[i])&gt;R3: x[i]=xt[i] print('f') else: x[i]=x[i-1] print('s') print(x[i], delta(R1,R2), i) I appreciate your help.
has comment: http://stackoverflow.com/comment/86708285
type: Question
upvote count: 0
tagged with: random
answer count: 1
has comment: http://stackoverflow.com/comment/86708523
downvote count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/86708355
has comment: http://stackoverflow.com/comment/86708387
has comment: http://stackoverflow.com/comment/86708703
favorite count: 0

http://stackoverflow.com/comment/86769267
score: 0
comment on: http://stackoverflow.com/q/49852061
type: QuestionComment
has text: also added "image_data_format": "channels_first" to keras json file,still not working
type: Comment

http://stackoverflow.com/a/49802038
has comment: http://stackoverflow.com/comment/86619828
accepted answer of: http://stackoverflow.com/q/49801952
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86619575
answers question: http://stackoverflow.com/q/49801952
has body: This is one way. df['NUMBERS'] = df['NUMBERS'].apply(lambda x: [x]) However, this is discouraged unless you have a very specific reason, since you lose the vectorisation benefits of pandas. To control behaviour when your value is np.nan: df = pd.DataFrame({'NUMBERS': list(range(1, 8))}) df['NUMBERS'] = df['NUMBERS'].apply(lambda x: [int(x)] if not pd.isnull(x) \ in (6, 8) else np.nan)
has comment: http://stackoverflow.com/comment/86619046
has comment: http://stackoverflow.com/comment/86618982
has comment: http://stackoverflow.com/comment/86619655
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86618755
upvote count: 4
has comment: http://stackoverflow.com/comment/86645162
score: 4
has comment: http://stackoverflow.com/comment/86619107

http://stackoverflow.com/comment/86760890
comment on: http://stackoverflow.com/q/49872752
has text: [Delete substrings from your list](https://stackoverflow.com/questions/22221878/python-delete-substrings-from-list-of-strings) and then [count the occurences](https://stackoverflow.com/questions/2600191/how-to-count-the-occurrences-of-a-list-item) of what's left. These are really two completely independent problems.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/49880441
has body: I want to remove those tuples which had same values at index 0 except the first occurance. I looked at other similar questions but did not get a particular answer I am looking for. Can somebody please help me? Below is what I tried. from itertools import groupby import random Newlist = [] abc = [(1,2,3), (2,3,4), (1,0,3),(0,2,0), (2,4,5),(5,4,3), (0,4,1)] Newlist = [random.choice(tuple(g)) for _, g in groupby(abc, key=lambda x: x[0])] print Newlist my expected output : [(1,2,3), (2,3,4), (0,2,0), (5,4,3)]
upvote count: 7
type: Question
has answer: http://stackoverflow.com/a/49880585
has answer: http://stackoverflow.com/a/49880544
downvote count: 1
score: 6
has answer: http://stackoverflow.com/a/49883564
tagged with: python
duplicate of: http://stackoverflow.com/q/480214
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/49880585
has answer: http://stackoverflow.com/a/49880587
accepted answer: http://stackoverflow.com/a/49880587
has comment: http://stackoverflow.com/comment/86776899
linked to: http://stackoverflow.com/q/480214
has title: How can I remove duplicate tuples from a list based on index value of tuple while maintaining the order of tuple?
answer count: 5
has answer: http://stackoverflow.com/a/49880784

http://stackoverflow.com/comment/86794309
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49889085
has text: @Sehwag Glad to help!
type: Comment

http://stackoverflow.com/q/49870482
has comment: http://stackoverflow.com/comment/86756435
has title: In Python, is there a simple way to print a string given a list of characters with using str.join() method
type: UnansweredQuestion
tagged with: python
has body: Is there a simple way to print a string out of a list of characters without using str.join() method? For example, I have a list of chars: li = ['H', 'e', 'l', 'l', 'o'] I want to get 'Hello' printed out without using str.join() method: print(''.join(li))
downvote count: 6
tagged with: list
tagged with: printing
answer count: 3
has comment: http://stackoverflow.com/comment/86756557
upvote count: 0
has answer: http://stackoverflow.com/a/49870856
tagged with: string
score: -6
has comment: http://stackoverflow.com/comment/86756243
has answer: http://stackoverflow.com/a/49870849
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49870553
has comment: http://stackoverflow.com/comment/86756266

http://stackoverflow.com/comment/87058850
comment on: http://stackoverflow.com/a/49899582
type: AnswerComment
score: 0
type: Comment
has text: Thanks for the reply. Is there any particular way to do things you suggested? like have you tried it before or do you know any links where I can find it.

http://stackoverflow.com/comment/86830002
score: 1
comment on: http://stackoverflow.com/a/49907046
type: Comment
has text: You shouldn't use wildcard imports if you want to comply with PEP 8: https://legacy.python.org/dev/peps/pep-0008/#imports
type: AnswerComment

http://stackoverflow.com/comment/86750299
comment on: http://stackoverflow.com/q/49867110
has text: You're trying to use string indexing on an integer, and then converting that to a `float`. You've entirely confused the Python parser. Break this down into individual operations; when you have the correct output from that, *then* combine them into one line.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86715944
type: Comment
type: QuestionComment
has text: Thanks for the reply, but how should i add "round(number, precision)" command into the list as the list is combine with "text,value,value", sorry that im very new and complete stupid to python code. @Vj
comment on: http://stackoverflow.com/q/49850625
score: 0

http://stackoverflow.com/a/49778367
has body: I think you want the * operator in your function call, like so: def rt1(*args): print f.__name__ print args return f(*args) This way, the parameters to rt1 will be packed into args, and then unpacked in the call to f(*args). Reference: What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
upvote count: 1
answers question: http://stackoverflow.com/q/49778093
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86572333
score: 1

http://stackoverflow.com/q/49798451
favorite count: 0
type: Question
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49798710
accepted answer: http://stackoverflow.com/a/49798710
tagged with: numpy
type: AnsweredQuestion
downvote count: 0
tagged with: array-broadcasting
has title: Python: Would vectorization/broadcasting boost speed?
upvote count: 1
has body: GOAL: Merge arrays p1 to p10 to create one large array named 'a' and return all values in 'a' that appear in 'a', 4 times. Question: This code is super slow because of all the looping to be done, How can I make it swifter? Would vectorization and/or broadcasting aid in efficiency (Is it possible to get rid of all that looping) ? Or any other out of the box ideas for swiftness? import numpy as np import itertools from numba import jit p1 = np.random.randint(0,314000,200000) p2 = np.random.randint(0,314000,100000) p3 = np.random.randint(0,314000,300000) p4 = np.random.randint(0,314000,150000) p5 = np.random.randint(0,314000,220000) p6 = np.random.randint(0,314000,320000) p7 = np.random.randint(0,314000,212100) p8 = np.random.randint(0,314000,100500) p9 = np.random.randint(0,314000,300700) p10 = np.random.randint(0,314000,200300) @jit def count(a,n): counters=np.zeros(10**6,np.int32) for i in a: counters[i] += 1 res=np.empty_like(counters) k = 0 for i,j in enumerate(counters): if j == n: res[k] = i k += 1 return res[:k] for t in range(0, 20000): a = itertools.chain(p1,p2,p3,p4,p5,p6,p7,p8,p9,p10) count(a,4)
answer count: 1
tagged with: loops
tagged with: vectorization

http://stackoverflow.com/a/49814837
answers question: http://stackoverflow.com/q/49814554
score: 0
has body: Comprehension will do it as well: resultsets = [[sc[t]/10 for t in years] for sc in scenarios]
has comment: http://stackoverflow.com/comment/86643797
has comment: http://stackoverflow.com/comment/86643846
type: Answer

http://stackoverflow.com/a/49821072
answers question: http://stackoverflow.com/q/49820707
type: Answer
has body: It turns out I needed to reload the module: mod = py.importlib.import_module('example'); py.importlib.reload(mod);
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49820707

http://stackoverflow.com/a/49954060
has comment: http://stackoverflow.com/comment/86938928
has comment: http://stackoverflow.com/comment/86938955
score: 1
accepted answer of: http://stackoverflow.com/q/49905530
type: Answer
has body: So the issue that it doesn't work is not related to Selenium. It is because of localization. As you can see in your top bar REST OF THE WORLD and you are not in United States which should show you the US prices Below script shows how it works from selenium import webdriver driver = webdriver.Chrome() driver.get("https://www.lobstersnowboards.com/shop/eiki-pro-model--459") driver.find_element_by_css_selector("button[title='Rest of the World'] span.caret").click() driver.find_element_by_xpath("//li[.='United States']").click() import time time.sleep(4) driver.find_element_by_css_selector("div.options [title='Select'] span.caret").click() elems = driver.find_elements_by_css_selector("div.options ul &gt; li a span") for elem in elems: print(elem.text.strip()) I have used a dirty quick sleep, which you should not but that is just for the demo And below is the actual page in the chrome Somethings that will impact you later but not in Chrome 65 On January 19, 2017, a public posting to the mozilla.dev.security.policy newsgroup drew attention to a series of questionable website authentication certificates issued by Symantec Corporation’s PKI. Symantec’s PKI business, which operates a series of Certificate Authorities under various brand names, including Thawte, VeriSign, Equifax, GeoTrust, and RapidSSL, had issued numerous certificates that did not comply with the industry-developed CA/Browser Forum Baseline Requirements. During the subsequent investigation, it was revealed that Symantec had entrusted several organizations with the ability to issue certificates without the appropriate or necessary oversight, and had been aware of security deficiencies at these organizations for some time. From: https://security.googleblog.com/2017/09/chromes-plan-to-distrust-symantec.html The SSL certificate used to load resources from https://www.lobstersnowboards.com will be distrusted in M66. Once distrusted, users will be prevented from loading these resources. See https://g.co/chrome/sy…
answers question: http://stackoverflow.com/q/49905530
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86675125
comment on: http://stackoverflow.com/a/49829907
score: 0
has text: Haha yeah that's all it took! Thank you :) I can finally move on to the next part.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49839927
has body: I am splitting up my code into separate files, but have a problems with variables within the sub files (I am sure it's something simple, but cannot work out what is wrong. When I run the code I get an "UnboundLocalError: local variable 'avglightlevel' referenced before assignment" error. I thought the variables would be local to the sub file, I have tried using global variables in each file and still cannot it working. How do I a variable in the sub file to keep a running total of the avg values? #main.py import datacalc datacalc.init(0) #Read sensors &amp; process the data datacalc.complielightlevel(lightlevel) # delay for 10 seconds and keep repeat ====================================================== #datacalc.py def init(avg): avglightlevel = 0 avgCO2level = 0 avgtemperaturelevel = 0 #================================================ def complielightlevel(lightlevel): if(lightlevel &gt; 0): avglightlevel = avglightlevel + lightlevel
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/86694597
answer count: 1
has title: python global variable within sub files
linked to: http://stackoverflow.com/q/423379
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49840265
duplicate of: http://stackoverflow.com/q/423379
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/49842305
downvote count: 0
has comment: http://stackoverflow.com/comment/86699582
has comment: http://stackoverflow.com/comment/86699541
type: Answer
has body: There is no difference. You can check where python is running from by typing which python in bash. You'll see that it points to your virtual env when you're in it.
answers question: http://stackoverflow.com/q/49842217
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86699618

http://stackoverflow.com/q/49916315
tagged with: python-3.x
type: Question
tagged with: exception
type: UnansweredQuestion
tagged with: python
has body: I'm facing a strange bug. I have a parent process that spawns two child processes with infinite loops that provide different services. Each child shares a multiprocessing.manager.list() variable type with the parent process. All processes (parent and children) are fully encapsulated in try except finally blocks so I can catch and process various errors. I've even used the except Exception term as a final catch all term. In spite of all this, I am still getting the following error pop up regularly: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Program Files\Python35\lib\multiprocessing\spawn.py", line 100, in spawn_main new_handle = steal_handle(parent_pid, pipe_handle) File "C:\Program Files\Python35\lib\multiprocessing\reduction.py", line 86, in steal_handle _winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE) PermissionError: [WinError 5] Access is denied From the log file I produce, there's no sign of it coming from any of my processes (which is obvious given the traceback), and given what I see in the code this has no effect on the program. I'm under the impression that for the multiprocessing.Manager to function to work it needs to generate a separate process just for shuttling these variables around. The problem is that I really need to at least hide the error from the command prompt. A lot of information is being presented to the user there and stray errors popping up regularly is very distracting. I can't show code unfortunately as I'm at work, and as its many thousands of lines at the moment I'm not sure of the exact source of the bug. I will continue trying to narrow things down and if I do manage to create a small example I'll edit the question with it. Any ideas or suggestions would be greatly appreciated. Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32
tagged with: multiprocess
upvote count: 4
score: 4
has title: Permission error using multiprocessing in Python 3.5 with unknown origin
has comment: http://stackoverflow.com/comment/86918734
answer count: 0
downvote count: 0
favorite count: 0
tagged with: python-multiprocessing

http://stackoverflow.com/comment/86688123
comment on: http://stackoverflow.com/a/49836207
has text: Sorry it seems the format is incorrect in the comment. What I meant to say is that in @MohsinBukhari's solution the results are swapped, that is 0 is in place of 15 and vice versa.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86746359
type: Comment
type: QuestionComment
score: 0
has text: other link: https://github.com/Kaspazza/Python/blob/master/Hangman/Hangman.py
comment on: http://stackoverflow.com/q/49865394

http://stackoverflow.com/q/49875667
has answer: http://stackoverflow.com/a/49875777
type: AnsweredQuestion
tagged with: pandas
has body: I want to do some analysis on data I have scraped from a forum. This is the first time I'm doing something like this so it's possible that my method is wrong from the start but here is what I have at the moment. I have scraped 17k discussions, each of which contains a certain number of posts (for a total of 78k post). I have stored everything in a dataframe with 6 columns. Each row corresponds to a post, and the columns are respectively: 'thread_id', 'thread_length', 'thread_title', 'post_number', 'post content' ,'poster' As you can see the values that pertain to the thread (so title, id, and length) are repeated a lot of times: for example if a thread has 30 posts, its id, length and title will be repeated 30 times. My problem is: how can I plot an histogram of the thread lengths? I probably should only pick length values that have a different thread id value, but I can't figure out how to do it. Also I guess there has to be a 'cleaner' way to organize this dataframe, so I'm open to any advice.
score: 1
tagged with: python
favorite count: 0
type: Question
has title: How to deal with duplicate fields in a pandas dataframe?
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49875777
upvote count: 1

http://stackoverflow.com/comment/86578384
has text: So, iterating over all of the possible numbers in the range `[0, 5**k)`, for each iteration, iterating over `lst`, and comparing the int values of the strings in `lst`, each one that is equal to the current number will be appended to the list.That seems to work! Thanks :)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49781369

http://stackoverflow.com/comment/86780138
comment on: http://stackoverflow.com/q/49881929
score: 0
has text: @StefanFalk I am not sure whether it answers the question. I need to find the cosine similarity between vectors of each field. My array is (m,n,k) dimension not a (m,n) array
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86648325
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49792539
has text: why is it not valid?

http://stackoverflow.com/a/49893109
type: Answer
has body: Use Regex. import re string='@!#word ' print(re.sub('[^A-Za-z]+', '', string)) Output: word Use this if you need to remove special chars on the sides. Ex: import string s='@!#word ' print(s.rstrip(string.punctuation).lstrip(string.punctuation)) Output: word
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49893077
downvote count: 0
has comment: http://stackoverflow.com/comment/86802094

http://stackoverflow.com/comment/86749547
type: AnswerComment
has text: You may want to explain why the `b` is needed
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49866997

http://stackoverflow.com/comment/86832821
type: Comment
has text: You are a lifesaver, that fixes the issue
type: AnswerComment
comment on: http://stackoverflow.com/a/49907592
score: 0

http://stackoverflow.com/q/49809471
has comment: http://stackoverflow.com/comment/86633791
has comment: http://stackoverflow.com/comment/86728418
tagged with: shutil
favorite count: 0
has answer: http://stackoverflow.com/a/77815239
type: Question
score: 9
tagged with: python-3.x
has answer: http://stackoverflow.com/a/53492792
upvote count: 9
has comment: http://stackoverflow.com/comment/86633729
downvote count: 0
has answer: http://stackoverflow.com/a/51627661
tagged with: python
possible better answer: http://stackoverflow.com/a/53492792
answer count: 4
has body: My code: if os.path.exists(myDir): shutil.rmtree(myDir) os.mkdir(myDir) Problem: It always work if myDir does not exist. If myDir exists, sometimes it throws error, sometimes it works. Error log: os.mkdir(myDir) PermissionError: [WinError 5] Access is denied: 'myDir' My guess: when I call os.mkdir, sometimes shutil.rmtree hasn't finished execution/ hasn't released the permission for the directory. Hence, the error. Is there any way to ensure complete execution of shutil.rmtree before calling os.mkdir?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86633893
accepted answer: http://stackoverflow.com/a/52194842
has answer: http://stackoverflow.com/a/52194842
has title: Overwrite directory with shutil.rmtree and os.mkdir sometimes gives 'Access is denied' error
has comment: http://stackoverflow.com/comment/86633650

http://stackoverflow.com/q/49819438
has comment: http://stackoverflow.com/comment/86656710
tagged with: python
type: Question
has title: How do I print inside the loss function during training in Keras?
answer count: 2
has answer: http://stackoverflow.com/a/49823563
has comment: http://stackoverflow.com/comment/86659393
has answer: http://stackoverflow.com/a/65982164
type: UnansweredQuestion
downvote count: 0
upvote count: 21
tagged with: keras
tagged with: tensorflow
favorite count: 0
score: 21
has body: I am trying to create a loss function in Keras (Tensorflow Backend) but I am a little stuck to check the inside of the custom loss function. In fact, the print appears on the console only when I compile the model, after that there is no print. (I am just testing very simple custom function, I will create the true function when I solved this problem). I train the model using the train_on_batch function. How can I solve this problem? def loss_yolo(self, y_true, y_pred): print('inside loss function') loss = K.mean(y_true - y_pred) return loss model.compile(optimizer='sgd', loss=loss_yolo) print('train on batch') print(model.train_on_batch(x, y)) And the output is inside loss function train on batch -0.481604

python-mss
type: Tag
tag name: python-mss
tags question: http://stackoverflow.com/q/49841971

linguistics
tags question: http://stackoverflow.com/q/49764572
tag name: linguistics
type: Tag

http://stackoverflow.com/comment/86801409
score: 0
type: Comment
has text: thanks its working negi ji
type: AnswerComment
comment on: http://stackoverflow.com/a/49892955

tensorboard
tags question: http://stackoverflow.com/q/49865478
tags question: http://stackoverflow.com/q/49787924
type: Tag
tags question: http://stackoverflow.com/q/49798531
tags question: http://stackoverflow.com/q/49817131
tags question: http://stackoverflow.com/q/49776618
tags question: http://stackoverflow.com/q/49779136
tag name: tensorboard
tags question: http://stackoverflow.com/q/49890477

http://stackoverflow.com/a/49881467
type: Answer
has comment: http://stackoverflow.com/comment/86783848
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49881299
downvote count: 0
type: AcceptedAnswer
has body: I believe need: for k, v in paper_topics_dict.items(): topic_count_timeline.loc[k] = v for k, v in count_dict.items(): topic_count_timeline[k] *= v print (topic_count_timeline) 2012 2013 2014 2015 2016 ecology 7 14 8.4 5.6 6.3 evolution NaN NaN NaN NaN NaN mathematics NaN NaN NaN NaN NaN biogeography NaN NaN NaN NaN NaN neutral theory 3 6 3.6 2.4 2.7 But if working with dictionary pairs better is for each pair update defaultdict, then convert it to Series, for DataFrame add unstack and reindex for missing columns and index values: from collections import defaultdict count_dict = {2012: 10, 2013: 20, 2014: 12, 2015: 8, 2016: 9} paper_topics_dict = {'ecology': 0.7, 'neutral theory': 0.3} count_dict2 = {2012: 3, 2013: 2, 2014: 15, 2015: 16, 2016: 13} paper_topics_dict2 = {'mathematics': 0.6, 'neutral theory': 0.4} L = [(count_dict, paper_topics_dict), (count_dict2, paper_topics_dict2)] d = defaultdict(float) for a, b in L: for k, v in b.items(): for k2, v2 in a.items(): d[(k, k2)] += v*v2 df = pd.Series(d).unstack().reindex(index=topics, columns=range_of_years) print (df) 2012 2013 2014 2015 2016 ecology 7.0 14.0 8.4 5.6 6.3 evolution NaN NaN NaN NaN NaN mathematics 1.8 1.2 9.0 9.6 7.8 biogeography NaN NaN NaN NaN NaN neutral theory 4.2 6.8 9.6 8.8 7.9
answers question: http://stackoverflow.com/q/49881299
has comment: http://stackoverflow.com/comment/86783958

http://stackoverflow.com/q/49869769
tagged with: python-asyncio
tagged with: python
tagged with: asynchronous
has body: I am trying to request a bunch of URLs concurrently however the URLs are built from a list. Currently I am looping over the list and (I think) adding them to the queue as it happens. It is definitely 10x faster than requests.get, however I am not sure I am doing it correctly and so it can be optimized. I profiled it and noticing it is still locking 90% of the time after the concurrent requests are done i.e start -> 10+ concurrent requests -> lock for 5 seconds or so -> done Additionally, this code results in a Unclosed client session message at the end. Any idea why? Pretty sure this is using a context manager properly. I have searched and not found this exact question import signal import sys import asyncio import aiohttp import json import requests lists = ['eth', 'btc', 'xmr', 'req', 'xlm', 'etc', 'omg', 'neo', 'btc', 'xmr', 'req', 'xlm', 'etc', 'omg', 'neo'] loop = asyncio.get_event_loop() client = aiohttp.ClientSession(loop=loop) async def fetch(client, url): async with client.get(url) as resp: assert resp.status == 200 return await resp.text() async def main(loop=loop, url=None): async with aiohttp.ClientSession(loop=loop) as client: html = await fetch(client, url) print(html) def signal_handler(signal, frame): loop.stop() client.close() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) tasks = [] for item in lists: url = "{url}/{endpoint}/{coin_name}".format( url='https://coincap.io', endpoint='page', coin_name=item.upper() ) print(url) tasks.append( asyncio.ensure_future(main(url=url)) ) loop.run_until_complete(asyncio.gather(*tasks))
accepted answer: http://stackoverflow.com/a/49874816
type: Question
tagged with: aiohttp
downvote count: 0
answer count: 1
tagged with: python-requests
favorite count: 0
has answer: http://stackoverflow.com/a/49874816
type: AnsweredQuestion
upvote count: 3
score: 3
has title: How do I *properly* run an asyncio/aiohttp request in a loop?

http://stackoverflow.com/a/49916477
answers question: http://stackoverflow.com/q/49916371
has body: Use - iname = "name1" ipassword = "password1" iemail = "email@domain.com" df2 = df.append(pd.DataFrame(iname,ipassword,iemail, columns =df.columns)) df2.to_csv("login.csv", index=False) Output name password email 0 admin admin asdfs 1 zds sd dsssfsfd 2 vipul rao dsfdsfs 0 name1 password1 email@domain.com
has comment: http://stackoverflow.com/comment/86848328
upvote count: 9
has comment: http://stackoverflow.com/comment/86848361
type: Answer
score: 9
downvote count: 0

http://stackoverflow.com/a/49889708
has comment: http://stackoverflow.com/comment/86797645
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49888935
score: 2
answers question: http://stackoverflow.com/q/49888935
downvote count: 0
has body: First of all, what you can do is to define your own cost function over a whole batch instead of single inputs. Sticking with your circle example, you can do: inside_bool = ( tf.square( X_pred ) + tf.square( Y_pred ) ) &lt; tf.square( r ) inside_float = tf.cast( inside_bool, tf.float32 ) proportion_inside = tf.reduce_mean( inside_float ) loss = -tf.abs( proportion_inside - 0.5 ) Another question is what the input to such a network would be. I'd suggest you just start with a random tensor. (Basically, build a generative network.) If your loss function is not derivable, it will be hard to train. So I'd suggest replace the non-derivable parts with derivable approximates. Most importantly, the inside-outside boolean could be a large root of the distance from the perimeter instead (maintaining sign.) Taking a large root approaches it to one. (Raising to power 0 would be the sign basically.) You can also add a regularizer that likes values around one and negative one. (This would ruin the distribution of your coordinates, however, if that's a factor.) tf.abs() is not such a big problem, that's basically L1 regularization. So with all that, an idea could be (untested code): dist_from_perimeter = ( tf.square( X_pred ) + tf.square( Y_pred ) ) - tf.square( r ) dist_loss = tf.sign( dist_from_perimeter ) * tf.pow( tf.abs( dist_from_perimeter ), 0.2 ) # 0.2 for 5th root inside = tf.reduce_mean( dist_loss ) # 0-based now! loss = -tf.abs( inside ) This would force all the points on the perimeter, but the gradient will grow really large around the perimeter, so it's not likely to be able to stay there. They will oscillate inside-outside, but once the proportion settles down, they won't move much. (Or so I think... :) ) If you have things other than a circle, then you have to come up with a reasonably easily calculable distance metric that would put close to equal pressure on both X and Y coordinates. Hope all this helped! Wrote working code for this, albeit didn't investigate the in…
has comment: http://stackoverflow.com/comment/86810430

keystroke
type: Tag
tags question: http://stackoverflow.com/q/49910688
tag name: keystroke

http://stackoverflow.com/q/49758960
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49760408
downvote count: 0
answer count: 1
has title: how to automate manage transactions in SQL Alchemy
has body: When use java Hibernate &amp; Spring framework, there is a transaction manager which we can configure some transaction rules, then we don't need write "commit, flush, rollback" stuff each time.
has comment: http://stackoverflow.com/comment/86533856
has comment: http://stackoverflow.com/comment/86533279
has comment: http://stackoverflow.com/comment/86534282
accepted answer: http://stackoverflow.com/a/49760408
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86532976
tagged with: contextmanager
upvote count: 1
tagged with: transactions
score: 1
has comment: http://stackoverflow.com/comment/86533911
tagged with: python
tagged with: sqlalchemy

http://stackoverflow.com/a/49769298
downvote count: 0
has body: Answer to your first question. Python &amp; operator will be executed first than == operator(due to higher precedence) Answer to your second question. if a==b &amp; a==20: When you executed this expression internally this is what happened. if a==(b&amp;a)==20: The expression (b&amp;a) will give you the answer 20. So the expression is like this now. if a==(20)==20: # which is nothing but if a==20 and 20==20: Since a = 20,the expression becomes true and you get the if part executed. But when you interchanged a and be this is what actually happened. if b==(a&amp;a)==20: a&amp;a again will give you 20. So the expression becomes if b==(20)==20: # if b==20 and 20==20: Now b is not 20,its 30. So expression becomes False and else part gets executed.
answers question: http://stackoverflow.com/q/49767101
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/q/49813836
linked to: http://stackoverflow.com/q/576169
has answer: http://stackoverflow.com/a/49814311
tagged with: python
score: 0
type: Question
has body: I'm working on this ( right now really messy ) code for an exercise in my studies. After I've added the super(TetrisBoard, self).__init__() line to my code in the TetrisBoard __init__ method I keep getting the following error: # Error: Error when calling the metaclass bases # __init__() takes exactly 3 arguments (4 given) # Traceback (most recent call last): # File "&lt;maya console&gt;", line 4, in &lt;module&gt; # TypeError: Error when calling the metaclass bases # __init__() takes exactly 3 arguments (4 given) # I've tried reading around but I really can't seem to wrap my head around why this error happens and where the extra argument comes from. Here is my code: import math from abc import ABCMeta, abstractmethod class Point(object): def __init__(self, x, y): super(Point, self).__init__() self.x = x self.y = y def rotatePoint(self, centerOfRotation, radians): coordinateRelativeToCenter = Point.pointOnNewPlane(self, centerOfRotation) newRelativeX = round(coordinateRelativeToCenter.x * math.cos(radians) - coordinateRelativeToCenter.y * math.sin(radians)) newRelativeY = round(coordinateRelativeToCenter.x * math.sin(radians) + coordinateRelativeToCenter.y * math.cos(radians)) coordinateRelativeToOrigin = Point.pointOnNewPlane(Point(newRelativeX, newRelativeY), Point(-centerOfRotation.x, -centerOfRotation.y)) self.x = coordinateRelativeToOrigin.x self.y = coordinateRelativeToOrigin.y def translatePoint(self, translateX, translateY): self.x += translateX self.y += translateY @classmethod def pointOnNewPlane(cls, point, origin): resultPoint = Point(point.x, point.y) resultPoint.x -= origin.x resultPoint.y -= origin.y return resultPoint def getX(self): return self.x def getY(self): return self.y class GameObjectManager(object): _gameObjects = [None] _freeId = 0 @classmethod def nextId(cls): id = cls._freeId cls._updateFreeId() return id @classmethod def _updateFreeId(cls): try: cls._freeId = cls._gameObjects[cls._freeId:].index(None) except ValueError: cls._gameObjects.…
type: UnansweredQuestion
has title: Type Error when calling the metaclass bases
answer count: 1

http://stackoverflow.com/comment/86742791
has text: @pault: Really? What's the semantics for `size`? The author doesn't say.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49863358

http://stackoverflow.com/q/49888258
has body: I have the following dataframe: Jack Joe Mary 1 I O O 2 I O I 3 I I I 4 O I I 5 O I O 6 I O O 7 I O I 8 I O I 9 O I I 10 O I O .... My columns have patterns of 'I I I' and 'O O O' dispersed throughout. I want to count the number of occurrences of 'I I I' and 'O O O' in each column. I know I can iterate through each row of each column but this is a very large dataframe. Does anyone have 1) a more efficient way to do this and 2) a more pythonic way to do this? Thanks.
tagged with: pandas
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49889353
upvote count: 1
tagged with: iteration
has answer: http://stackoverflow.com/a/49888653
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49888381
has answer: http://stackoverflow.com/a/49888381
tagged with: python
possible better answer: http://stackoverflow.com/a/49888653
has title: Counting Pattern Occurrences in a Large Data frame without Iterating Python Pandas
answer count: 4
has answer: http://stackoverflow.com/a/49890582
type: AnsweredQuestion

http://stackoverflow.com/a/49888608
has comment: http://stackoverflow.com/comment/86793421
accepted answer of: http://stackoverflow.com/q/49887970
has comment: http://stackoverflow.com/comment/86793759
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86793318
has comment: http://stackoverflow.com/comment/86793658
has comment: http://stackoverflow.com/comment/86793401
answers question: http://stackoverflow.com/q/49887970
score: 3
upvote count: 3
type: Answer
has body: What is your sample frequency? This sequence you are generating can represent a infinite number of continuous time signals according to the sample frequency. The sample frequency needs to be at least twice the maximum signal frequency, as stated by the Sampling Theorem, so, using fs = 250Hz and using a sine of 10 seconds it becomes: import matplotlib.pyplot as plt import numpy as np fs = 250 t = np.arange(0, 10, 1/fs) sp = np.fft.fft(np.sin(2*np.pi * 100 * t)) trange = np.linspace(0, fs, len(t)) plt.plot(trange, np.abs(sp)) plt.show() If you run this you will see a peak at 100Hz as expected.
has comment: http://stackoverflow.com/comment/86793358

http://stackoverflow.com/comment/86617110
comment on: http://stackoverflow.com/q/49788330
type: QuestionComment
score: 0
has text: That is not a [mcve]. You need to provide data and the code you wrote to actually reproduce the problem. You are using pipe-character `|` as a delimiter? I cannot reproduce your problem with semicolons. Indeed, I still don't understand what, exactly, your problem is.
type: Comment

http://stackoverflow.com/comment/86632201
type: Comment
comment on: http://stackoverflow.com/q/49808639
score: 0
type: QuestionComment
has text: Hash lengths cannot be arbitrary as that would increase the chance of collisions. Imagine specifying a hash length of 1 as a boundary case.

http://stackoverflow.com/q/49787559
has title: name 'fetched_tweets_filename' is not defined
tagged with: python
tagged with: tweepy
type: Question
has answer: http://stackoverflow.com/a/49787726
score: 0
has body: Unclear what's going wrong here. From what I see I have defined the fetched_tweets_filename variable above. I pass in fetched_tweets_filename to the initialization of the instance listener of the StdOutListener class. Receiving the following error: Traceback (most recent call last): File "twitter_scraper.py", line 51, in &lt;module&gt; main() File "twitter_scraper.py", line 39, in main listener = StdOutListener(fetched_tweets_filename) File "twitter_scraper.py", line 20, in __init__ self.fetched_tweets_filename = fetched_tweets_filename NameError: name 'fetched_tweets_filename' is not defined I define fetched_tweets_filename right above it. I am not the most experienced Python programmer so I may be doing something obvious. from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import twitter_credentials class StdOutListener(StreamListener): #basic class that prints received tweets to stdout def __init__(self, scraped_tweets_filename): self.fetched_tweets_filename = fetched_tweets_filename def on_data(self, data): try: print(data) with open(self.fetched_tweets_filename, 'a') as tf: tf.write(data) return True except BaseException as e: print("Error on_data: %s" % str(e)) return True def on_error(self,status): print(status) def main(): hash_tag_list = ["Greenpoint", "Williamsburg", "Boerum Hill", "Brooklyn Heights", "Brooklyn Navy Yard", "Clinton Hill", "Dumbo", "Fort Greene", "Fulton Ferry", "Fulton Mall", "Vinegar Hill", "BedStuy", "Bedford-Stuyvesant", "Bedford Stuyvesant", "Ocean Hill", "Stuyvesant Heights", "Bushwick"] fetched_tweets_filename = "tweets_scraped.json" listener = StdOutListener(fetched_tweets_filename) auth = OAuthHandler(twitter_credentials.CONSUMER_KEY, twitter_credentials.CONSUMER_SECRET) auth.set_access_token(twitter_credentials.ACCESS_TOKEN, twitter_credentials.ACCESS_TOKEN_SECRET) stream = Stream(auth, listener) stream.filter(track=hash_tag_list) if __name__ == "__main__": main()
answer count: 1
accepted answer: http://stackoverflow.com/a/49787726
tagged with: python-3.x
type: AnsweredQuestion

http://stackoverflow.com/comment/86827670
type: QuestionComment
score: 0
type: Comment
has text: this is a example work for me: https://pastebin.com/FUaTg0ba
comment on: http://stackoverflow.com/q/49905732

deconvolution
type: Tag
tag name: deconvolution
tags question: http://stackoverflow.com/q/49833886

http://stackoverflow.com/q/49818842
score: 0
has comment: http://stackoverflow.com/comment/86656897
answer count: 1
accepted answer: http://stackoverflow.com/a/49821039
tagged with: python-requests
has answer: http://stackoverflow.com/a/49821039
type: Question
has comment: http://stackoverflow.com/comment/86656548
has body: What i want to accomplish is to grab data from API-endpoint and store it as CSV. Then import CSV file into SQLite database. I can fetch the data from API just fine and output in CSV file. But to store the data from CSV file into SQLite is the problem. I keep getting this error: Traceback (most recent call last): File "info.py", line 46, in &lt;module&gt; i['col1'], i['col2'], i['col3'], i['col4'], i['col5']) for i in dr] File "info.py", line 46, in &lt;listcomp&gt; i['col1'], i['col2'], i['col3'], i['col4'], i['col5']) for i in dr] KeyError: 'col1' I wonder why this error appears? If there any other solutions I'm gladly and open for help. The goal is to store the data from CSV file into SQLite database. Here is what i have so far: import requests import csv import sqlite3 con = sqlite3.connect("business.db") cur = con.cursor() cur.execute('DROP TABLE IF EXISTS firms') cur.execute( "CREATE TABLE firms (col1 PRIMARY KEY, col2 TEXT, col3 TEXT, " "col4 TEXT, col5 TEXT,...);" ) r = requests.get('http://url/url/url') outfile = open(r"C:\Users\...\test.csv", "w") outfile.write(r.text) with open(r'C:\Users\...\...\test.csv', 'r') as fin: dr = csv.DictReader(fin) to_db = [(i['col1'], i['col2'], i['col3'], i['col4'], i['col5'], ...) for i in dr] cur.executemany("INSERT INTO firms (col1, col2, col3, col4, col5, "...) VALUES (?, ?, ?, ?, ?, " "...);", to_db) con.commit() con.close() Output from this command (print(next(dr))): OrderedDict([('col1;"col2";"col3";"col4";"col5";"..."', 'value1;"value2"; "value3";"value4";"value5";"..."')])
has comment: http://stackoverflow.com/comment/86657059
has comment: http://stackoverflow.com/comment/86654012
has comment: http://stackoverflow.com/comment/86652506
has title: Trying to insert data into database but this error appears: KeyError: 'identifier' (Python)
has comment: http://stackoverflow.com/comment/86656206
has comment: http://stackoverflow.com/comment/86656302
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/86657978
type: AnsweredQuestion

http://stackoverflow.com/comment/115331436
score: 0
type: Comment
has text: I was trying to use a Convolutional network for a 1d problem. For those unadvised like me, please don't.. that's not the real purpose of this kind of algorithm
type: AnswerComment
comment on: http://stackoverflow.com/a/49847100

http://stackoverflow.com/q/49862092
has body: I have two pd.Series: &gt;&gt;&gt; a = pd.Series([1,2,3],index=[1,2,3]) &gt;&gt;&gt; b = pd.Series([2,3,4],index=[2,3,4]) I would like to subtract these two series according to the elements' .iloc, not the index, and then get back the index of the first (or second, I don't care, really) Series. Desired output: &gt;&gt;&gt; a - b 1 -1 2 -1 3 -1 dtype: float64 What actually comes out is: &gt;&gt;&gt; a - b 1 NaN 2 0.0 3 0.0 4 NaN dtype: float64
accepted answer: http://stackoverflow.com/a/49862126
has title: Pandas subtract series by iloc, not by index
tagged with: python
has answer: http://stackoverflow.com/a/49862126
has answer: http://stackoverflow.com/a/49862212
type: AnsweredQuestion
score: 3
answer count: 2
tagged with: pandas
upvote count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/49862212
favorite count: 0
type: Question

http://stackoverflow.com/a/49842389
has comment: http://stackoverflow.com/comment/86699702
has comment: http://stackoverflow.com/comment/86700827
has comment: http://stackoverflow.com/comment/86699871
has comment: http://stackoverflow.com/comment/86700007
has comment: http://stackoverflow.com/comment/86700160
type: Answer
has comment: http://stackoverflow.com/comment/86700077
has comment: http://stackoverflow.com/comment/86700054
has comment: http://stackoverflow.com/comment/86700261
has comment: http://stackoverflow.com/comment/86699399
score: 0
has comment: http://stackoverflow.com/comment/86699993
has comment: http://stackoverflow.com/comment/86704274
has comment: http://stackoverflow.com/comment/86699913
answers question: http://stackoverflow.com/q/49838002
has comment: http://stackoverflow.com/comment/86700082
has body: You can use a full XPath to select the item you want based on two conditions, you just need to start from a parent node and then apply the conditions on the child nodes: //div[contains(./h1/a/text(), "MLK") and contains(./p/a/text(), "Black")]/a/@href You first need to select the element itself, after that you need to get the attribute @href from the element, something like this: Item = driver.find_element_by_xpath('//div[contains(./h1/a/text(), "MLK") and contains(./p/a/text(), "Black")]/a') href = Item .get_attribute("href")
has comment: http://stackoverflow.com/comment/86699700
has comment: http://stackoverflow.com/comment/86700875
has comment: http://stackoverflow.com/comment/86701556
has comment: http://stackoverflow.com/comment/86700318

http://stackoverflow.com/comment/86592060
type: AnswerComment
comment on: http://stackoverflow.com/a/49769059
score: 0
type: Comment
has text: The division calculating the probability is using integer division. you can solve this by converting the elements of lmax to float either at assignment `(lmax.append(float(c3 if c3>c4 else c4)))` or at calculation as i suggested above.

http://stackoverflow.com/q/49840087
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49840222
has title: Sci-Kit Scaler and Inversion Does Not Yield Identical Numbers?
has answer: http://stackoverflow.com/a/49840222
has body: A bit new to Sci-kit, but noticing some behavior that seems a bit strange with minmax normalization and inversion (but maybe this is the intended behavior??). I thought when inverting I would re-generate the original datapoints - but instead the inversion generates numbers that are "close" but not quite equal ... is this supposed to happen, or have I messed something up? #previously imported data is in a 3 column df scaler = sklearn.preprocessing.MinMaxScaler() df_norm = df.copy() (df_norm == df).all() #RETURNS TRUE df_norm = scaler.fit_transform(df_norm) df_norm = scaler.inverse_transform(df_norm) (df_norm == df.values).all() #RETURNS FALSE So I'm just a bit puzzled why I have 2 identical dataframes, but after scaling and inverting the datasets are no longer equal? Many of the numbers are equal, but quite a few are not. Oddly, as shown below, some even look identical but are not showing up that way when testing with df_norm == df df: array([[17.21 , 17.21 , 17.23 , 17.16 ], [17.21 , 17.19 , 17.25 , 17.19 ], [17.185, 17.21 , 17.23 , 17.18 ], ..., [12.78 , 12.78 , 12.78 , 12.78 ], [12.78 , 12.78 , 12.78 , 12.78 ], [12.78 , 12.78 , 12.78 , 12.78 ]]) df_norm array([[17.21 , 17.21 , 17.23 , 17.16 ], [17.21 , 17.19 , 17.25 , 17.19 ], [17.185, 17.21 , 17.23 , 17.18 ], ..., [12.78 , 12.78 , 12.78 , 12.78 ], [12.78 , 12.78 , 12.78 , 12.78 ], [12.78 , 12.78 , 12.78 , 12.78 ]]) df == df_norm array([[ True, True, True, True], [ True, True, True, True], [ True, True, True, True], ..., [ True, True, False, True], [ True, True, False, True], [ True, True, False, True]])
tagged with: inversion
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86694806
downvote count: 0
upvote count: 1
tagged with: scikit-learn
tagged with: python
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86707717

http://stackoverflow.com/comment/86672193
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49828078
type: AnswerComment
has text: Appreciate it! If I have multiple lists that I want to add, can I use this?

http://stackoverflow.com/q/49851582
has title: Odoo opportunity new message uncheck recipient
has answer: http://stackoverflow.com/a/49856420
type: AnsweredQuestion
answer count: 2
tagged with: odoo-10
upvote count: 2
linked to: http://stackoverflow.com/q/49875355
possible better answer: http://stackoverflow.com/a/49856420
score: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49853643
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49853643
tagged with: crm
tagged with: odoo
tagged with: javascript
tagged with: python
has body: In Odoo when I open an opportunity from "My pipeline" and on that opportunity I press button "New message" then customer from that opportunity appears (along with followers of that oppportunity) as a receiver of that message: there is a checked checkbox near the name of that customer in the list of recipients for that message. This is because file addons/mail/static/src/xml/chatter.xml has this: <t t-foreach='widget.suggested_partners' t-as='recipient'> <t t-esc="recipient.name"/> <t t-if="recipient.email_address">(<t t-esc="recipient.email_address"/>)</t> </t> And hovering on the one of the unwanted recipients shows following message "Adds as recipient and follower (reason: Customer)". There is relevant source code in addons/crm/models/crm_lead.py @api.multi def _message_add_suggested_recipient(self, result, partner=None, email=None, reason=''): """ Called by message_get_suggested_recipients, to add a suggested recipient in the result dictionary. The form is : partner_id, partner_name<partner_email> or partner_name, reason """ self.ensure_one() if email and not partner: # get partner info from email partner_info = self.message_partner_info_from_emails([email])[0] if partner_info.get('partner_id'): partner = self.env['res.partner'].sudo().browse([partner_info['partner_id']])[0] if email and email in [val[1] for val in result[self.ids[0]]]: # already existing email -> skip return result if partner and partner in self.message_partner_ids: # recipient already in the followers -> skip return result if partner and partner.id in [val[0] for val in result[self.ids[0]]]: # already existing partner ID -> skip return result if partner and partner.email: # complete profile: id, name <email> result[self.ids[0]].append((partner.id, '%s<%s>' % (partner.name, partner.email), reason)) elif partner: # incomplete profile: id, name result[self.ids[0]].append((partner.id, '%s' % (partner.name), reason)) else: # unknown partner, we are probably managing an email address result[self.ids[…

http://stackoverflow.com/comment/86634065
score: 0
type: AnswerComment
has text: Which one is Pythonic?
comment on: http://stackoverflow.com/a/49809706
type: Comment

http://stackoverflow.com/q/49889312
downvote count: 1
has answer: http://stackoverflow.com/a/49889362
has answer: http://stackoverflow.com/a/49889354
possible better answer: http://stackoverflow.com/a/49889362
favorite count: 0
type: Question
has title: Pandas count elements in a columns and show in duplicated way
has answer: http://stackoverflow.com/a/49889522
tagged with: group-by
tagged with: count
tagged with: python
accepted answer: http://stackoverflow.com/a/49889354
answer count: 4
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/17432944
has answer: http://stackoverflow.com/a/49889857
tagged with: pandas
upvote count: 1
has body: I want to get something like this. A 1 1 2 3 3 4 4 4 4 I want to make it to be A B 1 2 1 2 2 1 3 2 3 2 4 4 4 4 4 4 4 4 Like you see here, the keys are duplicated and still in the same order as original. I know how to do this task in R by using data.table and I only know how to use groupby to get unique key counts in pandas. Anyone have ideas? Thank you!

boto3
tags question: http://stackoverflow.com/q/49761497
tag name: boto3
tags question: http://stackoverflow.com/q/49794587
tags question: http://stackoverflow.com/q/49896513
tags question: http://stackoverflow.com/q/49828806
tags question: http://stackoverflow.com/q/49759940
tags question: http://stackoverflow.com/q/49767264
tags question: http://stackoverflow.com/q/49799318
tags question: http://stackoverflow.com/q/49772151
tags question: http://stackoverflow.com/q/49908912
tags question: http://stackoverflow.com/q/49784340
tags question: http://stackoverflow.com/q/49855087
tags question: http://stackoverflow.com/q/49809138
tags question: http://stackoverflow.com/q/49871917
type: Tag
tags question: http://stackoverflow.com/q/49825638
tags question: http://stackoverflow.com/q/49867759
tags question: http://stackoverflow.com/q/49807460

http://stackoverflow.com/q/49909487
tagged with: python-xarray
type: AnsweredQuestion
score: 0
has title: Trying to apply fftconvolve over xarray
tagged with: scipy
has answer: http://stackoverflow.com/a/49912520
type: Question
tagged with: numpy
answer count: 1
has body: I have a 3D xarray DataArray and a 1D xarray DataArray. One dimension of the 3D array has the same size as the single dimension of the other. I want to apply scipy.signal.fftconvolve along these corresponding dimensions. But I get an error. Here is some minimal example code: import numpy as np from scipy.signal import fftconvolve import xarray as xr xarr1 = xr.DataArray(np.random.random([10,20,500]), dims=('dim1', 'dim2', 'sample')) xarr2 = xr.DataArray(np.random.random(500), dims=('sample',)) res = xr.apply_ufunc(fftconvolve, xarr1, xarr2, input_core_dims=[['sample'], ['sample']], kwargs={'mode': 'same'}, vectorize=True) What I want to do is the equivalent of this: res = np.zeros(xarr1.shape) for i1 in range(xarr1.shape[0]): for i2 in range(xarr1.shape[1]): res[i1, i2, :] = fftconvolve(xarr1[i1, i2, :], xarr2, mode='same') But I get the following error with the apply_ufunc version: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-174-4f45f68ab252&gt; in &lt;module&gt;() 7 xarr2 = xr.DataArray(np.random.random(500), 8 dims=('sample',)) ----&gt; 9 res = xr.apply_ufunc(fftconvolve, xarr1, xarr2, input_core_dims=[['sample'], ['sample']], kwargs={'mode': 'same'}, vectorize=True) ~\Anaconda3\envs\dataproc\lib\site-packages\xarray\core\computation.py in apply_ufunc(func, *args, **kwargs) 932 join=join, 933 exclude_dims=exclude_dims, --&gt; 934 keep_attrs=keep_attrs) 935 elif any(isinstance(a, Variable) for a in args): 936 return variables_ufunc(*args) ~\Anaconda3\envs\dataproc\lib\site-packages\xarray\core\computation.py in apply_dataarray_ufunc(func, *args, **kwargs) 209 210 data_vars = [getattr(a, 'variable', a) for a in args] --&gt; 211 result_var = func(*data_vars) 212 213 if signature.num_outputs &gt; 1: ~\Anaconda3\envs\dataproc\lib\site-packages\xarray\core\computation.py in apply_variable_ufunc(func, *args, **kwargs) 563 raise ValueError('unknown setting for dask array handli…
accepted answer: http://stackoverflow.com/a/49912520
tagged with: python

http://stackoverflow.com/comment/86567534
comment on: http://stackoverflow.com/q/49775199
type: Comment
type: QuestionComment
has text: The link works with anything you can run from command line, from Jupyter notebook, from any IDE, etc. Feel free to ask a separate question if you get stuck profiling, providing you can pinpoint why it's not working for you.
score: 0

http://stackoverflow.com/q/49760098
tagged with: python
tagged with: heatmap
answer count: 0
has title: Folium HeatmapWithTime
score: 1
downvote count: 1
has body: I have a dataframe which looks like this : ID LAT LON VALUE COUNT 81215545953683710540 48.847306 2.433284 0 1 74994612102903447699 48.861935 2.441292 1 1 48126186377367976994 48.839644 2.655109 1 1 23522333658893375671 48.924351 2.386369 4 3 16194691060240380504 48.829872 2.376677 8 1 Each ID has coordinates, a VALUE corresponding to a time interval and a COUNT which represents how much people were there. I want to make a heatmap with time which displays all rows that have the same VALUE at a time, taking in account that the bigger the COUNT is, the bigger the dot should be. So far, I succeeded to have a heatmap with time but I struggle with changing the radius of the dots. So every dot have the same size, which I do not want. What I do understand about the documentation here is that it is normally possible to change the radius : http://python-visualization.github.io/folium/docs-v0.5.0/plugins.html#folium-plugins My code so far : import folium import folium.plugins as plugins %matplotlib inline heat_df = data heat_df['Weight'] = heat_df['VALUE'] heat_df['Weight'] = heat_df['VALUE'].astype(float) heat_df = heat_df.dropna(axis=0, subset=['LAT','LON', 'Weight']) ma_heatmap = folium.Map(location=[48.512,2.2055],tiles= "OpenStreetMap", zoom_start = 13) heat_data = [[[row['LAT'],row['LON']] for index, row in heat_df[heat_df['Weight'] == i].iterrows()] for i in range(0,145)] #value jusqu'à 145 hm = plugins.HeatMapWithTime(heat_data,auto_play=True,max_opacity=0.8, radius=heat_data['COUNT']*10) #here is my try to change the radius hm.add_to(ma_heatmap) ma_heatmap I also made a static heatmap without a count, but here the values are adding themselves so I am satisfied with the dots, but I can't apply the time to it. It looks like this : import folium from folium import plugins %matplotlib inline m = folium.Map(location=[48.897634, 2.420086], zoom_start=7) m.add_children(plugins.HeatMap([[row["LAT"], row["LON"]] for counts, row in data.iterrows()])) m Either way I can't comput…
tagged with: folium
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/86681552
score: 0
has text: The filter is not applied during runtime
type: Comment
comment on: http://stackoverflow.com/q/49833183
type: QuestionComment

http://stackoverflow.com/q/49902603
tagged with: mysql
upvote count: 1
tagged with: django-rest-framework
favorite count: 0
has body: The table has 110 fields. I need to highest value from each row (like gratest in mysql) from 100 columns (thousands of records) and I need the filed name well (which has the highest value) Work platform in Django, MySQL. I've tried hitting db from view but that just slows down. How do I do this in view ? Is there any other alternative ?
type: Question
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: highest
score: 1
has title: How do I get Max() from 100+ fields in Django
tagged with: max
downvote count: 0

http://stackoverflow.com/a/49831099
answers question: http://stackoverflow.com/q/49831048
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86677735
downvote count: 0
has comment: http://stackoverflow.com/comment/86677848
type: Answer
has body: Your OOO's are three letters O as in Object, not the digit 'zero' (0). Don't ask me, why someone would use letters instead of digits on purpose or if some text-recognition-program thought, these had to be letters... You could use [0O] in all your regex to match both.

http://stackoverflow.com/q/49777173
tagged with: python
has answer: http://stackoverflow.com/a/49777382
has title: Process files until every file is processed
has body: I've got the following situation: I have a lot of html files in the directory "path". My pipeline works on these html files and produces an xml output of the file to the directory "out". Using python, I call my pipeline like this: datei = '../path/'+str(filename) p = subprocess.Popen(["./process", "-d", "../data", "-t", "../temp", "-o", "../output", datei], stdout=subprocess.PIPE) # function call out, err = p.communicate() Now my question is: How would you upgrade the code s.t. it checks whether the filename which the server is working on is already in "out" or not? If it is already in "out", the next file in "path" can be picked. If the filename is not in "out", the computer should continuing working on this file. Thanks for any help and advice!
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86569675
type: Question
tagged with: pipeline
type: UnansweredQuestion

http://stackoverflow.com/a/49868041
has body: How about this code? It already handles the "close" methods for you using context managers (with), skips the header and split the content into files and is splited into functions with separate concerns! ;) import re def skip_header(source): for i in range(3): next(source) def write_file(filename, content): print(f'Writting file "{filename}" with content "{content}"...') with open(filename, 'w') as destination: destination.write(content) src_filename = './csv/main.csv' with open(src_filename) as source: skip_header(source) for index, line in enumerate(source): dst_filename = f'./csv/file_{str(index)}.csv' content = re.sub('[^a-zA-Z0-9\.]', "", line) write_file(dst_filename, content) Here is the folder structure of the simple project. The files file_X.csv were generated by the code above (Python 3.6.4).
type: Answer
has comment: http://stackoverflow.com/comment/86752370
has comment: http://stackoverflow.com/comment/86752421
has comment: http://stackoverflow.com/comment/86752406
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49867858
has comment: http://stackoverflow.com/comment/86752327
has comment: http://stackoverflow.com/comment/86752385
score: 1
answers question: http://stackoverflow.com/q/49867858

http://stackoverflow.com/q/49866765
has comment: http://stackoverflow.com/comment/86749087
has comment: http://stackoverflow.com/comment/87261482
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49872863
has title: Using tuple as key for nested properties with json.dump
favorite count: 0
type: Question
tagged with: tuples
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/86749360
linked to: http://stackoverflow.com/q/19189274
has comment: http://stackoverflow.com/comment/86749188
has answer: http://stackoverflow.com/a/49866884
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86749114
has body: Not sure how to use a tuple as a set of strings the way I would like. I would like my json to look like: 'item': { 'a': { 'b': { 'c': 'somevalue' } } } Which could be done with: item = {} item['a']['b']['c'] = "somevalue" However a, b, and c are dynamic, so I understand I need to use a tuple, but this does not do what I would like: item = {} path = ('a','b','c') item[path] = "somevalue" json.dump(item, sys.stdout) So I am getting the error: TypeError("key " + repr(key) + " is not a string" How do I dynamically get item['a']['b']['c']?
tagged with: list
answer count: 2
downvote count: 0

websphere
tags question: http://stackoverflow.com/q/49908270
tag name: websphere
type: Tag

http://stackoverflow.com/a/49795329
upvote count: 7
score: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86676019
downvote count: 0
has comment: http://stackoverflow.com/comment/86676744
accepted answer of: http://stackoverflow.com/q/49790974
has comment: http://stackoverflow.com/comment/86691700
has body: To start understanding how scipy curve_fit tries to solve a problem, start with reading about non-linear optimization methods such as the Levenberg-Marquardt (LM) method (see https://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm). This is the method curve_fit uses when bounds on parameter values are not specified, and it will give most of the answers you seek. This method (and the other solvers in scipy.optimize) start with initial values and try to refine these values in order to find the minimal resulting residual array (in the least-squares sense: to be clear, the method expects a residual array and does the squaring and summing itself). To find which direction to move parameter values, it uses the first derivative (of the residual wrt to the variables that is) or Jacobian. It it very common to not have an analytic form for this, in which case numerical derivatives are calculated by taking very small steps (ofteen around machine precision) in parameter values. With these derivatives and the last step size the LM method decides how big of a step to make to find the minimal residual. It is a common (and often a good) approximation to think of the residual as a quadratic function of each parameter. If the value is far from the bottom, taking a step that is linear in the derivative (ie, just following the local slope) is pretty good. But near the end solution, it is helpful to use the 2nd derivative (aka Hessian, curvature, or in some sense "history"). LM combines these two approaches to try to quickly find the solution. At each step, it first calculates the derivatives (and second derivative after the first step) then calculates the step to take for all parameters. It repeats this process until the solution (chi-square) does not improve compared to a tolerance. In scipy's leastsq (often used by curve_fit) the step size used to calculate numerical derivatives, and the tolerances for stopping the fit can be specified. Typically, when using curve_fit or l…
answers question: http://stackoverflow.com/q/49790974
type: Answer
has comment: http://stackoverflow.com/comment/86671996
has comment: http://stackoverflow.com/comment/86691856

http://stackoverflow.com/comment/86721415
type: Comment
has text: Do you have a proxy in your system
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49853247

http://stackoverflow.com/comment/86841032
comment on: http://stackoverflow.com/q/49912154
score: 0
type: Comment
has text: https://www.elastic.co/guide/en/elasticsearch/reference/2.0/docs-update.html#upserts
type: QuestionComment

http://stackoverflow.com/q/49764607
has comment: http://stackoverflow.com/comment/86544750
tagged with: python
has comment: http://stackoverflow.com/comment/86544806
tagged with: document
has comment: http://stackoverflow.com/comment/86545337
has body: Here is my code. I'm having trouble figuring out how to make my program count non alphanumerics. I am a new coding student so go easy on me. infile = open("Gettysburg.txt", "r") data = infile.readlines() non_alpha_num = 0 uppercase_count = 0 lowercase_count = 0 whitespace_count = 0 digit_count = 0 for character in data: if character.isupper(): uppercase_count += 1 elif character.islower(): lowercase_count += 1 elif character.isspace(): whitespace_count +=1 elif character.isdigit(): digit_count +=1 if not character.isalnum() and not character.isspace(): non_alpha_num += 1 print("Jake's text document counter") print('The uppercase count is ', uppercase_count) print('The lowercase count is ', lowercase_count) print('The digit count is ', digit_count) print('The whitespace count is ', whitespace_count) print('The non alphanumeric count is ', non_alpha_num)
tagged with: counting
has comment: http://stackoverflow.com/comment/86544954
tagged with: text
has comment: http://stackoverflow.com/comment/86544768
has comment: http://stackoverflow.com/comment/86545042
has comment: http://stackoverflow.com/comment/86544842
accepted answer: http://stackoverflow.com/a/49764642
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86544905
tagged with: non-alphanumeric
downvote count: 0
has answer: http://stackoverflow.com/a/49764642
upvote count: 1
score: 1
has title: How do I count non alphanumerics in a text document with Python?
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/86758013
type: Comment
comment on: http://stackoverflow.com/a/49871067
score: 0
type: AnswerComment
has text: Thanks a lot, this works but there is no space (tab) between the values. The answers are in the format ABCDEFGHIJ

http://stackoverflow.com/comment/112596297
comment on: http://stackoverflow.com/a/63673450
score: 0
type: AnswerComment
has text: Edited the answer.
type: Comment

http://stackoverflow.com/q/49807747
has body: I have two objects from different classes. What is a reasonable design choice to make the attribute of one reflect changes in the other? A naive solution that doesn't work is shown below and hopefully illustrates the aim: Specifically: class A(object): def __init__(self): self.x = 'a original string' class B(object): def __init__(self): self.x = 'b original string' a = A() b = B() b.x = a.x a.x = 'a modified string' print('b.x = "{}" was not modified when a.x = "{}" was changed'.format(b.x, a.x))
has comment: http://stackoverflow.com/comment/86630976
has title: sync attributes between objects of different type
has answer: http://stackoverflow.com/a/49807853
tagged with: properties
type: AnsweredQuestion
score: 0
tagged with: oop
accepted answer: http://stackoverflow.com/a/49807853
has comment: http://stackoverflow.com/comment/86630713
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86630772
tagged with: attributes
type: Question
tagged with: python-3.x

pip
tags question: http://stackoverflow.com/q/49787551
tags question: http://stackoverflow.com/q/49797828
tags question: http://stackoverflow.com/q/49797115
tags question: http://stackoverflow.com/q/49868091
tags question: http://stackoverflow.com/q/49854628
tags question: http://stackoverflow.com/q/49808547
tags question: http://stackoverflow.com/q/49868654
tags question: http://stackoverflow.com/q/49762985
tags question: http://stackoverflow.com/q/49854953
tags question: http://stackoverflow.com/q/49891625
tags question: http://stackoverflow.com/q/49793767
tags question: http://stackoverflow.com/q/49829330
tags question: http://stackoverflow.com/q/49903491
tags question: http://stackoverflow.com/q/49793849
tags question: http://stackoverflow.com/q/49840543
tags question: http://stackoverflow.com/q/49882684
tags question: http://stackoverflow.com/q/49874942
tags question: http://stackoverflow.com/q/49916736
tags question: http://stackoverflow.com/q/49768770
tags question: http://stackoverflow.com/q/49784924
tags question: http://stackoverflow.com/q/49802238
tags question: http://stackoverflow.com/q/49912511
tags question: http://stackoverflow.com/q/49875145
tags question: http://stackoverflow.com/q/49835849
tags question: http://stackoverflow.com/q/49799405
tags question: http://stackoverflow.com/q/49768897
tags question: http://stackoverflow.com/q/49861102
tags question: http://stackoverflow.com/q/49839610
tags question: http://stackoverflow.com/q/49881448
tags question: http://stackoverflow.com/q/49851668
tags question: http://stackoverflow.com/q/49820873
tags question: http://stackoverflow.com/q/49807046
tags question: http://stackoverflow.com/q/49869827
tags question: http://stackoverflow.com/q/49904228
tags question: http://stackoverflow.com/q/49870594
tags question: http://stackoverflow.com/q/49844560
tags question: http://stackoverflow.com/q/49822712
type: Tag
tags question: http://stackoverflow.com/q/49772348
tags question: http://stackoverflow.com/q/49837301
tags question: http://stackoverflow.com/q/49854465
tags question: http://stackoverflow.com/q/49767264
tags question: http://stackoverflow.com/q/49839924
tags question: http://stackoverflow.com/q/49796691
tags question: http://stackoverflow.com/q/49799578
tags question: http://stackoverflow.com/q/49873914
tags question: http://stackoverflow.com/q/49866012
tags question: http://stackoverflow.com/q/49888717
tags question: http://stackoverflow.com/q/49887395
tags question: http://stackoverflow.com/q/49891038
tags question: http://stackoverflow.com/q/49835842
tags question: http://stackoverflow.com/q/49818592
tags question: http://stackoverflow.com/q/49811955
tags question: http://stackoverflow.com/q/49785606
tags question: http://stackoverflow.com/q/49846804
tags question: http://stackoverflow.com/q/49817590
tags question: http://stackoverflow.com/q/49872110
tags question: http://stackoverflow.com/q/49848517
tags question: http://stackoverflow.com/q/49763029
tags question: http://stackoverflow.com/q/49836676
tags question: http://stackoverflow.com/q/49832133
tag name: pip
tags question: http://stackoverflow.com/q/49796203
tags question: http://stackoverflow.com/q/49898958
tags question: http://stackoverflow.com/q/49900875
tags question: http://stackoverflow.com/q/49887968
tags question: http://stackoverflow.com/q/49843479
tags question: http://stackoverflow.com/q/49883457
tags question: http://stackoverflow.com/q/49782230
tags question: http://stackoverflow.com/q/49873842
tags question: http://stackoverflow.com/q/49762035
tags question: http://stackoverflow.com/q/49861944
tags question: http://stackoverflow.com/q/49787901
tags question: http://stackoverflow.com/q/49867010
tags question: http://stackoverflow.com/q/49876140
tags question: http://stackoverflow.com/q/49805395
tags question: http://stackoverflow.com/q/49779380
tags question: http://stackoverflow.com/q/49844369
tags question: http://stackoverflow.com/q/49912739
tags question: http://stackoverflow.com/q/49818325

http://stackoverflow.com/comment/86820107
type: AnswerComment
comment on: http://stackoverflow.com/a/49901914
score: 0
type: Comment
has text: change `pages = {edge[0] for edge in edges}` to `pages = list({edge[0] for edge in edges})`

http://stackoverflow.com/comment/86834349
type: AnswerComment
has text: You have to use map for both if you want to make that comparison. Replace `[indices[x] for x in l2]` by `map(lambda x: indices[x], l2)` on line 9. I don't know why list comprehensions are so slow on your system, I only see a 20% difference on mine (Python 3.5 on Windows).
comment on: http://stackoverflow.com/a/49905355
score: 0
type: Comment

http://stackoverflow.com/a/49849093
accepted answer of: http://stackoverflow.com/q/49848395
has body: As taken from this issue, the solution is to install pyopenssl, which I apparently did not have. Running pip3 install --user pyopenssl Fixed all the errors. Still not sure exactly why this is. If someone could explain why pyopenssl fixed it, that would be great. Thanks!
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49848395
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86885743
type: Comment
has text: it worked. the first solution that included adding self at the beginning of the constructor worked.
type: AnswerComment
comment on: http://stackoverflow.com/a/49898790
score: 1

http://stackoverflow.com/q/49865442
has answer: http://stackoverflow.com/a/49865561
tagged with: python
has comment: http://stackoverflow.com/comment/86746380
answer count: 2
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/86746354
has answer: http://stackoverflow.com/a/49865547
has comment: http://stackoverflow.com/comment/86746550
tagged with: string
has title: write into a js file without passing in string quotes (in Python)
downvote count: 1
favorite count: 0
score: -1
type: Question
has body: I am writing a parser to grab data from GitHub api, and I would like to output the file into the following .js format: //Ideal output var LIST_DATA = [ { "name": "Python", "type": "category" }] Though I am having trouble writing into output.js file with the variable var LIST_DATA, no matter what I do with the string, the end result shows as "var LIST_DATA" For example: //Current Output "var LIST_DATA = "[ { "name": "Python", "type": "category" }] My Python script: var = "var LIST_DATA = " with open('list_data.js', 'w') as outfile: outfile.write(json.dumps(var, sort_keys = True)) I also tried using strip method according to this StackOverflow answer and got the same result var = "var LIST_DATA = " with open('list_data.js', 'w') as outfile: outfile.write(json.dumps(var.strip('"'), sort_keys = True)) I am assuming, whenever I am dumping the text into the js file, the string gets passed in along with the double quote... Is there a way around this? Thanks.
linked to: http://stackoverflow.com/q/25611882
type: UnansweredQuestion

http://stackoverflow.com/comment/86576381
has text: Yes that is correct. And I believe I answered the test_size * 100 in 3. above. I noticed you were adding to the question and added my responses. But to reiterate, adding this would give you different random states within a single run, but would still be reproducible from one run to the next as long as the test_size is consistent. (ie you aren't adding or changing the lengths)
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49779349

http://stackoverflow.com/q/49788801
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86592649
answer count: 1
has comment: http://stackoverflow.com/comment/86592880
has comment: http://stackoverflow.com/comment/86592936
has body: I've been using PyCharm for a month but decided to give geany a try. I've spend hours looking at all the installation and setup tutorials on the web and youtube and even in my book it tells you how to set it up. They all say the same thing and as far as I know, I've done exactly what they said. (I found a question on here by someone with the exact same problem but it was never answered.) go to Build>Set Build Commands, in the box next to Execute, put in the path to where python is located. Here is my path C:\Users\{username}\AppData\Local\Programs\Python\Python36-32\python.exe I don't know why my python installed in such an unusual place. Everyone else's look like this: C:\Python35\python. Is that the problem? When I go into C:\Users\{username}, the AppData folder is not visible. Is this for security? Is Geany not able to access those folders cause they are invisible? I'm pretty sure you don't need the .exe so I deleted it. C:\Users\{username}\AppData\Local\Programs\Python\Python36-32\python "%f" When I hit execute, I can see the command window appear for a split second and then disappear, probably because it tries, but can't find python so closes. I don't know what the %f is but everyone has it anyways. Before I entered all that into the text box, by default in that text box, there was .\%e I don't know what that is all about.
score: 0
has title: Geany do not find path to python
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/86593080
tagged with: geany
type: Question
has comment: http://stackoverflow.com/comment/86592763
has answer: http://stackoverflow.com/a/50643647

http://stackoverflow.com/comment/86570758
comment on: http://stackoverflow.com/q/49776624
type: QuestionComment
has text: Just added some explanation to my answer.
score: 0
type: Comment

http://stackoverflow.com/a/49853419
answers question: http://stackoverflow.com/q/49850431
type: Answer
score: 0
has body: Try this using iterators: #!/usr/bin/env python3 import sys def handle_count(count): print("count", count) def main(): with open("splitter.txt", "rt") as fhandle: for line in (d.strip() for d in fhandle): for d in (i.count('$') for i in line.split('#')): handle_count(d) if __name__ == '__main__': main()

http://stackoverflow.com/comment/86801029
type: Comment
has text: Check whether Select located inside `iframe` and whether class name `"select150"` is not dynamic
type: AnswerComment
comment on: http://stackoverflow.com/a/49892086
score: 0

http://stackoverflow.com/q/49882785
favorite count: 0
type: Question
score: 3
has title: Strange isinstance behaviour in pandas int and np.int64
tagged with: python
accepted answer: http://stackoverflow.com/a/49884099
has answer: http://stackoverflow.com/a/49882977
possible better answer: http://stackoverflow.com/a/49882977
type: AnsweredQuestion
upvote count: 3
has body: I have a series of np.int64, but for some reason using isinstance() in different cases yields different answers. You can see in the attached image that if I check the type of the individual element, I get numpy.int64, and so the isinstance on this particular element works out correctly. When I use apply, however, the opposite behavior happens, and I get different results. Is this because apply changes the type somehow? In more detail, the original series is defined with: sample_series = pd.Series([np.int64(1), np.int64(25), np.int64(50) ,np.int64(75)]) When I check the type of one element,type(sample_series.loc[0]), I get the output numpy.int64. Now using isinstance gives me the following (expected) answers, isinstance(sample_series.loc[0], int) , with output: False and isinstance(sample_series.loc[0], np.int64) with output: True. On the other hand, sample_series.apply(lambda x : isinstance(x,int)) gives the output: 0 True 1 True 2 True 3 True dtype: bool While sample_series.apply(lambda x : isinstance(x, np.int64)) gives the output: 0 False 1 False 2 False 3 False dtype: bool So it seems that the results are inconsistent. Thank you!
answer count: 2
downvote count: 0
tagged with: pandas
tagged with: types
has answer: http://stackoverflow.com/a/49884099

http://stackoverflow.com/q/49867647
has answer: http://stackoverflow.com/a/49867712
type: Question
has title: change variable type, and relabel variables
has comment: http://stackoverflow.com/comment/86750965
tagged with: python
score: -1
tagged with: analytics
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
has body: I have uploaded a dataset in Python. I need to do two things. One, change some of my variables, like ID, Gender (which is input as 0 and 1) from float64. I also want to change the input under gender from 0 to male and 1 to female. I am not sure how to go about the first questions, but the second, I figure I would do a combination of a for loop and if then statements, but I am really confused. Any suggestions?
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/43202777
favorite count: 0

http://stackoverflow.com/comment/86716718
type: Comment
type: AnswerComment
score: 0
has text: So usually I can pass a variable using `url_for`.
comment on: http://stackoverflow.com/a/49850378

http://stackoverflow.com/a/63262008
has body: If you have level 15 access to the switch you don't need the enable password. You give level 15 like this: username user1 privilege 15 secret goodpassword David Bombal have a couple of examples on configuring switches here: https://github.com/davidbombal/pythonvideos/blob/master/netmiko2.py for devices in all_devices: net_connect = ConnectHandler(**devices) for n in range (2,21): print "Creating VLAN " + str(n) config_commands = ['vlan ' + str(n), 'name Python_VLAN ' + str(n)] output = net_connect.send_config_set(config_commands) print output
type: Answer
answers question: http://stackoverflow.com/q/49759897
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49837324
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: If you have the data in rows with columns=["Taxi ID", "Timestamp", "Fare"] then convert the timestamp to datetime.datetime format (if it isn't already) and make it the index, i.e. df.index=df["Timestamp"]. Then you can use pd.DataFrame.resample with a rule (in your case 'H') and a built in method (see https://pandas.pydata.org/pandas-docs/stable/api.html#resampling) or .apply your own. For example: df = pd.DataFrame([[1],[2]],index=[datetime(2017,1,1,1),datetime(2017,1,1,2)]) resampled = df.resample('H').median()
answers question: http://stackoverflow.com/q/49837177
type: Answer
accepted answer of: http://stackoverflow.com/q/49837177
score: 1

http://stackoverflow.com/comment/86556643
comment on: http://stackoverflow.com/q/49770636
score: 0
type: Comment
type: QuestionComment
has text: The sample request shows an HTML form, so it looks as if the data should be form-encoded. That means you should use `data=payload` not `json=payload`. If you search for "INVALID_TICKET" there seem to be many results - [one suggestion](https://help.zoho.com/portal/community/topic/getting-invalid-ticket-id-error) I saw was to try regenerating the token.

http://stackoverflow.com/comment/86783885
type: QuestionComment
has text: You're overwriting `player1` (which stores the letter "x") with `True` in your loop. You need to use a different variable for that.
comment on: http://stackoverflow.com/q/49883898
score: 7
type: Comment

http://stackoverflow.com/a/55920178
answers question: http://stackoverflow.com/q/49776568
has body: I used to import some R packages ans use them inside my python code but recently I improvised a method where you can simply use your R code and give the required tasks to it. Have a look here https://stackoverflow.com/a/55900840/5350311 it can be useful for your case.
type: Answer
score: 0

http://stackoverflow.com/comment/86715078
type: Comment
score: 0
type: QuestionComment
has text: I do not think this is easily (or efficiently) doable.
comment on: http://stackoverflow.com/q/49850024

http://stackoverflow.com/q/49808508
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/8311900
has comment: http://stackoverflow.com/comment/86631989
has title: python csv to tsv: in case record has comma inside
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/49808627
tagged with: python
accepted answer: http://stackoverflow.com/a/49808627
has body: I'm trying to convert csv format to tsv. I just used this to change comma to tab. tsv = re.sub(',', '\t', csv) But I can't deal with the string with comma inside, for example: dept_no,dt,hello 1,20180411,hello its me 2,20180412,here has tab 3,20180412,"here, is, commas" Is there any way to convert to tsv without affecting comma inside of the string?
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86631930

http://stackoverflow.com/a/49838252
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49838179
accepted answer of: http://stackoverflow.com/q/49838179
has comment: http://stackoverflow.com/comment/86691602
has body: This should work with BeautifulSoup v3 and v4. content = """ &lt;img src="http://dcimg6.dcinside.co.kr/viewimage.php?id=2fbcc323e7d334aa51b1d3a240&amp;amp;no=24b0d769e1d32ca73fef84fa11d028318f52c0eeb141bee560297996d466c894cf2d16427672bba3d66d67f244141456484cb174854719ce631af568a8c297d4e29cc59286bf0d77bcf8d9267e7297e17913fdd84522b3d3" style="cursor:pointer;" onclick="javascript:imgPop('http://image.dcinside.com/viewimagePop.php?id=2fbcc323e7d334aa51b1d3a240&amp;amp;no=24b0d769e1d32ca73fef84fa11d028318f52c0eeb141bee560297996d466c894cf2d16427672bba3d66d67f24450460016bd8e2258cb95ccf2b058e84f237054da6dbbc48af67310bf0bff50c529f1331053edf6','image','fullscreen=yes,scrollbars=yes,resizable=no,menubar=no,toolbar=no,location=no,status=no');"&gt; """ soup = BeautifulSoup(content) onclick = soup.find('img').get('onclick') js_item = onclick.split(',')[0] link = js_item.replace('javascript:imgPop(', '').replace("'", "")
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/49766456
score: 0
answer count: 1
type: Question
tagged with: dask
has answer: http://stackoverflow.com/a/49847319
type: UnansweredQuestion
has body: I have two dataframe with same shape. I tried to convert to dask dataframe specifying same n_partition=50. However, how each dataframe split into partition seems different as shown below image. Does anyone know how I can specify how dataframe should be separated?
tagged with: python
has title: How can I specify row order when I use dask.dataframe
tagged with: pandas

http://stackoverflow.com/a/49775529
score: 1
has comment: http://stackoverflow.com/comment/86575784
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49763193
upvote count: 1
has comment: http://stackoverflow.com/comment/86575012
has comment: http://stackoverflow.com/comment/86575443
type: Answer
has body: This is caused by the relative module import import a that exists in b.py For Python 3, this should be: from . import a
has comment: http://stackoverflow.com/comment/86574216
has comment: http://stackoverflow.com/comment/86573632
answers question: http://stackoverflow.com/q/49763193

http://stackoverflow.com/comment/86727717
type: QuestionComment
comment on: http://stackoverflow.com/q/49856572
has text: I'm confused. To my understanding, a command prompt by definition is in "interactive mode".
score: 0
type: Comment

http://stackoverflow.com/comment/86563064
type: Comment
type: QuestionComment
has text: `for x, y in xy_list[1:8]:`?
comment on: http://stackoverflow.com/q/49774174
score: 1

http://stackoverflow.com/comment/86806578
score: 4
type: Comment
comment on: http://stackoverflow.com/q/49895499
type: QuestionComment
has text: Possible duplicate of [Django: implementing JOIN using Django ORM?](https://stackoverflow.com/questions/4125379/django-implementing-join-using-django-orm)

http://stackoverflow.com/a/49782846
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86612391
has comment: http://stackoverflow.com/comment/87366556
has comment: http://stackoverflow.com/comment/86607754
has comment: http://stackoverflow.com/comment/86612450
has comment: http://stackoverflow.com/comment/86612466
has comment: http://stackoverflow.com/comment/87375913
type: Answer
accepted answer of: http://stackoverflow.com/q/49782358
has comment: http://stackoverflow.com/comment/86583328
has body: I haven't found a way to record a video using pypylon; it seems to be a pretty light wrapper around Pylon. However, I have found a way to save a video using imageio: from imageio import get_writer with get_writer('I:/output-filename.mp4', fps=fps) as writer: # Some stuff with the frames The above can be used with .mov, .avi, .mpg, .mpeg, .mp4, .mkv or .wmv, so long as the FFmpeg program is available. How you will install this program depends on your operating system. See this link for details on the parameters you can use. Then, simply replace the call to imwrite with: writer.append_data(image) ensuring that this occurs in the with block. An example implementation: import os import pypylon from imageio import get_writer while True: try: fsamp = float(input('Sampling rate (Hz): ')) break except ValueError: print('Invalid input.') time_exposure = 1000000 / fsamp available_cameras = pypylon.factory.find_devices() cam = pypylon.factory.create_device(available_cameras[0]) cam.open() cam.properties['ExposureTime'] = time_exposure buffer = tuple(cam.grab_images(2000)) with get_writer( 'I:/output-filename.mkv', # mkv players often support H.264 fps=fsamp, # FPS is in units Hz; should be real-time. codec='libx264', # When used properly, this is basically # "PNG for video" (i.e. lossless) quality=None, # disables variable compression pixelformat='rgb24', # keep it as RGB colours ffmpeg_params=[ # compatibility with older library versions '-preset', # set to faster, veryfast, superfast, ultrafast 'fast', # for higher speed but worse compression '-crf', # quality; set to 0 for lossless, but keep in mind '11' # that the camera probably adds static anyway ] ) as writer: for image in buffer: writer.append_data(image) del buffer
upvote count: 3
answers question: http://stackoverflow.com/q/49782358
score: 3

http://stackoverflow.com/q/49780698
has answer: http://stackoverflow.com/a/49781417
downvote count: 0
answer count: 1
has body: I have data structured into a nested list my_lst, example output of its loop: ['A', 2312] ['B', 2000] ['C', 1312] etc... element 1 of each list = download_budget I have a value download_total = 5000 I am attempting to append 2 value per list by spreading the download_target value across the different lists based on the following rules: The maximum value for element 2 2047 Element 3 increments by 1 every time element 2 goes beyond 2047 An example using: my_lst = [['A', 2312], ['B', 2000], ['C', 1312], ['D', 3000]] with download_total as 5000 should yield the output of ['A', 2312, 0, 0] ['B', 2000, 265, 1] # total d/l = 2312 ['C', 1312, 218, 2] # total d/l = 2312 + 2000 = 4312 ['D', 3000, 906, 2] # total d/l = 5000 # i.e. (2 * 2047) + 906 The first entry will always be a given offset (e.g. 0, 0). The 2nd entry reads the download_budget of the first entry (2312) and attempts to spread the values according to the rules described, making sure the download_total is not exceeded. My attempt: el2 = 0 el3 = 0 for i, element in enumerate(my_lst): if i == 0: element.append(el2) element.append(el3) if i &gt;= 1: download_budget = my_lst[i-1][1] while (download_budget &gt; 2047): el3 += 1 download_budget = download_budget - 2047 if download_budget &lt; 2047: el2 = download_budget element.append(el2) element.append(el3) Basically, I kind of get the grasp of how I can do this but would be useful to know if there are better ways of doing it
tagged with: python
favorite count: 0
type: AnsweredQuestion
score: 3
tagged with: python-2.7
has title: Spreading values across lists in bins
upvote count: 3
accepted answer: http://stackoverflow.com/a/49781417
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86713013
comment on: http://stackoverflow.com/a/49849124
type: Comment
score: 0
type: AnswerComment
has text: Just done a bool check, its always returning True which is what I've had before, thats why I assumed `startswith` doesnt work for this case. Baffled

http://stackoverflow.com/comment/86613066
type: Comment
type: QuestionComment
has text: @RishiG the space where it str(month)?
score: 0
comment on: http://stackoverflow.com/q/49798889

http://stackoverflow.com/q/49868005
tagged with: python
has answer: http://stackoverflow.com/a/49868238
tagged with: graphene-python
has answer: http://stackoverflow.com/a/49907321
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49910960
tagged with: graphql
upvote count: 1
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
type: Question
has body: I'm currently trying to integrate GraphQL (using graphene and flask_graphql) into my flask app. Tried a few tutorial from here and here. But seems none works in my situation. Currently my project is like this -manage.py |app |__init__.py (create_app is here) |mod_graphql (this is folder) |__init__.py (blueprint created here) |models.py |schema.py |controller.py The issue is in both tutorial, it recommend to create Base and engine in the models file, I did the same, but I would need to read config file using current_app for the URI to create engine. But actually, because it happens in flask initialization, so there is no request context yet, so current_app doesn't exist. so everything fails. Would it be possible to help me setup this? Below are some code: app/__init__.py create_app(): ... from .mod_graphql import bp_graph app.register_blueprint(bp_graph) ... mod_graphql/__init__.py from flask import Blueprint bp_graph = Blueprint('graphql', __name__) from . import controller from . import models from . import schema mod_graphql/models.py Base = declarative_base() engine = create_engine(current_app.config.get('BASE_URI'), convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base.query = db_session.query_property() class Model1_Model(Base): ... class Model2_Model(Base): ... mod_graphql/schema.py class Model1(SQLAlchemyObjectType): class Meta: model = Model1_Model interfaces = (relay.Node,) class Model2(SQLAlchemyObjectType): class Meta: model = Model2_Model interfaces = (relay.Node,) class Query(graphene.ObjectType): node = relay.Node.Field() schema = graphene.Schema(query=Query, types=[Model1]) mod_graphql/controller.py bp_graph.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True, context={'session': db_session})) @bp_graph.teardown_app_request() def shutdown_session(exception=True): db_session.remove() When I try to start server, it tells me: Working outside of appli…
answer count: 3
score: 1
has title: Integrate graphql into flask blueprint

http://stackoverflow.com/comment/86812261
type: QuestionComment
comment on: http://stackoverflow.com/q/49868630
has text: You can find the complete pytube documentation at https://python-pytube.readthedocs.io/en/latest/
score: 1
type: Comment

http://stackoverflow.com/q/49838224
downvote count: 1
accepted answer: http://stackoverflow.com/a/50455100
type: AnsweredQuestion
has title: Understand why Bitcoinlib is generating different addresses than what I have
tagged with: bitcoin
answer count: 1
score: -1
favorite count: 0
type: Question
tagged with: cryptocurrency
tagged with: bitcoinlib
has answer: http://stackoverflow.com/a/50455100
upvote count: 0
tagged with: mnemonics
tagged with: python
has body: Here is the library in question https://github.com/1200wd/bitcoinlib. When I try to create an address using the same keywords for example abs=a.from_passphrase('average title retreat fox hundred wife figure disease dry admit choice volcano') (example list) I think I understand that it uses bip44 to generate a WIF and Address but when I check the address using Ian Coles Mnemonic Code Converter https://iancoleman.io/bip39/ it gives a different address than the one given from bitcoinlib. Are they each using different methods to create an address? Is there way I can get bitcoinlib to spit out the same address from a mnemoic word list as in Ian Cole's converter.

http://stackoverflow.com/comment/86805733
type: Comment
has text: @Thatshowweroll no worries! Cheers!
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49894685

http://stackoverflow.com/comment/86624119
type: Comment
comment on: http://stackoverflow.com/a/49804657
type: AnswerComment
score: 0
has text: The problem with this however is that if one of the limits is exceeded as long as there are no null values it will still be inserted into the database.

http://stackoverflow.com/comment/86543183
has text: Thanks @abarnert, for such an excellent solution. Much obliged.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49763777

http://stackoverflow.com/comment/86587623
has text: Thanks ! This is exactly what I am looking for
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49785808
type: AnswerComment

http://stackoverflow.com/comment/86726398
comment on: http://stackoverflow.com/q/49823594
score: 0
has text: Thanks! I've updated the question to show the answers :D
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49800475
tagged with: datetime
tagged with: python
has body: Building a Twitter scraper I'm stuck at converting tweet creation datetime (I get it as local timezone) into UTC. Creation date from data-original-title -attribute's format is 12:17 AM - 8 Apr 2018. How can I convert it to UTC?
accepted answer: http://stackoverflow.com/a/49800869
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49801269
answer count: 2
has title: Convert tweet creation time to UTC
has answer: http://stackoverflow.com/a/49800869
has answer: http://stackoverflow.com/a/49801269
score: 1
tagged with: utc
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86565853
has text: It seems your desired (2nd) DataFrame has multiple dates in the date column, but your input DataFrame only has 1 date in the date column. Do you have one DataFrame per date? Have you tried DataFrame.merge()?
comment on: http://stackoverflow.com/q/49775308
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86714420
has text: did you actually read the error message?
comment on: http://stackoverflow.com/q/49841971
score: 0
type: Comment
type: QuestionComment

numpy-ndarray
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/49884232
type: Tag
tags question: http://stackoverflow.com/q/49916268
tags question: http://stackoverflow.com/q/49863633

http://stackoverflow.com/comment/86685656
type: Comment
has text: how do i define a statement where it can check for the interger value and return a invlid entry message
type: AnswerComment
comment on: http://stackoverflow.com/a/49835199
score: 0

http://stackoverflow.com/comment/86555575
score: 1
type: Comment
has text: You could also look at the shutil library which contains many shell utilities, including copying files. so add "from shutil import copy2" and then copy the file with "copy2(info.name, targdir)"
comment on: http://stackoverflow.com/a/49770121
type: AnswerComment

http://stackoverflow.com/comment/106406157
type: AnswerComment
comment on: http://stackoverflow.com/a/49868074
has text: this solution doesn't work with 16GB files..... looking for a way to do that without pre-loading the entire file.
score: 0
type: Comment

http://stackoverflow.com/comment/86674908
type: QuestionComment
has text: @RamkishoreM I would like it to the second block of text I posted. Maybe I shouldn't do keywords and their is a better way
score: 0
comment on: http://stackoverflow.com/q/49829614
type: Comment

http://stackoverflow.com/comment/86680118
type: QuestionComment
comment on: http://stackoverflow.com/q/49832443
has text: `return list(set(your_list))`
type: Comment
score: 1

http://stackoverflow.com/a/49870575
score: 0
answers question: http://stackoverflow.com/q/49868822
type: AcceptedAnswer
has body: You need to join the dataframe on common columns otherwise it will generate 2 conflicting columns of the same name from 2 different dataframes. common_cols = [x for x in df1.columns if x in df2.columns] df3 = df1.join(df2, on=common_cols, how='outer') You can use outer join or left join based on your requirement. And please do not ask multiple questions for the same issue. You are already getting active answers at : when trying to join two tables, happening IndexError: list index out of range in pyspark
accepted answer of: http://stackoverflow.com/q/49868822
type: Answer

http://stackoverflow.com/q/49847946
score: 1
has title: Scipy.integrate gives odd results
tagged with: python
has body: I am still struggling with scipy.integrate.quad. Sparing all the details, I have an integral to evaluate. The function is of the form of the integral of a product of functions in x, like so: Z(k) = f(x) g(k/x) / abs(x) I know for certain the range of integration is between tow positive numbers. Oddly, when I pick a wide range that I know must contain all values of x that are positive - like integrating from 1 to 10,000,000 - it intgrates fast and gives an answer which looks right. But when I fingure out the exact limits - which I know sice f(x) is zero over a lot of the real line - and use those, I get another answer that is different. They aren't very different, though I know the second is more accurate. After much fiddling I got it to work OK, but then needed to add in an exopnentiation - I was at least getting a 'smooth' answer for the computed function of z. I had this working in an OK way before I added in the exponentiation (which is needed), but now the function that gets generated (z) becomes more and more oscillatory and peculiar. Any idea what is happening here? I know this code comes from an old Fortran library, so there must be some known issues, but I can't find references. Here is the core code: def normal(x, mu, sigma) : return (1.0/((2.0*3.14159*sigma**2)**0.5)*exp(-(x- mu)**2/(2*sigma**2))) def integrand(x, z, mu, sigma, f) : return np.exp(normal(z/x, mu, sigma)) * getP(x, f._x, f._y) / abs(x) for _z in range (int(z_min), int(z_max) + 1, 1000): z.append(_z) pResult = quad(integrand, lb, ub, args=(float(_z), MU-SIGMA**2/2, SIGMA, X), points = [100000.0], epsabs = 1, epsrel = .01) # drop error estimate of tuple p.append(pResult[0]) # drop error estimate of tuple By the way, getP() returns a linearly interpolated, piecewise continuous,but non-smooth function to give the integrator values that smoothly fit between the discrete 'buckets' of the histogram.
type: Question
has answer: http://stackoverflow.com/a/66230701
accepted answer: http://stackoverflow.com/a/66230701
tagged with: python-3.x
downvote count: 0
answer count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/86711180
favorite count: 0
has comment: http://stackoverflow.com/comment/86711341
type: AnsweredQuestion
upvote count: 1

http://stackoverflow.com/comment/86645959
type: Comment
has text: That works too. Any particular reason you prefer that? Subtracting 2 `Timedeltas` or 2 `datetimes` both end up in a `Timedelta`
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49808459

http://stackoverflow.com/comment/86757363
has text: Do you understand what the `key` parameter does?
comment on: http://stackoverflow.com/q/49871071
type: Comment
type: QuestionComment
score: 0

ggplot2
tags question: http://stackoverflow.com/q/49834828
type: Tag
tag name: ggplot2

http://stackoverflow.com/q/49871041
tagged with: dictionary
has title: Logging python dictionary where values may have unicode errors
has answer: http://stackoverflow.com/a/49871812
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/86757799
has comment: http://stackoverflow.com/comment/86758945
has comment: http://stackoverflow.com/comment/86761414
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86758910
answer count: 1
downvote count: 1
tagged with: logging
favorite count: 0
score: 3
tagged with: format
has comment: http://stackoverflow.com/comment/86767800
has body: I am trying to add verbose logs, to an existing script. This script fetches data through a soap client API, into a dictionary. I am using logging module and format function to log this dictionary as is. In some, cases I am getting unicode exception as below, because a value may have non-ascii characters, resulting in exceptions. Sample Ref: ref = {'Name': 'John', 'Surname': 'Doe', 'MI': None, 'Title': u'\xe2\x80\xa2\tEngineer_I'} '\xe2\x80\xa2\tEngineer_I', is .encode('utf-8') representation of the value returned though below query. Present code: logger = logging.getLogger(name) ref_data = soap_query() for ref in ref_data: logger.debug("This is the reference data: {}".format(ref)) Error: UnicodeEncodeError: 'ascii' codec can't encode character u'\u2022' in position 0: ordinal not in range(128) Traceback Traceback (most recent call last): File "stack.py", line 65, in &lt;module&gt; query_db(db_obj) File "stack.py", line 50, in query_db logger.info("This is the reference data: {}".format(ref)) UnicodeEncodeError: 'ascii' codec can't encode character u'\u2022' in position 0: ordinal not in range(128) Workaround To get around this, I wrote another function as below: # Dictionary comprehension to encode all unicode values as ascii and ignore errors def convert_to_str(ref): return {k: v.encode('ascii', 'ignore') if v else v for k, v in ref.iteritems()} Any better solution? This works for me but i want to know, if there is any better approach to handle this? Can i pass any argument to logger or format function to encode as ascii or ignore unicode errors? I am using Python 2.7.6
tagged with: python-unicode
tagged with: python
has comment: http://stackoverflow.com/comment/86767884
has comment: http://stackoverflow.com/comment/86764862

twilio
tag name: twilio
type: Tag
tags question: http://stackoverflow.com/q/49790437

http://stackoverflow.com/comment/86664979
score: 0
type: Comment
has text: what is the question, what is the problem you encounter ?
type: QuestionComment
comment on: http://stackoverflow.com/q/49824377

http://stackoverflow.com/q/49817762
has answer: http://stackoverflow.com/a/49817832
has body: I found a max_value (grayscale 2D array [50,200]) with max = numpy.amax(matrice) so it gives me a value. Now I want to know were I can find this value. I tried this code: for x in range (1,50): for y in range (1,200): if matrice[x,y]==max: print ("[%s,%s]",x,y) but it gives me an error message: "for y in range (1,200): IndentationError: expected an indented block" Can someone tell me what is the error or how I can find the address of this pixel?
score: 0
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/49817868
has answer: http://stackoverflow.com/a/49818547
type: Question
tagged with: numpy
tagged with: pixel
linked to: http://stackoverflow.com/q/45621722
has title: How to find the address of a value in an 2D array
has comment: http://stackoverflow.com/comment/86650306
tagged with: grayscale
type: UnansweredQuestion
tagged with: arrays
upvote count: 1
downvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/45621722

http://stackoverflow.com/comment/86664230
score: 0
comment on: http://stackoverflow.com/q/49824027
has text: @cᴏʟᴅsᴘᴇᴇᴅ I've been using integers and not strings. Same error.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49810526
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/86636367
accepted answer of: http://stackoverflow.com/q/49810087
answers question: http://stackoverflow.com/q/49810087
score: 0
has body: Adding on what cruisepandey said in python it's: driver.switch_to_window(driver.window_handles[-1]) -1 means the newly created page. you may also have to do something like: driver.switch_to_frame('foobar') if the website is divided in frames.

http://stackoverflow.com/comment/86821458
comment on: http://stackoverflow.com/q/49902914
type: Comment
type: QuestionComment
has text: `album` is a required field on your model, but you have excluded it from the fields in your `CreateSong` form, hence the error.
score: 0

http://stackoverflow.com/q/49843361
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/86724942
favorite count: 0
type: Question
tagged with: numpy
has title: SKlearn RandomForestClassifier ValueError: setting an array element with a sequence
type: UnansweredQuestion
tagged with: arrays
has body: I am passing a data frame with each row contains two columns that contains numpy arrays two randomforestclassifier i.e. it gives me this error --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-110-e0a56908e930&gt; in &lt;module&gt;() 1 clf = RandomForestClassifier(max_depth=2) ----&gt; 2 clf.fit(X_train, y_train) sklearn\ensemble\forest.py in fit(self, X, y, sample_weight) 245 """ 246 # Validate or convert input data --&gt; 247 X = check_array(X, accept_sparse="csc", dtype=DTYPE) 248 y = check_array(y, accept_sparse='csc', ensure_2d=False, dtype=None) 249 if sample_weight is not None: sklearn\utils\validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator) 431 force_all_finite) 432 else: --&gt; 433 array = np.array(array, dtype=dtype, order=order, copy=copy) 434 435 if ensure_2d: ValueError: setting an array element with a sequence. I have went through two nearly same issues here on stack overflow with no useful answers, that's why I created a new question
has comment: http://stackoverflow.com/comment/86733207
tagged with: python
has comment: http://stackoverflow.com/comment/86729472
score: 0
has comment: http://stackoverflow.com/comment/86766866
has comment: http://stackoverflow.com/comment/86732458
answer count: 0
has comment: http://stackoverflow.com/comment/86706156
has comment: http://stackoverflow.com/comment/86729617
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/86698632
type: Comment
comment on: http://stackoverflow.com/a/49841975
type: AnswerComment
has text: Ok thank you to both! I am new to python so I will try to build my script following your advice and using a dict. Will learn something on the way for sure!
score: 1

http://stackoverflow.com/q/49835865
downvote count: 0
tagged with: moviepy
has comment: http://stackoverflow.com/comment/86693541
favorite count: 0
type: Question
has title: Compositing two soundtracks with moviepy
upvote count: 2
has answer: http://stackoverflow.com/a/54200806
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86697377
tagged with: python
score: 2
has body: I am trying to add an audio to a clip. Problem is it's replacing the original soundtrack with the new one i.e. pond5.wav. I first concat some small clips, each of these clips contain original soundtrack. The end result doesn't contain the original soundtracks, however. I need both original and new soundtracks (the new sound track's volume must be lower than the original). I need clues how to modify the following code and composite two soundtracks. media = "promo" clips = [VideoFileClip(clip) for clip in get_filepaths(media) if ntpath.basename(clip).startswith('clip_') and ntpath.basename(clip).endswith('.mp4') ] vclip = concatenate_videoclips([clips[0], clips[1].crossfadein(0.3), clips[2].crossfadein(0.3), clips[3].crossfadein(0.3), ], method="compose", padding=-0.3) audio = AudioFileClip(os.path.join(folder,"pond5.wav")) audio = audio.audio_loop(duration=vclip.duration) cc = vclip.set_audio(audio .set_duration(vclip.duration) .volumex(0.3) .audio_fadein(1.0) .audio_fadeout(1.0) ) cc.write_videofile(os.path.join(folder, "demo.mp4"), fps=60, codec="libx264", bitrate="20000k", threads=6)
linked to: http://stackoverflow.com/q/41992335
answer count: 1

http://stackoverflow.com/comment/131410584
has text: It may have been fixed after 3.2
comment on: http://stackoverflow.com/q/49819773
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86666021
type: AnswerComment
has text: If you wait for a title change and the title is wrong, you wont get a timeout but you will fail the assert. If you wait for a specific title change and the title is wrong, you will get a timeout exception instead of an assert fail. I would prefer to get the assert fail rather than a timeout exception but maybe that's just me.
comment on: http://stackoverflow.com/a/49823819
score: 0
type: Comment

http://stackoverflow.com/comment/86601738
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49793366
has text: Do you mean `\mathrm{A}`?
type: Comment

http://stackoverflow.com/comment/86622090
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49778663
has text: Im confused... It seems like in pages encoded with UTF-8 both encoding and decoding works just fine, but still in this site Encoding gets the error above anf decode returns : 'UnicodeEncodeError: 'ascii' codec can't encode characters in position 7189-7190: ordinal not in range(128)'

http://stackoverflow.com/q/49876832
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49880050
tagged with: openpyxl
has answer: http://stackoverflow.com/a/49877186
has title: Cannot run generated .exe with py2exe
tagged with: py2exe
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/27766435
has answer: http://stackoverflow.com/a/50024228
tagged with: python
has body: I am trying to generate aa .exe using py2exe for a python script that generates an excel. Here is just a sample code. I am writing value 100 to a cell and saving the excel to Users Desktop using openpyxl. This works perfectly fine when I run it directly. import openpyxl import getpass wb = openpyxl.Workbook() ws = wb.create_sheet('test') ws.cell(row=1, column=1, value=100) username = getpass.getuser() wb.save('C:\\Users\\{}\\create_exe\\gen.xlsx'.format(username)) print 'Done' And when I compile it using py2exe it compiles also just fine. The problem arises when I run the generated .exe file. I get a return saying ImportError: No module named jdcal setup.py file is as follows import py2exe from distutils.core import setup packages = ["openpyxl", "openpyxl.workbook", "xml.etree", "xml"] excludes = [] setup(console=['test_program.py'], options={"py2exe": {"excludes": excludes, "packages": packages}} ) Thisngs I have already tried I have searched and few people said Install openpyxl using pip. I have done that and pip says its alöready installed. I have also tried to install jdcal using pip and pip says it is installed. I have uninstalled jdcal and installed it using pip and manually, and still the same error. I have included jdcal in the packages and still no change in the outcome. I hope someone can help me with it. Thanks in advance EDIT : Generated Filed in dist folder are as follows (openpyxl cannot be seen here, I don't know why) tcl (Folder) _ctypes.pyd _elementtree.pyd _hashlib.pyd _multiprocessing.pyd _socket.pyd _ssl.pyd _tkinter.pyd bz2.pyd pyexpat.pyd select.pyd unicodedata.pyd win32ui.pyd numpy.core._dummy.pyd numpy.core.multiarray.pyd numpy.core.multiarray_tests.pyd numpy.core.operand_flag_tests.pyd numpy.core.struct_ufunc_test.pyd numpy.core.test_rational.pyd numpy.core.umath.pyd numpy.core.umath_tests.pyd numpy.fft.fftpack_lite.pyd numpy.linalg._umath_linalg.pyd numpy.linalg.lapack_lite.pyd numpy.random.mtrand.pyd _win32sysloader.pyd win32api.pyd win32p…

http://stackoverflow.com/q/49819657
score: 0
has comment: http://stackoverflow.com/comment/86654449
linked to: http://stackoverflow.com/q/2777188
has comment: http://stackoverflow.com/comment/86655084
has comment: http://stackoverflow.com/comment/86654339
has body: What's the most effective way to do something like this C code for(int i = 0; i &lt; 10; i++) { printf("%d\n", i); if(i == 5) i = 1; } in python, so the output would be 0 1 2 3 4 5 1 2 3 4 5 1 I know there is for in range with next() iterator = iter(range(0, 10)) for i in iterator: next(iterator) print(i) so this code would print every second number, but I don't know how to jump back in for loop.
has comment: http://stackoverflow.com/comment/86654742
has title: Jump back in python iterator
has answer: http://stackoverflow.com/a/49819991
type: Question
tagged with: python-3.x
tagged with: for-loop
possible better answer: http://stackoverflow.com/a/49819731
has comment: http://stackoverflow.com/comment/86654320
has answer: http://stackoverflow.com/a/49819731
tagged with: python
has comment: http://stackoverflow.com/comment/86654335
accepted answer: http://stackoverflow.com/a/49820100
answer count: 4
has answer: http://stackoverflow.com/a/49826805
has answer: http://stackoverflow.com/a/49820100
type: AnsweredQuestion

http://stackoverflow.com/a/49798710
has comment: http://stackoverflow.com/comment/86625763
downvote count: 0
has body: Yes and yes. You can get rid of the loops and it will speed up things: &gt;&gt;&gt; a = np.concatenate([p1,p2,p3,p4,p5,p6,p7,p8,p9,p10]) &gt;&gt;&gt; np.flatnonzero(np.bincount(a, minlength=314000)==4) array([ 29, 33, 38, ..., 313944, 313949, 313973])
type: AcceptedAnswer
score: 3
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/49798451
answers question: http://stackoverflow.com/q/49798451

http://stackoverflow.com/comment/86660900
has text: Is there a way to join the subsets of e.g. Attributes with a ", " instead of all "or"s?
type: Comment
comment on: http://stackoverflow.com/a/49821524
score: 0
type: AnswerComment

http://stackoverflow.com/q/49833200
has comment: http://stackoverflow.com/comment/86681775
tagged with: numpy
has comment: http://stackoverflow.com/comment/86954113
has title: cython version of multi_dot based on np.dot
type: Question
linked to: http://stackoverflow.com/q/45852228
score: 0
has comment: http://stackoverflow.com/comment/86681671
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86683948
has comment: http://stackoverflow.com/comment/86683160
has body: I have to optimize a python code with cython. The code has a lot of vectors and matrices dot products, which is the key of the optimization procedure. The products are in chain like : A.B.C.D.e where e can be a vector and A,B,C,D are matrices. I'm using numpy to represent all the objects. Originally, I used numpy.linalg.multi_dot. I read here that multi_dot can be more efficient than np.dot because it tries to optimize operation order. However, in my case, the matrices are small and using multi_dot is about 10x slower than doing a chain of np.dot. However, the syntax of multi_dot is nice and there are thousands of lines in the code doing products of different numbers of matrices and vectors. Re-writing all these lines using np.dot would really loose readability for other developers. Creating a pure python equivalent of multi_dot based on np.dot was easy, but I'd like to Cythonize it. The fact that I don't know the number of matrices given as arguments of multi_dot at compilation time forces me to call the python interpretor. Here is the code I wrote: @cython.boundscheck(False) @cython.wraparound=False cpdef mymultidot(np_array_list): cdef int n=len(np_array_list) R=np_array_list[0] for i in range(1,n): R=np.dot(R,np_array_list[i]) Is there a way to reduce python calls in this function? In particular, not deducing type of np_array_list at execution time? Maybe deduce the type of np_array_list at compile time something like list_of ( np.ndarray[np.float_t, ndim=2] )? But not knowing the size of the list will make it difficult. Is there a way in Cython to have methods with the same name but not the same arguments like in C/C++? So that I could create mymultidot( np.ndarray[np.float_t, ndim=2], np.ndarray[np.float_t, ndim=2], np.ndarray[np.float_t, ndim=2]) mymultidot( np.ndarray[np.float_t, ndim=2], np.ndarray[np.float_t, ndim=2]) mymultidot( np.ndarray[np.float_t, ndim=2], np.ndarray[np.float_t, ndim=1]) ... and so on? It will be long to write all the versions existin…
has comment: http://stackoverflow.com/comment/86738466
has comment: http://stackoverflow.com/comment/86684215
tagged with: python
tagged with: cython

http://stackoverflow.com/a/49760648
type: Answer
score: 2
upvote count: 2
has body: You first need to convert your string to a date object: from datetime import date your_date_string = '1982,14,4' year, day, month = [int(f) for f in your_date_string.split(',')] your_date = date(year, month, day) And then use that date object to compute the number of years. A quick and easy way to do that is to rely on dateutil third-party library that you can install using pip install dateutil. Here is an example: from dateutil.relativedelta import relativedelta difference_in_years = relativedelta(date.today(), your_date).years In this example, difference_in_years = 35.
answers question: http://stackoverflow.com/q/49760454
downvote count: 0

http://stackoverflow.com/q/49876974
has comment: http://stackoverflow.com/comment/86829683
favorite count: 0
has answer: http://stackoverflow.com/a/49877142
type: Question
tagged with: python-3.x
has body: I am .xls file and i have column of timestamp with following format of timestamp 2018-04-01 00:01:45 2018-04-01 00:16:45 2018-04-01 00:31:46 2018-04-01 00:46:45 2018-04-01 01:01:46 2018-04-01 01:16:45 2018-04-01 01:31:50 2018-04-01 01:46:45 2018-04-01 02:01:46 I Have another column with in same .xls file by name of temperature with following format 34 34 34 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 I want to plot values versus time . I tried to plot it but i am having issues in plotting it as it is not correctly reading the timestamp My code : #changing timestamp data from object to datatype w = df['Timestamp'] // column name "Timestamp" was creating issue so i have to remove it" w=w.drop(w.index[0]) //converting timestamp type object to datetime w = pd.to_datetime(w) area = (12 * np.random.rand(N))**2 # 0 to 15 point radii plt.xlabel('Temperature') plt.ylabel('DateTime') plt.title('Temperature and DateTime Relation') plt.scatter(t, w, s=area, c='purple', alpha=0.5) plt.show() Its Giving me error "TypeError: invalid type promotion"
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: pandas
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86769562
has title: Plotting time stamp column versus another column in Python
downvote count: 1

http://stackoverflow.com/comment/86865139
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49885379
type: AnswerComment
has text: Thanks for the guidance. That works as you say *if you do not rescale the data* with StandardScaler().fit_transform(). My understanding is that it's good PCA practice to rescale data that have very different ranges. So the question remains, how do I back transform the *scaled* cluster centers to the original data range?

http://stackoverflow.com/comment/127820397
comment on: http://stackoverflow.com/a/66440775
score: 0
has text: Instead of using `predicted`, pick the predicted class you want to view the `accuracy_score` for. Use one of `predicted[:,0]` or `predicted[:,1]`, instead of `predicted`.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86750941
has text: I've been playing with your suggestion. Please see Edit 2 to my original question.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49865085
type: AnswerComment

http://stackoverflow.com/a/60517449
has body: No, they will enter the queue in the order they finish, not in the order they were started. This means that if you start your processes with a certain order in mind, they may or may not finish in that order. If order is important to you, you should pass back the starting order with your results in the queue, perhaps as a tuple queue.put((order, result)). Here's an example showing the random order you get out of the queue. (Which is still FIFO) import multiprocessing import random import time def square(x, queue): # Sleep for a value between 0 and 1. time.sleep(random.random()) queue.put(x**2) queue = multiprocessing.Queue() for i in range(10): process = multiprocessing.Process(target = square, args = (i, queue)) process.start() results = [] for i in range(10): results.append(queue.get()) print (results) This gave me [25, 16, 9, 0, 36, 64, 81, 1, 49, 4]. Assuming your task is reasonably straight forward, I always prefer using Python's Pool functionality and its corresponding pool.map() function which does guarantee that output order is preserved according to input order.
score: 10
type: Answer
upvote count: 10
has comment: http://stackoverflow.com/comment/125384108
answers question: http://stackoverflow.com/q/49858968
downvote count: 0

http://stackoverflow.com/comment/86675736
has text: @OlivierMelançon both solutions give `array([], dtype=int64)` in the case you mention.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49811961
type: AnswerComment

http://stackoverflow.com/comment/86676997
type: Comment
has text: This does work in the case of `to_datetime`, however, it can't be used for the slicing nor `date_range`. I know how to get around it, but it is such an inconvenience.
comment on: http://stackoverflow.com/a/49830836
score: 0
type: AnswerComment

http://stackoverflow.com/q/49804663
tagged with: jquery
tagged with: web.py
score: 0
has answer: http://stackoverflow.com/a/49812323
has title: Send data from Python backend to Highcharts while escaping quotes for date
answer count: 1
tagged with: python
tagged with: web
has body: I would highly appreciate any help on this. I'm constructing dynamic highcharts at the backend and would like to send the data along with html to the frontend. In highcharts, there is a specific field to accept Date such as: x:Date.UTC(2018,01,01) or x:2018-01-01. However, when I send dates from the backend, it is always surrounded by quotes,so it becomes: x:'Date.UTC(2018,01,01)' and x:'2018-01-01', which does not render the chart. Any suggestions on how to escape these quotes?
type: Question
type: UnansweredQuestion
tagged with: highcharts

http://stackoverflow.com/comment/86779535
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49881048
type: Comment
has text: I've heard `FunctionOne` described as "Pascal Case", and `functionOne` would be "Camel Case" (because it has a "hump" in the middle).

http://stackoverflow.com/a/49991357
has body: But if the curl command itself fails with error, or "tlsv1 alert protocol version" persists even after upgrading pip, it means your operating system's underlying OpenSSL library version&lt;1.0.1 or Python version&lt;2.7.9 (or &lt;3.4 in Python 3) do not support the newer TLS 1.2 protocol that pip needs to connect to PyPI since about a year ago. You can easily check it in Python interpreter: &gt;&gt;&gt; import ssl &gt;&gt;&gt; ssl.OPENSSL_VERSION 'OpenSSL 0.9.8o 01 Jun 2010' &gt;&gt;&gt; ssl.PROTOCOL_TLSv1_2 AttributeError: 'module' object has no attribute 'PROTOCOL_TLSv1_2' The AttributeError (instead of expected '5') means your Python stdlib ssl module, compiled against old openssl lib, is lacking support for the TLSv1.2 protocol (even if the openssl library can or could be updated later). Fortunately, it can be solved without upgrading Python (and the whole system), by manually installing extra Python packages -- the detailed step-by-step guide is available here on Stackoverflow. Note, curl and pip and wget all depend on the same OpenSSL lib for establishing SSL connections (use $ openssl version command). libcurl supports TLS 1.2 since curl version 7.34, but older curl versions should be able to connect if you had OpenSSL version 1.0.2 (or later). P.S. For Python 3, please use python3 and pip3 everywhere (unless you are in a venv/virtualenv), including the curl command from above: $ curl https://bootstrap.pypa.io/get-pip.py | python3 --user
has comment: http://stackoverflow.com/comment/90731459
type: Answer
answers question: http://stackoverflow.com/q/49768770
score: 31
upvote count: 31
downvote count: 0

http://stackoverflow.com/comment/86803658
type: QuestionComment
comment on: http://stackoverflow.com/q/49893941
score: 0
type: Comment
has text: you can import speedtest, as it is actually a python module, and call the functions natively. Please see documentation of speedtest-cli

http://stackoverflow.com/comment/86543902
type: QuestionComment
comment on: http://stackoverflow.com/q/49764144
has text: So what would you like it to do? I assume you are aware that a dictionary cannot have repeated keys?
score: 0
type: Comment

http://stackoverflow.com/comment/86703924
has text: do i need to change any index in mlab
score: 0
comment on: http://stackoverflow.com/q/49843914
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49868727
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86753480
score: 3
has body: EDIT: The solution was simply changing how I was opening the file (thanks Primusa), not how I was replacing the information. I am attempting to overwrite parts of a file, but my code does not work. When it runs, it completely erases everything in the file, leaving nothing behind. Here is my code: for fname in store: with open(fname + ".txt", "w+") as f: for line in f: c = store[fname] x = (c-1)%len(line.split(",")) y = m.floor((c-1)/len(line.split(","))) for n in range(y): f.readline() ldata = line.strip("\n").split(",") for i in range(len(ldata)): ldata[i] = int(ldata[i]) if w == None: ldata[x] += 1 elif w == True: ldata[x] += 2 elif w == False: ldata[x] -= 1 #s = line.find("\n") - 1 #f.truncate(s) f.write(str(ldata) + "\n") Key: fname: a string variable corresponding to a file name without the file type. store: a dictionary containing file name keys as string and integer values. f: a file containing multiple lines of integer lists. c: an integer variable used to determine the integer to be accessed. x and y: variables with values set as the column and row (respectively) of the integer to be accessed in the file. w: a variable stored as either a boolean or None, used to determine whether the accessed integer should increase or decrease, and by how much. s: a currently unused integer variable used to truncate part of the file. Example of use: Say I have a file Foo.txt, which has the following information stored in it: 0,2,3,7 11,3,6,4 I want to increase the "6" value by 2, so I run the code with w set to True and add "Foo" : 7 to store, since "6" is the 7th number in the file (regardless of list length). What should happen: Foo.txt is modified and now contains: 0,2,3,7 11,3,8,4 What actually happens: Foo.txt still exists, but now contains: Which is to say it is empty. What is wrong with my code? Am I handling the file incorrectly, the variable calculations, syntax, or something else entirely?
linked to: http://stackoverflow.com/q/17140886
has comment: http://stackoverflow.com/comment/86784681
tagged with: python
has title: Overwriting part of a file results in empty string Python 3
has comment: http://stackoverflow.com/comment/86753519
type: AnsweredQuestion
upvote count: 3
tagged with: overwrite
downvote count: 0
answer count: 1
tagged with: file
has answer: http://stackoverflow.com/a/49868776
accepted answer: http://stackoverflow.com/a/49868776
favorite count: 0

http://stackoverflow.com/comment/86691016
has text: @suyash999 please accept it as answer. Thank you :)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49817969

http://stackoverflow.com/q/49786727
tagged with: list
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49787104
has comment: http://stackoverflow.com/comment/86590522
has answer: http://stackoverflow.com/a/49786807
type: Question
has title: Find Max values within list
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4836710
has comment: http://stackoverflow.com/comment/86588819
has body: I have text file with parse logged file, file contains: file: output.log End result should be: 1. sorted the list with max number rt01,te1/1,111,11 rt02,te1/1,11,10 rt01,te1/2,122,20 rt02,te1/2,113,5 rt02,te1/3,10,1 rt03,te1/1,1,6 rt03,te1/2,11,8 Result: rt01,te1/2,122,20 rt01,te1/1,111,11 rt02,te1/1,11,10 rt03,te1/2,11,8 rt03,te1/1,1,6 rt02,te1/2,113,5 rt02,te1/3,10,1 What is the best way, to get the max value within the list: I try: results = [] top = [] bottom = [] found = 0 with open('Python/output.log', 'r') as f: for line in f: line = line.split(",") results.append(line) print results for i,j in enumerate(results[:-1]): #print results[i+1][3] if j[3] &gt; results[i+1][3]: top.append(j) elif results[i+1][3] &gt; top[3]: bottom.append(results[i+1]) if top[i-1][3] &gt; results[i+1][3]: top.append(j.pop()) bottom.append(j) #top.append(j[]) print(top) print(bottom)
tagged with: python
linked to: http://stackoverflow.com/q/1517793
has comment: http://stackoverflow.com/comment/86588825
has answer: http://stackoverflow.com/a/49786886

http://stackoverflow.com/comment/93623736
score: 0
type: AnswerComment
has text: How to print full tensor? in my case it print just `[[1 1 1]...]`
type: Comment
comment on: http://stackoverflow.com/a/49823563

http://stackoverflow.com/q/49779606
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49779784
tagged with: python-3.x
has title: How to make a function that can set a max size in stack?
downvote count: 3
score: -3
has comment: http://stackoverflow.com/comment/86574944
tagged with: python
type: AnsweredQuestion
upvote count: 0
has body: I made a stack below. Now I want to add a function or method that allows you to specify the maximum size of the stack. What do I need to change or add? class MyStack: def __init__(self): self.myList = [] self.top = -1 self.size = 0 def isEmpty(self): if (self.size &gt; 0): return False else: return True def push(self, item): self.myList.append(item) self.size = self.size + 1 self.top = self.top + 1 def pop(self): if self.isEmpty(): return None else: self.ret = self.myList.pop(self.top) self.size = self.top - 1 self.top = self.top - 1 return self.ret def peek(self): if self.isEmpty(): return None else: return self.myList[self.top]
tagged with: stack
answer count: 1
has answer: http://stackoverflow.com/a/49779784

http://stackoverflow.com/q/49834264
tagged with: python
tagged with: object-detection
has answer: http://stackoverflow.com/a/69310799
type: Question
has comment: http://stackoverflow.com/comment/86993985
tagged with: image-segmentation
score: 5
downvote count: 0
tagged with: image-processing
favorite count: 0
possible better answer: http://stackoverflow.com/a/52966430
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/86684041
has answer: http://stackoverflow.com/a/52966430
accepted answer: http://stackoverflow.com/a/51756526
upvote count: 5
has title: MRI (brain tumor) image processing and segmentation, skull removing
has answer: http://stackoverflow.com/a/51756526
has body: I need help for image segmentation. I have a MRI image of brain with tumor. I need to remove cranium (skull) from MRI and then segment only tumor object. How could I do that in python? with image processing. I have tried make contours, but I don't know how to find and remove the largest contour and get only brain without a skull. Thank's a lot. def get_brain(img): row_size = img.shape[0] col_size = img.shape[1] mean = np.mean(img) std = np.std(img) img = img - mean img = img / std middle = img[int(col_size / 5):int(col_size / 5 * 4), int(row_size / 5):int(row_size / 5 * 4)] mean = np.mean(middle) max = np.max(img) min = np.min(img) img[img == max] = mean img[img == min] = mean kmeans = KMeans(n_clusters=2).fit(np.reshape(middle, [np.prod(middle.shape), 1])) centers = sorted(kmeans.cluster_centers_.flatten()) threshold = np.mean(centers) thresh_img = np.where(img &lt; threshold, 1.0, 0.0) # threshold the image eroded = morphology.erosion(thresh_img, np.ones([3, 3])) dilation = morphology.dilation(eroded, np.ones([5, 5])) These images are similar to the ones I'm looking at: Thanks for answers.

http://stackoverflow.com/q/49813009
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86661785
tagged with: python
tagged with: kivy
score: 0
has comment: http://stackoverflow.com/comment/86661524
tagged with: widget
has title: Updating widgets in kivy (python)
answer count: 1
has answer: http://stackoverflow.com/a/49813127
has body: Can anyone explain to me how you update widgets in kivy? I have a code sample here: class Game(Widget): def __init__(self, **kwargs): super(Game, self).__init__(**kwargs) with self.canvas: Color(*sky_color) Rectangle(pos=(0, 0), size=self.size) with self.canvas: Color(*grass_color) Rectangle(pos=(0,0), size=(800,75)) with self.canvas: Label(text='Funky Chicken', font_size='50sp', pos=(360, 400)) with self.canvas: Button(text='Play', font_size='20') class FunkyChickenApp(App): def build(self): return Game(size=Window.size) if __name__ == "__main__": FunkyChickenApp().run() This is supposed to be a game menu so some labels and stuff have to change when you press some buttons. Edit* What i mean is how do I use Kivy clock
has comment: http://stackoverflow.com/comment/86660078
type: Question

http://stackoverflow.com/a/78953191
answers question: http://stackoverflow.com/q/49841577
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/139233682
has body: use a list like this >>> import ctypes >>> a = ["hello world!"] >>> ctypes.cast(id(a), ctypes.py_object).value[0] = "new value" >>> print(a) ['new value']

http://stackoverflow.com/a/49844633
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86704269
answers question: http://stackoverflow.com/q/49844496
accepted answer of: http://stackoverflow.com/q/49844496
type: Answer
has body: One way is to use numpy.digitize to bin your categories. Then use a dictionary or list comprehension to calculate results. import numpy as np chl = np.array([0.4,0.1,0.04,0.05,0.4,0.2,0.6,0.09,0.23,0.43,0.65,0.22,0.12,0.2,0.33]) depth = np.array([0.1,0.3,0.31,0.44,0.49,1.1,1.145,1.33,1.49,1.53,1.67,1.79,1.87,2.1,2.3]) bins = np.array([0,0.5,1.0,1.5,2.0,2.5]) A = np.vstack((np.digitize(depth, bins), chl)).T res = {bins[int(i)]: np.mean(A[A[:, 0] == i, 1]) for i in np.unique(A[:, 0])} # {0.5: 0.198, 1.5: 0.28, 2.0: 0.355, 2.5: 0.265} Or for the precise format you are after: res_lst = [np.mean(A[A[:, 0] == i, 1]) for i in range(len(bins))] # [nan, 0.198, nan, 0.28, 0.355, 0.265]
score: 3
upvote count: 3

http://stackoverflow.com/comment/86805456
comment on: http://stackoverflow.com/q/49857395
has text: Did either of the posted solutions work for you?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49792539
tagged with: sockets
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51705957
has comment: http://stackoverflow.com/comment/90379694
has comment: http://stackoverflow.com/comment/86648325
has title: Invalid argument when trying to bind python socket to IPv6 address
score: 3
has body: I'm trying from my virtual machine to bind my socket in python to the address of my other virtual machine so that I could sniff the frames that are exchanged by the two. So here's my code import socket UDP_IP = "fe80:849b:21f4:624c:d70b" UDP_PORT = 61627 sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) sock.bind((UDP_IP, UDP_PORT)) while True: data, addr = sock.recvfrom(1024) print(data) When I try to execute my python, I get an error message : sock.bind((UDP_IP, UDP_PORT)) socket.error: [Error 22] Invalid argument What am I doing wrong, thanks in advance !
tagged with: udp
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/86619254
favorite count: 0
type: Question
tagged with: ipv6
type: UnansweredQuestion

http://stackoverflow.com/q/49821169
type: Question
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/49821549
type: UnansweredQuestion
tagged with: python
tagged with: numpy
has comment: http://stackoverflow.com/comment/86658137
has body: I converted a PIL image into a 3-dimension Numpy matrix, but the values of each pixel go from -1.88 to 3.36. How could I save it into a png file?
has comment: http://stackoverflow.com/comment/86657775
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: I have a PIL image in a Numpy matrix that has negative values. How could I save it?
favorite count: 0

http://stackoverflow.com/comment/86588488
score: 0
type: Comment
type: QuestionComment
has text: Provide us that link.
comment on: http://stackoverflow.com/q/49786276

http://stackoverflow.com/comment/86564123
comment on: http://stackoverflow.com/q/49774630
type: Comment
score: 0
has text: You don't. `whatever` is an implementation detail of the function `main`, if it were publicly accessible in the module it would not have been nested.
type: QuestionComment

http://stackoverflow.com/a/49818351
upvote count: 5
score: 5
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49817518
has body: The queue hello in the default vhost / already exists but it is declared as durable. Either delete this queue before you execute your code or declare it as durable from Python: channel.queue_declare(queue='hello', durable=True) See the section 'Message durability' of the tutorial.

twos-complement
tags question: http://stackoverflow.com/q/49862614
tag name: twos-complement
type: Tag

http://stackoverflow.com/comment/86779555
has text: @JohnColeman "OP would need to clarify" is an understatement :) thanks, I think there's no other way to interpret OP question, and the fine tuning you're noting can be added without changing the bulk of the answer.
score: 0
comment on: http://stackoverflow.com/a/49881681
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86621547
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49801685
has text: Happy it helped.

http://stackoverflow.com/comment/107271841
score: 0
type: AnswerComment
type: Comment
has text: I just had cache issues, too, despite `debug=true`. Explicitly clearing the templates before `bottle.template()` resolved it for my script. Possibly related: https://stackoverflow.com/questions/9073645/bottle-py-caching-templates-despite-being-in-debug-mode https://stackoverflow.com/questions/29759636/bottle-framework-caches-my-template-even-in-debug-mode
comment on: http://stackoverflow.com/a/49806166

http://stackoverflow.com/q/49797837
tagged with: python
type: AnsweredQuestion
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49797947
downvote count: 0
has answer: http://stackoverflow.com/a/49797947
upvote count: 1
has title: Find date name in datetime column with user input as weekday name as a 'String'
favorite count: 0
type: Question
has body: I have a datetime column called 'Start Time' I am trying to find entries with a specific weekday name based on user input. The user input is a String and can be Sunday, Monday,...Saturday. So if Sunday is input I want to find all entries that have Sunday as the day, regardless of the month or year. Here is my code: user_day = input('Input the name of the day.user_day.') print(df[df['Start Time'].dt.weekday == dt.datetime.strptime(user_day, '%A')]) The output is: Empty DataFrame Columns: [Unnamed: 0, Start Time, End Time, Trip Duration, Start Station, End Station, User Type] Index: []
possible better answer: http://stackoverflow.com/a/49798035
score: 1
has answer: http://stackoverflow.com/a/49798035

http://stackoverflow.com/comment/86826269
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49902533
has text: I'm quite baffled that something so simple to do in cmd and python and C# is becoming quite a headache.
type: Comment

http://stackoverflow.com/a/49822495
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: Using your combine dataframe dfs you can use pd.crosstab to get the counts of customers tag usages pd.crosstab(dfs.var1,dfs.var2) var2 chocolate glazed sprinkles var1 A 3 0 3 B 2 0 2 C 1 2 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49822030
accepted answer of: http://stackoverflow.com/q/49822030

http://stackoverflow.com/a/49886874
has comment: http://stackoverflow.com/comment/86789911
type: Answer
has body: I think you are looking to use igraph.Graph.Adjacency, not igraph.Graph.adj. You are trying to call a method that does not exist. http://igraph.org/python/doc/igraph.GraphBase-class.html#Adjacency igraph Graph from numpy or pandas adjacency matrix
score: 0
has comment: http://stackoverflow.com/comment/86789982
answers question: http://stackoverflow.com/q/49886746

http://stackoverflow.com/q/49854070
answer count: 1
has answer: http://stackoverflow.com/a/49854725
tagged with: machine-learning
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/86723566
score: 0
tagged with: categorical-data
has body: I have a dataset with categorical data that are of different weights, take for an instance Phd has a higher weight than Masters and like MSc is higher than Bsc. I know am to use Label encoder but i dont want python to assigned codes to these variables arbitrarily. I want higher codes for Phd = 4, Msc = 3 , Bsc = 2, O Levels = 1 and No education = 0. Is there anyway i can go about this? Can anyone be of help?
tagged with: python
linked to: http://stackoverflow.com/q/16992713
type: Question
has title: Ordinal Categorical Data in Regression
type: UnansweredQuestion

http://stackoverflow.com/comment/86615562
has text: did you check [keras.layers.normalization.BatchNormalization](https://faroit.github.io/keras-docs/1.2.0/layers/normalization/) already?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49800045
score: 0

http://stackoverflow.com/comment/86742292
comment on: http://stackoverflow.com/a/49862889
score: 0
type: Comment
has text: I think this will work! thank you! If i run into a snag il reply again.
type: AnswerComment

http://stackoverflow.com/comment/86690506
type: AnswerComment
comment on: http://stackoverflow.com/a/49837559
type: Comment
has text: I should have specified that I was using Windows earlier. The help file for 'sigwait' states that it is only available on Unix.
score: 0

http://stackoverflow.com/comment/86793608
comment on: http://stackoverflow.com/a/49837908
type: Comment
has text: What's your image source? If you have a bunch of files on disk (or in a zip file) you can make a dataset of just their filenames, shuffle/repeat these, then load them in a map call. Alternatively you could convert them to tfrecords. That's supposedly faster, but it will take up a chunk of additinal memory, they're hard to debug and I've never noticed a speed difference so long as you're using pretetch and your entire process is GPU constrained.
type: AnswerComment
score: 0

http://stackoverflow.com/q/49850429
type: Question
tagged with: numpy
tagged with: colormap
accepted answer: http://stackoverflow.com/a/49993092
has answer: http://stackoverflow.com/a/49993092
tagged with: matplotlib
tagged with: python
type: AnsweredQuestion
has title: Manually create a colormap
score: 3
has body: I am using a scatter plot to create a heat map. I have used the Greys colormap to display the dense area's as black and the light areas as white. So the areas with more xy points as black and less xy as white. This works fine but the areas without data is too white for this application. Because I have background data displayed on the plot, if the map is too white this data is very hard to see. Therefore, I'm trying to create a colormap were the contrast between black and white isn't so great. I'd like it go to between black and a very light grey. Initial code is shown here: import matplotlib.pyplot as plt import numpy as np import random x = [random.randrange(1,101,1) for _ in range (10)] y = [random.randrange(1,101,1) for _ in range (10)] fig, ax1 = plt.subplots() ax1.grid(False) data1,x,y,p = plt.hist2d(x,y, bins = 10, range = np.array([(0,80), (0,80)])) ax1.imshow(data1, interpolation = 'gaussian', origin = 'lower', extent = [0,100,0,100], cmap = 'Greys') The areas without xy data are very white and anything displayed in these areas are hard to see. So I imported my own colormap were the lightest colour is grey. cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["gainsboro","lightgrey","lightgrey","silver","silver","darkgray","darkgray","gray","gray","dimgray","dimgray","black","black"]) This is ok but I'd like like there to be a bigger contrast from black to light grey. Specifically, I'd like it to go lighter grey. The areas with no data (which would be white) are too dark. It only goes from grey to black. Is there another way to create a colormap that has a bigger contrast in colors that doesn't go completely to white. I know it sounds vague but I was hoping it would go from black down to a very light grey. Is there a way to manually play with the contrast?
tagged with: pandas
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/49772415
accepted answer: http://stackoverflow.com/a/49772511
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49772601
possible better answer: http://stackoverflow.com/a/49772601
upvote count: 1
downvote count: 0
tagged with: python
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: regex
has title: How to find information between two words excluding white spaces using python re?
has answer: http://stackoverflow.com/a/49772511
has body: Hi I am trying to develop a script using python that detects if there is something between two words. I am using regular expression r'Madrid:(.*?)Newyork' for this: import re string_1 = "Madrid: good bars Newyork: good building Warranty: No" pattern = r'Madrid:(.*?)Newyork' searchObj = re.search(pattern, string_1, re.I) if searchObj: return True else: return False This is working fine the problem is that it also detects whitespaces, and when I have whitespaces it should not find anything. I would like to develop an expression that excludes a whitespace from the match. For example, for these two is match is true and should be false: string_2 = "Madrid: Newyork: good building Warranty: No" string_3 = "Madrid: Newyork: good building Warranty: No" I am trying with [^\s] but Is not working, any help?

http://stackoverflow.com/a/49903930
has comment: http://stackoverflow.com/comment/116357398
has comment: http://stackoverflow.com/comment/86824005
downvote count: 0
type: Answer
has body: I would suggest using the formatters within the to_html function, description of the parameter: formatters : list or dict of one-parameter functions, optional formatter functions to apply to columns’ elements by position or name, default None. The result of each function must be a unicode string. List must be of length equal to the number of columns. Example if you want to make all your Name column bold: df.to_html(formatters={'Name': lambda x: '&lt;b&gt;' + x + '&lt;/b&gt;'}) Let me know whether it works!
has comment: http://stackoverflow.com/comment/114912489
has comment: http://stackoverflow.com/comment/86824894
has comment: http://stackoverflow.com/comment/86823664
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49903773
has comment: http://stackoverflow.com/comment/86825080
has comment: http://stackoverflow.com/comment/86834935
has comment: http://stackoverflow.com/comment/86824172
has comment: http://stackoverflow.com/comment/86823877
has comment: http://stackoverflow.com/comment/86824323
score: 12
answers question: http://stackoverflow.com/q/49903773
upvote count: 12

http://stackoverflow.com/comment/86701094
has text: It's interesting that this error only happened when I connected from google cloud vm instance. Azsgy There is no proxy in my google cloud network settings. @Steffen Ullrich adding -servername seems making difference: depth=2 C = US, O = "Entrust, Inc.", OU = See www.entrust.net/legal-terms, OU = "(c) 2009 Entrust, Inc. - for authorized use only", CN = Entrust Root Certification Authority - G2 verify error:num=19:self signed certificate in certificate chain So this means I get difference certificate from google cloud which contains a self signed certificate I guess?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49825793

http://stackoverflow.com/a/49789424
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49789332
upvote count: 3
downvote count: 0
has body: The syntax (x) = generator(1) is not a tuple of one item. You want: (x,) = generator(1) or x, = generator(1) Then you'll find the generator is called, just as in your other examples, due to "unpacking". Note that in the expression (x, y) it is not the () that make it a tuple, it is the comma. The parentheses simply bound the expression x, y.

http://stackoverflow.com/q/49837479
tagged with: arrays
downvote count: 0
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/86690232
type: AnsweredQuestion
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/86690214
possible better answer: http://stackoverflow.com/a/49837537
accepted answer: http://stackoverflow.com/a/49837502
has title: print an array with all the possible mean
favorite count: 0
has answer: http://stackoverflow.com/a/49837537
type: Question
has answer: http://stackoverflow.com/a/49837502
linked to: http://stackoverflow.com/q/464864
has body: Suppose I have a list 'a'. Now, I want to print a list with all the possible mean(only integers) from all the possible pairs of list 'a'.For example: a = [0,0,3,4,1,2,9] Now, I want to print a list b such that; b = [0,2,1,2,1,2,6,3,5] If (a,b) is taken as a pair then (b,a) wont count. But it would count if there are duplicates of a and b present.
upvote count: 2
tagged with: mean
tagged with: python-3.5

http://stackoverflow.com/q/49859183
has comment: http://stackoverflow.com/comment/86733441
has title: Function return only first output value by default
has comment: http://stackoverflow.com/comment/86733324
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/32463205
has answer: http://stackoverflow.com/a/49859212
score: 1
has comment: http://stackoverflow.com/comment/86733514
has comment: http://stackoverflow.com/comment/86733384
has comment: http://stackoverflow.com/comment/86733325
duplicate of: http://stackoverflow.com/q/32463205
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86734168
has comment: http://stackoverflow.com/comment/86733665
possible better answer: http://stackoverflow.com/a/49859212
answer count: 2
accepted answer: http://stackoverflow.com/a/49859340
tagged with: function
has comment: http://stackoverflow.com/comment/86733476
has body: Suppose I have a function: def my_func(): return 1,2 What I want: If I call function like this: a = my_func() I want it to return only the first output parameter, i.e. 1; and if I call a,b = my_func() it returns both - a=1 and b=2. This task is about backward compatibility: I already have a lot of scripts when I use just a = my_func(), and now I want to add extra functionality. But now a is actually a tuple, consisting of both values: (1,2) Is it possible?
has answer: http://stackoverflow.com/a/49859340
downvote count: 0
has comment: http://stackoverflow.com/comment/86733368
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86733680
has comment: http://stackoverflow.com/comment/86733538

http://stackoverflow.com/q/49829789
accepted answer: http://stackoverflow.com/a/49829881
tagged with: python
has answer: http://stackoverflow.com/a/49829881
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49829866
answer count: 3
has answer: http://stackoverflow.com/a/49830024
upvote count: 1
downvote count: 1
has title: writing output to file in python
has body: I need to read input from a text file and create a new text file with the output in it. At the moment my code is reading fine but it is writing only the last line of data, not going through all the lines. Can someone please help me fix this? def generate_daily_totals(input_filename, output_filename): """Returns date followed by the sum of values""" infile = open(input_filename) for line in infile: content = line.split(",") date = content[0] total = 0 for value in content[1:]: total = total + float(value) rounded_total = "{:.2f}".format(total) summary = date + " " + "=" + " " + rounded_total outfile = open(output_filename, "w") outfile.write(summary) generate_daily_totals('data60.txt', 'totals60.txt') checker = open('totals60.txt') print(checker.read()) checker.close() The input is 2006-04-10,836.2,563.263 2006-04-10,462.06,1694.3,666.0 2006-04-10,1318.19,1485.62 2006-04-10,49.714,304.0,1269.0 2006-04-10,1360.0,1731.0,28.6 2006-04-10,998.879,890.264,367.0 2006-04-10,757.4,1501.05,861.6 2006-04-10,1218.0,270.0 What I am getting for output is 2006-04-10 = 1488.00 But the correct one should be 2006-04-10 = 1399.46 2006-04-10 = 2822.36 2006-04-10 = 2803.81 2006-04-10 = 1622.71 2006-04-10 = 3119.60 2006-04-10 = 2256.14 2006-04-10 = 3120.05 2006-04-10 = 1488.00
possible better answer: http://stackoverflow.com/a/49829866
favorite count: 0
tagged with: text-files
type: Question
has comment: http://stackoverflow.com/comment/86696111
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86674842

http://stackoverflow.com/q/49842165
tagged with: backtracking
has body: I have this code def swap(a, i, j): a[i], a[j] = a[j], a[i] def permute(a, i, n): if (a == b): print('String matched') else: if i == n: print(a) for j in range(i, n + 1): swap(a, i, j) permute(a, i + 1, n) swap(a, i, j) def main(): string = "ABCD" n = len(string) a = list(string) global b b = list("ABDC") permute(a, 0, n - 1) if __name__ == '__main__': main() My goal is to stop the loop when string a matched string b, but the program output is ['A', 'B', 'C', 'D'] String matched ['A', 'C', 'B', 'D'] ['A', 'C', 'D', 'B'] ['A', 'D', 'C', 'B'] ['A', 'D', 'B', 'C'] ['B', 'A', 'C', 'D'] ['B', 'A', 'D', 'C'] ['B', 'C', 'A', 'D'] ['B', 'C', 'D', 'A'] ['B', 'D', 'C', 'A'] ['B', 'D', 'A', 'C'] ['C', 'B', 'A', 'D'] ['C', 'B', 'D', 'A'] ['C', 'A', 'B', 'D'] ['C', 'A', 'D', 'B'] ['C', 'D', 'A', 'B'] ['C', 'D', 'B', 'A'] ['D', 'B', 'C', 'A'] ['D', 'B', 'A', 'C'] ['D', 'C', 'B', 'A'] ['D', 'C', 'A', 'B'] ['D', 'A', 'C', 'B'] ['D', 'A', 'B', 'C'] Process finished with exit code 0 as we can see, the "String matched" is replacing the matched string (which means the if-condition is working). My problem is, the loop still works after that. Next try: putting return false for the if-statement. The output is still the same unfortunately Does anyone knows how to stop the looping?
accepted answer: http://stackoverflow.com/a/49843861
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49843861
type: Question
tagged with: recursion
score: 0
possible better answer: http://stackoverflow.com/a/49844217
has title: Recursion won't stop executing after an if-statement
has answer: http://stackoverflow.com/a/49844217
tagged with: python
has comment: http://stackoverflow.com/comment/86699001

http://stackoverflow.com/comment/86704274
comment on: http://stackoverflow.com/a/49842389
type: Comment
score: 0
type: AnswerComment
has text: @sniperipp I don't have much experience in Python, you might want to place that as a new question.

http://stackoverflow.com/a/50152554
has body: To grab all text from a document, tree.descendants will be a lot more friendly here. This will output all text in order. def getText(section): for token in section.descendants: if isinstance(token, str): corpus.write(str(x)) To capture the edge cases, I wrote a slightly more fleshed-out version. This includes checks for all the conditions you've listed up there. from TexSoup import RArg def getText(section): for x in section.descendants: if isinstance(x, str): if x.startswith('$') and x.endswith('$'): continue corpus.write(str(x)) elif isinstance(x, RArg): corpus.write(str(x)) elif hasattr(x, 'source') and hasattr(x.source, 'name') and x.source.name in ('acknowledgements', 'appendix'): return
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49779853
type: Answer
has comment: http://stackoverflow.com/comment/94208554
score: 2
has comment: http://stackoverflow.com/comment/94218946

http://stackoverflow.com/comment/86820670
score: 0
has text: You missed a single quote after `df['filename`, is it a typo?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49902525

http://stackoverflow.com/comment/86632282
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49808639
has text: in this case i am trimming a generated hash to 8 chr instead of generating a 8 character hash, thats my problem

http://stackoverflow.com/comment/86633305
comment on: http://stackoverflow.com/a/49808218
score: 1
type: Comment
has text: @Evgenii, you have `test_hello.py` and `test_hello()` function, this could mess up the `import`, and I ran with `python -m pytest test_hello.py`
type: AnswerComment

http://stackoverflow.com/comment/86848442
comment on: http://stackoverflow.com/q/49916412
score: 2
type: Comment
type: QuestionComment
has text: Can you have one multi-level dict and store author and term in the same dict? Like d['id001']["authors"]=['author1', 'author2']; and d['id001']["terms"] = ['term1', 'term2']

http://stackoverflow.com/a/49817922
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86650538
has comment: http://stackoverflow.com/comment/86650886
has body: Try: data3 = Games.objects.filter( reduce(lambda x, y: x | y, [Q(id__contains=i.id) for i in data1]) | reduce(lambda x, y: x | y, [Q(id__contains=i.id) for i in data2]) )
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49817816
has comment: http://stackoverflow.com/comment/86650727
answers question: http://stackoverflow.com/q/49817816

http://stackoverflow.com/comment/86578735
score: 0
type: AnswerComment
has text: I think the alias approach matches my original need as it is the same as calling the function in the wrappedObject, right?
comment on: http://stackoverflow.com/a/49775407
type: Comment

http://stackoverflow.com/q/49837500
tagged with: python
has body: I made a neural network (which has unfortunately grown in complexity and become rather CPU intensive) which analyzes screenshots in real-time. I wish to pause it when I press the letter 'a' and un-pause it when the letter 'a' is pressed again. What is the most efficient way to pause it (without breaking the loop altogether)? It uses Python OpenCV library, but I don't use cv2.imshow, hence I can't use cv2.Waitkey. I'm running this on Windows 10. Could you please provide example code to your answer? Here's a bit of the code: import cv2 import mss from PIL import Image import numpy as np #Creates an endless loop for high-speed image acquisition... while (True): with mss.mss() as sct: # Get raw pixels from the screen sct_img = sct.grab(sct.monitors[1]) # Create the Image img = Image.frombytes('RGB', sct_img.size, sct_img.bgra, 'raw', 'BGRX') #The rest of the neural network goes here... #PAUSE statement...
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
answer count: 1
favorite count: 0
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/49837559
has title: What's the most efficient way to pause a CPU-intensive python program?

http://stackoverflow.com/q/49839176
has title: Reading CSV with newlines within row
type: Question
has comment: http://stackoverflow.com/comment/86693542
has comment: http://stackoverflow.com/comment/86693880
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/86694161
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49892943
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49892943
has comment: http://stackoverflow.com/comment/86693846
has body: I'm using Pandas to read a CSV file but some of the rows will continue on the next line and the delimiter(") will be at the start of the next line. I'm trying to find a parameter for 'pd.read_csv' that will fix it but after reading the documentation, I still not sure if there is one. Ex: "0","","0","0","0","0","0 ","0","0","0","0","0","0" In other words, "0","","0","0","0","0","0\r\n","0","0","0","0","0","0"
has comment: http://stackoverflow.com/comment/86694263
answer count: 1

http://stackoverflow.com/a/68603594
has body: You need to know first how the element interact with the user. In Chosen you need to click first the input field, and enter your keys in the box provided. This is how I did it (I'm using .Net) var eleChosen = driver.FindElementById("BodyContent_Element_chosen"); eleChosen.Click(); var eleInput = eleChosen.FindElement(By.XPath(".//input")); eleInput.SendKeys("First Choice"); eleInput.SendKeys(Keys.Tab);
score: 0
answers question: http://stackoverflow.com/q/49762941
type: Answer

http://stackoverflow.com/comment/86709498
has text: The best solution I'm aware of is to combine the results of `traceback.extract_tb` and `traceback.extract_stack`.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49847204
type: QuestionComment

http://stackoverflow.com/a/49770275
score: 3
has comment: http://stackoverflow.com/comment/86578246
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/49765174
downvote count: 0
has comment: http://stackoverflow.com/comment/86577776
has comment: http://stackoverflow.com/comment/86574735
has body: I wrote a module named JiTCODE, which creates ODE integrator objects (with a handling similar to scipy.integrate.ode) from symbolic expressions (SymPy or SymEngine) describing the right-hand side. Under the hood it uses scipy.integrate.ode and scipy.integrate.solve_ivp for the integration. The only drawback in your case is that the symbol for the dynamical variables and time is prescribed, so you might have to do a symbolic substitution – which should not be a big issue, however. Below, is your Lotka–Volterra equation as an example, using y(0) instead of x and y(1) instead of y. import numpy as np from sympy.abc import a,b,c,d from jitcode import y, jitcode xy0 = [600,400] argst = [0.4,0.002,0.001,0.7] lotka_volterra = [ a*y(0) - b*y(0)*y(1), -d*y(1) + c*y(0)*y(1) ] ODE = jitcode( lotka_volterra, control_pars=[a,b,c,d] ) ODE.set_integrator("dopri5") ODE.set_initial_value(xy0) ODE.set_parameters(*argst) times = np.linspace(0, 50, 250) xy_t = np.vstack(ODE.integrate(time) for time in times) Note that the main feature of this module is that the right-hand side is compiled for efficiency. Depending on what you need to do, this may be overkill, but it doesn’t harm if it works (you can also disable this and use lambdification as detailed in the other answer).
has comment: http://stackoverflow.com/comment/86578268

http://stackoverflow.com/a/49857570
score: 0
answers question: http://stackoverflow.com/q/49853772
has comment: http://stackoverflow.com/comment/86732227
has comment: http://stackoverflow.com/comment/86732473
has comment: http://stackoverflow.com/comment/86733909
has comment: http://stackoverflow.com/comment/86732331
type: Answer
has body: Not related: Why the extra dim? Are you using Conv2D? You should probably get better results with Conv1D, with (exams, timeSteps, channels). Also: did you make sure you're using data_format='channels_first'? Keras' default is data_format='channels_last'. Answer for Conv2D: You must choose a form of interacting the two sets of data. This interaction can be very creative and there is no rule. Two possibilities: Multiply this 1D value somewhere, or add, or think of nice operations (requires functional API model with two inputs). Add the age as an additional channel to every step (I like this one) Adding the age as an additional channel: x_with_age = np.empty((745,14,60,1)) age = age.reshape((745,1,1,1)) x_with_age[:,:13] = X x_with_age[:,-1:] = age Train the model using x_with_age as input. If following the Conv1D suggestion: #this is using channels_last, which is keras' default #if your data is channels_first, then just invert the shapes below X = should be something like (745, 60, 13) x_with_age = np.empty((745,60,14)) age = age.reshape((745,1,1)) x_with_age[:,:,:13] = X x_with_age[:,:,-1:] = age

http://stackoverflow.com/comment/86818793
comment on: http://stackoverflow.com/a/49886179
type: Comment
type: AnswerComment
has text: Oh, I didn't realize that was what you were referring to. I haven't used Visual Studio in years. My suspicion then is that the code never gets called. You could always add a logging call to the function too that just writes to a file whenever it gets called.
score: 0

http://stackoverflow.com/comment/86851976
type: QuestionComment
has text: Firstly, it's unclear what you mean by texture comparison. Secondly, when asking questions on SO, you need to show effort: what have you tried? Where is your code? What libraries are you using?
comment on: http://stackoverflow.com/q/49914471
score: 0
type: Comment

http://stackoverflow.com/a/49777083
has comment: http://stackoverflow.com/comment/86583401
type: Answer
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/86570101
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49776936
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49776936
has body: With assign df.assign(C=[{'M': [1, 2, 3]}]) A B C 0 1 f {'M': [1, 2, 3]}

http://stackoverflow.com/a/49810792
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/49810566
has body: @Maaaaa has pointed out the exact reason for incorrect text recognition by Tessearact. But still you can improve your final output by applying some post processing steps on the tesseract output. Here are a few points that you can think about and use them if it helps: Try disabling the dictionary check feature in Tesseract input parameters. Use heuristic based information from your dataset. From the given sample images in question, i guess first character of each word/sequence is an alphabet so you can replace first digit in your output with most probable alphabet based on your dataset, for example '0' can be replaced with D so '0001' -> 'D001', similarly for other cases too. Tesseract also provides the character level recognition confidence value, so use that information to replace the characters with the one having highest confidence value.
downvote count: 0
type: Answer

http://stackoverflow.com/a/49867727
type: Answer
answers question: http://stackoverflow.com/q/49867667
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has body: If your column EventTime is already a datetime type, you can do this: df.groupby(df['EventTime'].dt.date).mean()['Price'] Which gives you this: &gt;&gt;&gt; df.groupby(df['EventTime'].dt.date).mean()['Price'] EventTime 2015-03-30 2.5293 2015-03-31 2.7260 If not, simply cast it to pd.datetime first: df['EventTime'] = pd.to_datetime(df['EventTime']) df.groupby(df['EventTime'].dt.date).mean()['Price'] Explanation: using df['EventTime'].dt.date as the argument to your groupby ensures that you are grouping by the date only (ignoring the timestamp)
accepted answer of: http://stackoverflow.com/q/49867667

http://stackoverflow.com/comment/86820595
type: QuestionComment
has text: Yes or perhaps better practice would be to make a new column: if (str(data_file.col2[value]).find(text) != -1): data_file.loc[value, 'newcol'] = text else: data_file.loc[value, 'newcol'] = data_file.loc[value, 'col1']
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49902412

http://stackoverflow.com/comment/86604938
comment on: http://stackoverflow.com/a/49793958
score: 0
has text: Sorry to have been not clear: I want to go back to the previous state of variables (like is doing `case_courante`)
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49841716
score: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/99598860
favorite count: 0
has comment: http://stackoverflow.com/comment/86905053
type: Question
has comment: http://stackoverflow.com/comment/86866488
has title: Keras accuracy calculation and meaning
tagged with: neural-network
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/86704383
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86860044
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/86905468
linked to: http://stackoverflow.com/q/48775305
has body: I am detecting objects using CNN and keras When i test/train model it outputs acc and loss. I am using MSE loss functions so i understand what loss mean, however what is accuracy and how is it calculated? I have 4000 loss and accuracy 80% which is stupid. It does not detect object 80% correctly. What does it mean and how is it calcualted then? Thanks for help.
tagged with: machine-learning
upvote count: 1

http://stackoverflow.com/a/49823060
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49822552
score: 93
upvote count: 94
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49822552
has comment: http://stackoverflow.com/comment/86661922
has body: Only asynchronous (defined with async def) functions can be awaited. Whole idea is that such functions are written special way what makes possible to run (await) them without blocking event loop. If you want to get result from common (defined with def) function that takes some considerable time to be executed you have these options: rewrite this whole function to be asynchronous call this function in another thread and await for result asynchronously call this function in another process and await for result asynchronously Usually you want to choose second option. Here's example of how to do it: import asyncio import time from concurrent.futures import ThreadPoolExecutor _executor = ThreadPoolExecutor(1) def sync_blocking(): time.sleep(2) async def hello_world(): # run blocking function in another thread, # and wait for it's result: await loop.run_in_executor(_executor, sync_blocking) loop = asyncio.get_event_loop() loop.run_until_complete(hello_world()) loop.close() Please, read this answer about how asyncio works. I think it'll help you much.

generator
type: Tag
tags question: http://stackoverflow.com/q/49848989
tags question: http://stackoverflow.com/q/49838269
tags question: http://stackoverflow.com/q/49825809
tags question: http://stackoverflow.com/q/49782828
tags question: http://stackoverflow.com/q/49902780
tags question: http://stackoverflow.com/q/49789332
tags question: http://stackoverflow.com/q/49840621
tags question: http://stackoverflow.com/q/49905849
tag name: generator
tags question: http://stackoverflow.com/q/49864917
tags question: http://stackoverflow.com/q/49842115

http://stackoverflow.com/comment/86676769
comment on: http://stackoverflow.com/a/49830628
type: Comment
score: 0
type: AnswerComment
has text: Ok, thanks. And for i in x,y: gives an error "TypeError: list indices must be integers or slices, not list", even though i= [0, 1, 2, 2, 5, 2, 1, 0, 1, 2] and j = [0, 1, 3, 2, 1, 4, 1, 3, 1, 2], why is that. Is it because i can't take two values, and if we created a tuple instead it would store the values?

dataframe
tags question: http://stackoverflow.com/q/49843864
tags question: http://stackoverflow.com/q/49786769
tags question: http://stackoverflow.com/q/49902146
tags question: http://stackoverflow.com/q/49838956
tags question: http://stackoverflow.com/q/49863071
tags question: http://stackoverflow.com/q/49906137
tags question: http://stackoverflow.com/q/49859182
tags question: http://stackoverflow.com/q/49885060
tags question: http://stackoverflow.com/q/49890625
tags question: http://stackoverflow.com/q/49798099
tags question: http://stackoverflow.com/q/49854796
tags question: http://stackoverflow.com/q/49777274
tags question: http://stackoverflow.com/q/49845285
tags question: http://stackoverflow.com/q/49865057
tags question: http://stackoverflow.com/q/49898007
tags question: http://stackoverflow.com/q/49834916
tags question: http://stackoverflow.com/q/49823263
tags question: http://stackoverflow.com/q/49784279
tags question: http://stackoverflow.com/q/49909710
tags question: http://stackoverflow.com/q/49775571
tags question: http://stackoverflow.com/q/49863862
tags question: http://stackoverflow.com/q/49820691
tags question: http://stackoverflow.com/q/49818031
tags question: http://stackoverflow.com/q/49763220
tags question: http://stackoverflow.com/q/49889398
tags question: http://stackoverflow.com/q/49913887
tags question: http://stackoverflow.com/q/49886924
tags question: http://stackoverflow.com/q/49807976
tags question: http://stackoverflow.com/q/49856785
tags question: http://stackoverflow.com/q/49885411
tags question: http://stackoverflow.com/q/49798888
tags question: http://stackoverflow.com/q/49834133
tags question: http://stackoverflow.com/q/49830532
tags question: http://stackoverflow.com/q/49834793
tags question: http://stackoverflow.com/q/49759397
tags question: http://stackoverflow.com/q/49891200
tags question: http://stackoverflow.com/q/49775199
tags question: http://stackoverflow.com/q/49904983
tags question: http://stackoverflow.com/q/49860301
tags question: http://stackoverflow.com/q/49804691
tags question: http://stackoverflow.com/q/49798796
tags question: http://stackoverflow.com/q/49864278
tags question: http://stackoverflow.com/q/49847730
tags question: http://stackoverflow.com/q/49786312
tags question: http://stackoverflow.com/q/49793922
tags question: http://stackoverflow.com/q/49787099
tags question: http://stackoverflow.com/q/49793977
tags question: http://stackoverflow.com/q/49876449
tags question: http://stackoverflow.com/q/49854722
tags question: http://stackoverflow.com/q/49848273
tags question: http://stackoverflow.com/q/49846754
tags question: http://stackoverflow.com/q/49847771
tags question: http://stackoverflow.com/q/49906526
tags question: http://stackoverflow.com/q/49908710
tags question: http://stackoverflow.com/q/49786024
tags question: http://stackoverflow.com/q/49847684
tags question: http://stackoverflow.com/q/49801805
tags question: http://stackoverflow.com/q/49795825
tags question: http://stackoverflow.com/q/49875520
tags question: http://stackoverflow.com/q/49843444
tags question: http://stackoverflow.com/q/49767227
tags question: http://stackoverflow.com/q/49866797
tags question: http://stackoverflow.com/q/49806160
tags question: http://stackoverflow.com/q/49837943
tags question: http://stackoverflow.com/q/49844960
tags question: http://stackoverflow.com/q/49821843
tags question: http://stackoverflow.com/q/49782397
tags question: http://stackoverflow.com/q/49776386
tags question: http://stackoverflow.com/q/49833339
tags question: http://stackoverflow.com/q/49881299
tags question: http://stackoverflow.com/q/49905818
tags question: http://stackoverflow.com/q/49812802
tags question: http://stackoverflow.com/q/49824398
tags question: http://stackoverflow.com/q/49762555
tags question: http://stackoverflow.com/q/49858037
tags question: http://stackoverflow.com/q/49894161
tags question: http://stackoverflow.com/q/49901691
tags question: http://stackoverflow.com/q/49848597
tags question: http://stackoverflow.com/q/49805747
tags question: http://stackoverflow.com/q/49894829

http://stackoverflow.com/q/49886530
tagged with: python
has comment: http://stackoverflow.com/comment/86795612
score: 0
tagged with: amazon-s3
answer count: 1
tagged with: pymongo
has comment: http://stackoverflow.com/comment/86883227
type: Question
has body: I am trying to query mongodb documents using Pymongo and trying to write them to s3. I want to save files to s3 in json array format. I can restore it back to mongo easily. Mongodb queries are getting build dynamically and I dont have option to save documents at some temporary location and then upload . Below snippet works but it consumes lot of memory. To copy 1.5GB data it consumes ~12GB of physical memory. mongo_query = {"$and": [{"ABC": school_year_id.upper()}, {"XYZ": clientid}] plans = mongo_conn[self.database][self.collection] plans_archivable_docs = plans.find(mongo_query) s3_key = school_year + '/' + clientid + '/' + self.database + self.collection + '.json' s3_client = mngarchs3.get_s3_client() response = s3_client.put_object(ACL='private', Bucket='xxxx-mongo-archives', Key=s3_key, Body=dumps(plans_archivable_docs) ) print (response) Is there any anther more memory efficient option ?
tagged with: mongodb
has comment: http://stackoverflow.com/comment/86885419
has title: mongo cursor s3 putObject
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52127320

http://stackoverflow.com/a/49846478
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/49822414
answers question: http://stackoverflow.com/q/49822414
type: Answer
upvote count: 4
has body: You can use the duplicated method on col1, which can detect whether an element has duplicates with keep=False parameter and returns a boolean Series which you can use to subset/filter/drop rows: df[df.col1.duplicated(keep=False)] # col1 col2 months #0 1 3 6 #1 1 4 6 #4 4 20 6 #5 4 11 7 #6 4 12 7
type: AcceptedAnswer

http://stackoverflow.com/comment/86629477
has text: If you really want to do this, the easiest way is probably to create an `entrypoint` script that reads `sys.argv[1]` and dispatches on that to `import` a different module (`main`, or `first`, or `second`, etc.) and call a method out of it. Then, `main` doesn't try to subprocess `first.py`, it instead subprocesses `entrypoint` with `first` as an extra argument.
comment on: http://stackoverflow.com/q/49806594
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49847143
has comment: http://stackoverflow.com/comment/86709272
has comment: http://stackoverflow.com/comment/86709330
has comment: http://stackoverflow.com/comment/86709320
has comment: http://stackoverflow.com/comment/86709307
has comment: http://stackoverflow.com/comment/86710874
favorite count: 0
type: Question
tagged with: numpy
tagged with: indexing
has comment: http://stackoverflow.com/comment/86709190
has comment: http://stackoverflow.com/comment/86709220
has answer: http://stackoverflow.com/a/49847221
has title: Convert Python numeric list to numpy array of float
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/86709253
has comment: http://stackoverflow.com/comment/86709186
has comment: http://stackoverflow.com/comment/86709350
has comment: http://stackoverflow.com/comment/86709378
tagged with: arrays
downvote count: 5
tagged with: python
has body: I have a list of numbers that need to be converted to floats in an 45 x 45 array. gauss_matrix = [list of 2025 float numbers] mat_template = np.zeros([45, 45]) for rows in np.arange(45): for columns in np.arange(45): mat_template[rows, columns] = float(gauss_matrix[np.arange(2025)]) Does this start at row 0, loop through columns 0-44. Then start at row 2, loop through columns 0-44 and so on? Resolved Code: (thanks for the help!) with open('gaussfilter.csv', 'r+') as gauss: # Let's me read and write gaussfilter.csv GaussFilterData = gauss.readlines() # Reads the lines of the csv file # print("GaussFilterData: \n", GaussFilterData) GaussList = [] # Empty list which will be used to append values to from the csv file # print("GaussList 1: \n", GaussMatrix) for lines in GaussFilterData: # Loops through each row of data in gaussfilter.csv # print("lines: \n", lines) for row in np.arange(45): # Looping through each row and splitting up the list by commas, while converting each value to a float and not a string GaussList.append(float(lines.split(',')[row])) # Appending each row to GaussList # print("\nGaussList 2: \n", GaussList) # Making the array of values from GaussList gauss = np.zeros([45, 45]) # Matrix of zeros, the zeros are placeholders for the values in GaussList # print("gauss: \n", gauss) Counter = -1 # Counter has to start at -1 so that it begins at 0 when referring to row 0 and column 0 for rows in np.arange(45): # Loop through rows 0 - 44 for columns in np.arange(45): # As we are looping through row 0, loop through all 45 columns Counter = Counter + 1 # Counter keeps track of the number of cells in the matrix (2025) gauss[rows][columns] = GaussList[Counter] print("gauss array: \n", gauss)
has comment: http://stackoverflow.com/comment/86709261
answer count: 2
has comment: http://stackoverflow.com/comment/86709296
upvote count: 3
has answer: http://stackoverflow.com/a/49847234
has comment: http://stackoverflow.com/comment/86709534
has comment: http://stackoverflow.com/comment/86709178
has comment: http://stackoverflow.com/comment/86709276

http://stackoverflow.com/a/49874184
has body: just split your list and check either for "word" or for integer, using set comprehension to get rid of duplicates: if 3 in {int(x) for x in output.stdout.decode('utf-8').split()}: a simpler way is also possible with the direct output of split: if "3" in output.stdout.decode('utf-8').split(): (less powerful if integers can start with 0: 03)
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49874090
accepted answer of: http://stackoverflow.com/q/49874090

jupyter-notebook
tags question: http://stackoverflow.com/q/49914880
tags question: http://stackoverflow.com/q/49873779
tags question: http://stackoverflow.com/q/49769611
tags question: http://stackoverflow.com/q/49859885
tags question: http://stackoverflow.com/q/49864367
tags question: http://stackoverflow.com/q/49795287
tags question: http://stackoverflow.com/q/49879205
tags question: http://stackoverflow.com/q/49842718
tags question: http://stackoverflow.com/q/49817409
tags question: http://stackoverflow.com/q/49848074
tags question: http://stackoverflow.com/q/49863561
tags question: http://stackoverflow.com/q/49895238
tags question: http://stackoverflow.com/q/49891052
tags question: http://stackoverflow.com/q/49813234
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/49784614
tags question: http://stackoverflow.com/q/49914882
tags question: http://stackoverflow.com/q/49904313
tags question: http://stackoverflow.com/q/49766627
type: Tag
tags question: http://stackoverflow.com/q/49805480
tags question: http://stackoverflow.com/q/49759170
tags question: http://stackoverflow.com/q/49823513
tags question: http://stackoverflow.com/q/49829466
tags question: http://stackoverflow.com/q/49790025
tags question: http://stackoverflow.com/q/49902478
tags question: http://stackoverflow.com/q/49781303
tags question: http://stackoverflow.com/q/49870879
tags question: http://stackoverflow.com/q/49854842
tags question: http://stackoverflow.com/q/49908158
tags question: http://stackoverflow.com/q/49843309
tags question: http://stackoverflow.com/q/49891038
tags question: http://stackoverflow.com/q/49792820
tags question: http://stackoverflow.com/q/49877747
tags question: http://stackoverflow.com/q/49863553
tags question: http://stackoverflow.com/q/49830559

http://stackoverflow.com/q/49835108
has comment: http://stackoverflow.com/comment/86685367
has answer: http://stackoverflow.com/a/49835252
score: -1
favorite count: 0
has answer: http://stackoverflow.com/a/49835199
answer count: 4
has comment: http://stackoverflow.com/comment/86685444
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/86685355
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49835235
has answer: http://stackoverflow.com/a/49835193
has body: I am trying to write code to find the length of a string, and to return "invalid entry" when an integer is entered. def length_of_string(mystring): if type(mystring) == int: return "invalid entry" else: mystring = input("enter the string ") return len(mystring) When I try to execute this function it doesn't give me an error, nor does it produce any solution.
has title: Not getting any results
downvote count: 3

http://stackoverflow.com/q/49896433
type: Question
duplicate of: http://stackoverflow.com/q/38390177
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49896779
answer count: 1
tagged with: django
tagged with: python
score: 0
has body: I am new to django.I want upload the file in django web page.When I'm executing the code it shows the following error. NoReverseMatch at /index/ Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Please help me to print the csv results on the table by without saving the csv_file on db and correct my code if there is any error Main urls.py urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^',include('myapp.urls',namespace='myapp')), ) if settings.DEBUG: urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) myapp.urls from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^index/', views.upload_csv,name='upload_csv'), ] views.py from django.shortcuts import render from django.conf import settings from django.http import HttpResponseRedirect from django.contrib import messages import csv from django.core.urlresolvers import reverse import logging def upload_csv(request): data = {} if "GET" == request.method: return render(request, "myapp/index.html", data) # if not GET, then proceed try: csv_file = request.FILES["csv_file"] if not csv_file.name.endswith('.csv'): c=messages.error(request,'File is not CSV type') return HttpResponseRedirect(reverse("myapp:index",{"c":c})) #if file is too large, return if csv_file.multiple_chunks(): messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),)) return HttpResponseRedirect(reverse("myapp:index")) file_data = csv_file.read().decode("utf-8") rows=[] lines = file_data.split("\n") for line in lines: fields = line.split(",") data_dict = {} data_dict["GSTIN/UIN"] = fields[0] data_dict["INV NO"] = fields[1] data_dict["INV-DATE"] = fields[2] data_dict["Taxable value"] = fields[3] try: form = EventsForm(data_dict) if form.is_valid(): form.save() else: logging.getLogger("error_logger").error(form.errors.as_…
linked to: http://stackoverflow.com/q/38390177
has title: How to solve NoReverseMatch error in django

http://stackoverflow.com/comment/86720606
comment on: http://stackoverflow.com/q/49836827
score: 0
type: Comment
type: QuestionComment
has text: I would also suggest MayaVI or Matplotlib. In my opinion, VTK is not as straight forward to use as the other two.

http://stackoverflow.com/a/49834920
has body: Try to cast the input value to integer before the if statement. use if int(roomChoice) == 1: print("You went to the bar, and lost $5, your total loot is : " + main.totalLoot) else: print(roomChoice)
type: Answer
answers question: http://stackoverflow.com/q/49834849
score: 0

http://stackoverflow.com/a/49836189
answers question: http://stackoverflow.com/q/49835692
has comment: http://stackoverflow.com/comment/86690436
has body: On cursory glance, it looks like the error is occurring here: cur.execute ("UPDATE articles SET title=%s, body=%s WHERE id=%s",(title, body, id)) Problem 1) id isn't defined up with title and body: title = request.form['title'] body = request.form['body'] Problem 2) If id is numeric, you need to format into your 'execute' string with %d. cur.execute ("UPDATE articles SET title=%s, body=%s WHERE id=%d",(title, body, id))
score: 0
has comment: http://stackoverflow.com/comment/86687922
type: Answer
has comment: http://stackoverflow.com/comment/86880900

http://stackoverflow.com/comment/86729268
has text: @Ev.Kounisyou are right! Copied from the wrong place! Thank you.
comment on: http://stackoverflow.com/q/49857185
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49903906
score: 1
downvote count: 0
has body: You can use the axis parameter for fft and ifft, as well as broadcasting: ss = np.ones((num_row, num_col), dtype=np.complex128) sig = np.random.standard_normal(num_col) * 1j * np.random.standard_normal(num_col) ss = ifft(fft(ss, axis=1) * sig, axis=1)
upvote count: 1
answers question: http://stackoverflow.com/q/49903741
type: Answer
has comment: http://stackoverflow.com/comment/86823954

http://stackoverflow.com/q/49867912
score: 0
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/86755820
linked to: http://stackoverflow.com/q/40029549
type: Question
has answer: http://stackoverflow.com/a/49906354
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has body: I've been working on a research project that is looking to obtain a list of reference articles from the Brazil Hemeroteca (The desired page reference: http://memoria.bn.br/DocReader/720887x/839, needs to be collected from two hidden elements on the following page: http://memoria.bn.br/DocReader/docreader.aspx?bib=720887x&amp;pasta=ano%20189&amp;pesq=Milho). I asked a question a few weeks back that was answered and I was able to get things running well in regards to that, but now I've hit a new snag and I'm not exactly sure how to get around it. The problem is that after the first form is filled in, the page redirects to a second page, which is a JavaScript/AJAX enabled page which I need to spool through all of the matches, which is done by means of clicking a button at the top of the page. The problem I'm encountering is that when clicking the next page button I'm dealing with elements on the page that are updating, which leads to Stale Elements. I've tried to implement a few pieces of code to detect when this "stale" effect occurs to indicate the page has changed, but this has not provided much luck. Here is the code I've implemented: import urllib from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select import time saveDir = "C:/tmp" print("Opening Page...") browser = webdriver.Chrome() url = "http://bndigital.bn.gov.br/hemeroteca-digital/" browser.get(url) print("Searching for elements") fLink = "" fails = 0 frame_ref = browser.find_elements_by_tag_name("iframe")[0] iframe = browser.switch_to.frame(frame_ref) journal = browser.find_element_by_id("PeriodicoCmb1_Input") search_journal = "Relatorios dos Presidentes dos Estados Brasileiros (BA)" search_timeRange = "1890 - 1899" search_text = "Milho" xpa…
has title: Scraping an updating JavaScript page in Python
has comment: http://stackoverflow.com/comment/86753424
has comment: http://stackoverflow.com/comment/86753286
has comment: http://stackoverflow.com/comment/86753897

http://stackoverflow.com/comment/86782582
type: Comment
comment on: http://stackoverflow.com/a/49882562
type: AnswerComment
has text: thanks but I only have a database which contains positve label for all sentences
score: 0

http://stackoverflow.com/a/50414656
answers question: http://stackoverflow.com/q/49894329
has comment: http://stackoverflow.com/comment/87845967
score: 2
has comment: http://stackoverflow.com/comment/87845738
upvote count: 2
has comment: http://stackoverflow.com/comment/87845826
downvote count: 0
has comment: http://stackoverflow.com/comment/87845583
has body: Using pandas.cut() could be a quick solution for you: import pandas as pd import numpy as np start_date = "2015-11-21" # As @ALollz mentioned, the month with the original end_date='2017-11-20' was missing. # since pd.date_range() only generates dates in the specified range (between start= and end=), # '2017-11-31'(using freq='M') exceeds the original end='2017-11-20' and thus is cut off. # the similar situation applies also to start_date (using freq="MS") when start_month might be cut off # easy fix is just to extend the end_date to a date in the next month or use # the end-date of its own month '2017-11-30', or replace end= to periods=25 end_date = "2017-12-20" # create a testing dataframe df = pd.DataFrame({ "date": pd.date_range(start_date, periods=710, freq='D'), "value": np.random.randn(710)}) # set up bins to include all dates to create expected date ranges bins = [ d.replace(day=20) for d in pd.date_range(start_date, end_date, freq="M") ] # group and summary using the ranges from the above bins df.groupby(pd.cut(df.date, bins)).sum() value date (2015-11-20, 2015-12-20] -5.222231 (2015-12-20, 2016-01-20] -4.957852 (2016-01-20, 2016-02-20] -0.019802 (2016-02-20, 2016-03-20] -0.304897 (2016-03-20, 2016-04-20] -7.605129 (2016-04-20, 2016-05-20] 7.317627 (2016-05-20, 2016-06-20] 10.916529 (2016-06-20, 2016-07-20] 1.834234 (2016-07-20, 2016-08-20] -3.324972 (2016-08-20, 2016-09-20] 7.243810 (2016-09-20, 2016-10-20] 2.745925 (2016-10-20, 2016-11-20] 8.929903 (2016-11-20, 2016-12-20] -2.450010 (2016-12-20, 2017-01-20] 3.137994 (2017-01-20, 2017-02-20] -0.796587 (2017-02-20, 2017-03-20] -4.368718 (2017-03-20, 2017-04-20] -9.896459 (2017-04-20, 2017-05-20] 2.350651 (2017-05-20, 2017-06-20] -2.667632 (2017-06-20, 2017-07-20] -2.319789 (2017-07-20, 2017-08-20] -9.577919 (2017-08-20, 2017-09-20] 2.962070 (2017-09-20, 2017-10-20] -2.901864 (2017-10-20, 2017-11-20] 2.873909 # export the result summary = df.groupby(pd.cut(df.date, bins)).value.sum().tolist() ..
type: Answer

http://stackoverflow.com/comment/86817385
comment on: http://stackoverflow.com/q/49878894
type: QuestionComment
type: Comment
has text: @shao.lo if it has done what I asked it to, then how can I display what it has done? the `print (imagetag)` isn't showing the complete contents of ` ` because of that error
score: 0

http://stackoverflow.com/q/49770609
duplicate of: http://stackoverflow.com/q/3044580
score: 0
has comment: http://stackoverflow.com/comment/86556127
has title: Simple asynchronous task with asyncio
linked to: http://stackoverflow.com/q/26270681
tagged with: python-asyncio
answer count: 0
duplicate of: http://stackoverflow.com/q/26270681
has body: I have a function that takes a lot of time to run, but actually has returns no program relevant value -- it simply does some IO / plotting to store current progress. I would like to asynchronously call it, and have found the newly core'd asyncio library. My main function then looks something like async def doStuff(input): plt.figure() plt.plot(input) plt.savefig('foobar.pdf') However, it's unclear to me how to exactly call that. All examples I've seen do a variant on loop = asyncio.get_event_loop() # Blocking call which returns when the hello_world() coroutine is done loop.run_until_complete(doStuff() but actually, I just need a single call (not a loop), and explicitely do not want to wait ever for it to finish. What's the most trivial implementation of that in the asyncio framework?
tagged with: asynchronous
type: Question
duplicate of: http://stackoverflow.com/q/2846653
duplicate of: http://stackoverflow.com/q/7168508
has comment: http://stackoverflow.com/comment/86556384
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/86532976
comment on: http://stackoverflow.com/q/49758960
type: Comment
type: QuestionComment
score: 0
has text: SQL Alchemy comes with decorators and context managers to automate transaction management: a transaction (optionally a nested one) is created at the start, and then it's rolled back if you exit with an exception or committed if you exit normally. Is that what you're looking for, or something different?

http://stackoverflow.com/q/49802645
downvote count: 0
has comment: http://stackoverflow.com/comment/86621149
tagged with: unicode
favorite count: 0
type: Question
has body: I'm trying to read the list of available wifi connections from python. I use the following code to do so: ps = subprocess.Popen(('sudo', 'iwlist', 'wlan0', 'scan'), stdout=subprocess.PIPE) output = subprocess.check_output(('grep', 'ESSID'), stdin=ps.stdout) ssids = filter(None, sorted(dict.fromkeys(re.findall('"([^"]*)"', output)))) This produces a list of available ssids. Great. But if I have an ssid with an apostrope in it, I get something like: Ryan\xe2\x80\x99s iPhone Cool..the only way I can get this to display correctly on my web app is if I run str.decode('string_escape') on each of the ssids. It then looks like: Ryan’s iPhone But then...when I try to write that value to wpa_supplicant.conf, I get: UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position... Ok...so I try to utf-8 encode it before it is submitted, and I get this error: UnicodeDecodeError: 'ascii' codec can't decode byte 0x32 in position... I've tried utf-8 encoding the ssids initially (instead of using decode('string_escape'), but the character still just shows up and is passed as \xe2\x80\x99. I don't know what I can do to simply display and pass this like any other normal character.
has title: Python woes with ssids, utf-8, and unicode
tagged with: python
tagged with: utf-8
has comment: http://stackoverflow.com/comment/86620306
score: 2
has comment: http://stackoverflow.com/comment/86620574
tagged with: encoding
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: wifi

http://stackoverflow.com/q/49768866
tagged with: pandas
tagged with: matplotlib
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86557184
linked to: http://stackoverflow.com/q/45704366
has answer: http://stackoverflow.com/a/49774065
upvote count: 3
has body: I have a dataFrame with datetimeIndex and two columns with int values. I would like to plot on the same graph Col1 as a bar plot, and Col2 as a line plot. Important feature is to have correctly labeled x-axis as datetime, also when zooming in-out. I think solutions with DateFormatter would not work, since I want a dynamic xtick labeling. import matplotlib.pyplot as plt import pandas as pd import datetime as dt import numpy as np startDate = dt.datetime(2018,1,1,0,0) nrHours = 144 datetimeIndex = [startDate + dt.timedelta(hours=x) for x in range(0,nrHours)] dF = pd.DataFrame(index=datetimeIndex) dF['Col1'] = np.random.randint(1,3,nrHours) dF['Col2'] = np.random.randint(3,6,nrHours) axes = dF'Col1'.plot(kind='bar') dF'Col2'.plot(ax=axes) What seemed to be a simple task turns out being very challenging. Actually, after extensive search on the net, I still haven't found any clean solutions. I have tried to use both pandas plot and matplotlib. The main issue arises from the bar plot that seems to have difficulties handling datetime index (prefers integers, in some cases it plot dates but in Epoch 1970-1-1 style which is equivalent to 0).
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86562543
tagged with: bar-chart
answer count: 1
downvote count: 0
has title: How to combine bar and line plots with x-axis as datetime in matplotlib
linked to: http://stackoverflow.com/q/46503073
favorite count: 0
type: Question
score: 3

http://stackoverflow.com/q/49901661
has comment: http://stackoverflow.com/comment/86821119
has comment: http://stackoverflow.com/comment/86819068
accepted answer: http://stackoverflow.com/a/49977878
tagged with: python
has body: I trained my model in Keras and I converted it to tensorflow model for inference using C++ (I didn't quantize). My inference code in C++ is straight forward. I read image directly from file. I perform Decode png, resize and normalize operations using the following functions. static Status ReadFile(Env *oEnv, const string &amp;sFileName, Tensor *output) { uint64 nFileSize = 0; TF_RETURN_IF_ERROR(oEnv-&gt;GetFileSize(sFileName, &amp;nFileSize)); string oFile; oFile.resize(nFileSize); std::unique_ptr&lt;RandomAccessFile&gt; oFileAccess; TF_RETURN_IF_ERROR(oEnv-&gt;NewRandomAccessFile(sFileName, &amp;oFileAccess)); StringPiece oData; TF_RETURN_IF_ERROR(oFileAccess-&gt;Read(0, nFileSize, &amp;oData, &amp;(oFile)[0])); output-&gt;scalar&lt;string&gt;()() = oData.ToString(); return Status::OK(); } //Reads a PNG image and converts it to a tensor of specified size. Status ReadImageFromFile(const string &amp;sFileName, const int nWidth, const int nHeight, const float fMean, const float fScale, std::vector&lt;Tensor&gt; *oTensor) { Tensor oTInput(DT_STRING, TensorShape()); TF_RETURN_IF_ERROR(ReadFile(Env::Default(), sFileName, &amp;oTInput)); auto oTRoot = Scope::NewRootScope(); auto oInput = ops::Placeholder(oTRoot.WithOpName("input"), DT_STRING); std::vector&lt;std::pair&lt;string, Tensor&gt;&gt; oInputs = { {"input",oTInput} }; Output oOpImgRead = ops::DecodePng(oTRoot.WithOpName("png_file"), oInput, ops::DecodePng::Channels(3)); auto oTFloatConv = ops::Cast(oTRoot.WithOpName("float_conv"), oOpImgRead, DT_FLOAT); auto oDimExpand = ops::ExpandDims(oTRoot, oTFloatConv, 0); auto oResize = ops::ResizeBilinear(oTRoot, oDimExpand, ops::Const(oTRoot.WithOpName("size"), { nHeight, nWidth })); auto oMeanSub = ops::Sub(oTRoot, oResize, { fMean }); auto oScale = ops::Div(oTRoot.WithOpName("output"), oMeanSub, { fScale }); GraphDef oGraph; TF_RETURN_IF_ERROR(oTRoot.ToGraphDef(&amp;oGraph)); Session *oSess; NewSession(SessionOptions(), &amp;oSess); TF_RETURN_IF_ERROR(oSess-&gt;Create(oG…
tagged with: keras
has comment: http://stackoverflow.com/comment/86984022
has comment: http://stackoverflow.com/comment/86915768
has answer: http://stackoverflow.com/a/49977878
has comment: http://stackoverflow.com/comment/86904780
has comment: http://stackoverflow.com/comment/86911592
tagged with: c++
type: AnsweredQuestion
score: 3
has title: Tensorflow C++ inference result is slightly different from Keras inference
upvote count: 3
downvote count: 0
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/comment/86532207
has text: My guess is that python has become smart enough to optimize element wise operations as above well enough. Try a matrix multiplication type of operation, and I'd bet the farm you'd see a big difference.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49758589

http://stackoverflow.com/a/49777721
score: 0
accepted answer of: http://stackoverflow.com/q/49777595
type: AcceptedAnswer
has body: Python can print number, string, ... pretty much anything as long as types are not mixed up. In your case, age is a number and the rest of the line you want to print is a string. You need to convert your number to a string by adding str(age) instead of just age.
answers question: http://stackoverflow.com/q/49777595
type: Answer

http://stackoverflow.com/comment/86580620
type: QuestionComment
score: 0
has text: i want to paste it in google spreadsheet, but thats not the main problem i will figure it how to do it later on^^
type: Comment
comment on: http://stackoverflow.com/q/49782514

http://stackoverflow.com/a/49802417
answers question: http://stackoverflow.com/q/49802416
score: 2
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49802416
has body: As per issue logged in pyautocad repository, https://github.com/reclosedev/pyautocad/issues/6 comtypes has issue related to accessing array. Hence to read block references we have to use win32com as follows: import win32com.client acad = win32com.client.Dispatch("AutoCAD.Application") # iterate through all objects (entities) in the currently opened drawing # and if its a BlockReference, display its attributes. for entity in acad.ActiveDocument.ModelSpace: name = entity.EntityName if name == 'AcDbBlockReference': HasAttributes = entity.HasAttributes if HasAttributes: for attrib in entity.GetAttributes(): print(" {}: {}".format(attrib.TagString, attrib.TextString)) for more details you can see https://gist.github.com/thengineer/7157510.
type: Answer

http://stackoverflow.com/q/49822692
score: 0
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/49822731
has answer: http://stackoverflow.com/a/49822731
answer count: 1
type: Question
tagged with: visual-studio-code
has body: My lecturer uploaded a youtube video explaining how to activate node and anaconda. I've installed node, anaconda (and vscode through the installation of the anaconda). In the video, he says that we can check if the anaconda was installed properly by typing in the cmd jupiter --version and then the version should be presented on the screen. I get the message: 'jupiter' is not recognized as an internal or external command, operable program or batch file. How can I fix this so that I could see the version? Thanks a lot.
tagged with: python
has comment: http://stackoverflow.com/comment/86662141
has comment: http://stackoverflow.com/comment/86660955
has title: Installing vscode, node, anaconda
type: AnsweredQuestion

http://stackoverflow.com/q/49763252
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86542196
upvote count: 2
has comment: http://stackoverflow.com/comment/86542243
downvote count: 0
accepted answer: http://stackoverflow.com/a/49763332
tagged with: python
has answer: http://stackoverflow.com/a/49763329
has comment: http://stackoverflow.com/comment/86542290
possible better answer: http://stackoverflow.com/a/49763361
type: AnsweredQuestion
score: 2
has body: I have a saved python script. I run this python script from the command prompt in Windows 10. This is as simple as navigating to the directory where the script is located and then typing: python myscript.py and the script will run fine. However, sometimes, I want to run this script such that a variable within that script is set to one value and sometimes to another. This variable tells the script which port to operate an API connection through (if this is relevant). At the moment, I go into the script each time and change the variable to the one that I want and then run the script after that. Is there a way to set the variable at the time of running the script from the command prompt in Windows 10? Or are there potentially any other efficient solutions to achieve the same flexibility at the time of running? Thanks
answer count: 3
has title: Is it possible to run a python script from the windows command prompt and pass an argument for that script at the same time?
has answer: http://stackoverflow.com/a/49763361
has comment: http://stackoverflow.com/comment/86542393
has comment: http://stackoverflow.com/comment/86542309
tagged with: windows-10
has answer: http://stackoverflow.com/a/49763332
favorite count: 0
type: Question
tagged with: command-line

http://stackoverflow.com/a/49996659
has body: Nested dict {0: [{1: 2}, {2: 3}, {3: 6}, {7: 8}], 1: [{0: 2}, {4: 7}, {2: 5}], 2: [{0: 3}, {1: 5}, {5: 4}, {11: 5}], 3: [{0: 6}, {6: 2}, {11: 4}], 4: [{1: 7}], 5: [{2: 4}, {8: 3}], 6: [{3: 2}, {9: 3}], 7: [{0: 8}], 8: [{5: 3}], 9: [{6: 3}, {10: 6}], 10: [{9: 6}], 11: [{2: 5}, {3: 4}]} unwrap results = [] for v,list_dicts in data_dict.items(): for d in list_dicts: results.append([v,list(d.keys())[0],list(d.values())[0]]) results [out] [[0, 1, 2], [0, 2, 3], [0, 3, 6], [0, 7, 8], [1, 0, 2], [1, 4, 7], [1, 2, 5], [2, 0, 3], [2, 1, 5], [2, 5, 4], [2, 11, 5], [3, 0, 6], [3, 6, 2], [3, 11, 4], [4, 1, 7], [5, 2, 4], [5, 8, 3], [6, 3, 2], [6, 9, 3], [7, 0, 8], [8, 5, 3], [9, 6, 3], [9, 10, 6], [10, 9, 6], [11, 2, 5], [11, 3, 4]]
answers question: http://stackoverflow.com/q/49885953
type: Answer
score: 0

http://stackoverflow.com/q/49814731
score: 2
has comment: http://stackoverflow.com/comment/86645621
answer count: 0
upvote count: 3
has body: when i'm dumping the data to pickle file I am getting this error ."TypeError: write() argument must be str, not bytes" with open('vocabulary-embedding.pickle', 'wb') as f: pickle.dump((embedding, idx2word, word2idx),f,-1) Input --> embedding : [[0.06625115 0.01928704 -0.02624818 0.00121181 0.05762575 -0.03544753]...] . idx2word : [on,the,for....] word2idx :[100,12,13,15...] Why I am getting this error ? How do i solve this?
has comment: http://stackoverflow.com/comment/86694203
has comment: http://stackoverflow.com/comment/86644726
has title: TypeError: write() argument must be str, not bytes python
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86645858
has comment: http://stackoverflow.com/comment/86645703
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86645746
has comment: http://stackoverflow.com/comment/86645691
has comment: http://stackoverflow.com/comment/86645953
has comment: http://stackoverflow.com/comment/86681619
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/86644430
has comment: http://stackoverflow.com/comment/86644763
has comment: http://stackoverflow.com/comment/86645386

http://stackoverflow.com/q/49786200
has answer: http://stackoverflow.com/a/49797010
has title: API Calling another API using Falcon framework
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: api
tagged with: falconframework
type: UnansweredQuestion
answer count: 1
has body: I have two apis written using Falcon. First API returns some JSON response. Second API uses First API to get its response. When I independently run First API, I get response but when I use second API, I get a read timeout exception when this second API uses First API call. Any idea ? localhost:port/firstapi/{123} - Works fine independently. when loaclhost:port/secondapi uses localhost:port/firstapi/{123}. I get read time out at localhost:port/firstapi/{123} PS : The two routes are registered in firstapi.py FirstAPIResource class.
downvote count: 0
upvote count: 1
score: 1
tagged with: python

http://stackoverflow.com/q/49898899
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49900646
accepted answer: http://stackoverflow.com/a/49900646
has title: How do I convert 3 Lists in a combined array of 3 members in Python?
has body: I'm a noob in Python 3, I'm coming from Java and javascript. How can I go from a = ['a', 'b', 'c'] b = [1, 2, 3] c = ['red', 'green', 'blue'] to x = [ ['a', 1, 'red'], ['b', 2, 'green'], ['c', 3, 'blue'] ] in an easy way, without using some loop (while/for/map) ? Thanks
tagged with: python
has answer: http://stackoverflow.com/a/49900266
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49899014
tagged with: list
has answer: http://stackoverflow.com/a/49899014
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/49900540

http://stackoverflow.com/comment/86870291
type: AnswerComment
has text: end of my data within the csv file.There is only space after the point,which I want to remove: CSV File: desteklemelidir. CRLR Your code adds in front of the text [' and at the end ']
comment on: http://stackoverflow.com/a/49924711
type: Comment
score: 0

http://stackoverflow.com/q/49787869
score: 1
has comment: http://stackoverflow.com/comment/86591357
has comment: http://stackoverflow.com/comment/86591712
tagged with: python
linked to: http://stackoverflow.com/q/15171695
has answer: http://stackoverflow.com/a/49788272
has comment: http://stackoverflow.com/comment/86591373
type: UnansweredQuestion
answer count: 1
downvote count: 0
has body: While analyzing id() built-in behavior with numbers &amp; string I got confusion. x = 100 y = x # x and y both points to same object that is 100 id(x) 162569156 id(y) 162569156 Now I tried to change the object where x is pointing as x = 200 # since x points to different objects &amp; garbage collector increments reference counts as its no longer points to old objects id(y) 162569156 id(x) # its different 162569932 Now as of my understanding python garbage collector which is reference count garbage collector, the moment x=200 or number of references changes, it clean it up. Here is my doubt, from above point can I assume that whenever I will do x = 100 again i.e tried to point to old object, id() will give exactly same memory location always as previuosly ? x = 100 #making x to points to same old object id(x) 162569156 #getting same old location id(y) 162569156 If above is true then does that means that for each number(millions) one references will be there and id() gives same location when points to old object in future ? I got this doubt as in other language like in C once pointer lost its address(heap), its not guaranteed that next time it will get same address when you will do malloc.
upvote count: 1
has comment: http://stackoverflow.com/comment/86591996
favorite count: 0
type: Question
has title: how garbage collector keep track of its references in python?
has comment: http://stackoverflow.com/comment/86590820
has comment: http://stackoverflow.com/comment/86607818
has comment: http://stackoverflow.com/comment/86590874

http://stackoverflow.com/q/49871020
accepted answer: http://stackoverflow.com/a/49871203
downvote count: 0
has answer: http://stackoverflow.com/a/49871203
tagged with: file-upload
favorite count: 0
score: 28
type: Question
has title: Extract file from file storage object in flask
linked to: http://stackoverflow.com/q/39437909
has body: I am learning how to work with file uploads in flask. Earlier from here, i worked with pdf file uploads and read the contents of it. This happens inside client.py file. Now i would like to pass my file from client to server that is running locally. When i use request.file, it will get it as FileStorage Object. So, without saving or providing file path, i want to upload file from client and pass it to the server to do further process. class mainSessRunning(): def proces(input): ... ... return result run = mainSessRunning() @app.route('/input', methods=['POST']) def input(): input_file = request.files['file'] ...(extract file from filestorage object "input_file")... result = run.process(file) ## process is user defined function return (result) here i want to send the incoming file through process() function to server running locally. How do i do this? I came across same question but couldn't able to find anything
linked to: http://stackoverflow.com/q/49773141
upvote count: 28
tagged with: python
tagged with: object-storage
tagged with: flask
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/60824889
tagged with: python-2.7
answer count: 2
possible better answer: http://stackoverflow.com/a/63848704
has answer: http://stackoverflow.com/a/63848704

http://stackoverflow.com/comment/86595199
type: QuestionComment
has text: Ok, just did that.
comment on: http://stackoverflow.com/q/49769952
score: 0
type: Comment

http://stackoverflow.com/comment/86866265
type: AnswerComment
has text: @chrisz I know, but you already gave that answer as a comment to the question. I’m not sure why you didn’t give it as an answer, but there is no point giving duplicate answers without any extra explanation.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49907046

http://stackoverflow.com/q/49792619
has answer: http://stackoverflow.com/a/49793085
tagged with: flask
favorite count: 0
type: Question
has body: I am trying to read contents of files like .txt,.docx,.pdf and so on with textract. when i use the below code, it throws error: @app.route('/upload', methods=['POST']) def upload(): request_file = request.files['file'] text = textract.process(request_file.stream) return (text) when i uploaded a docx file, File "/usr/lib/python2.7/genericpath.py", line 26, in exists os.stat(path) TypeError: coercing to Unicode: need string or buffer, instance found 10.0.2.2 -- [12/Apr/2018 09:04:58] "POST /upload HTTP/1.1" 500 - How can i send these files with different extension into textract with flask?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/62044497
tagged with: python-2.7
has title: how to give input file to read using textract inside flask
answer count: 2
downvote count: 0
score: 1
upvote count: 1
tagged with: upload

http://stackoverflow.com/comment/86621558
type: QuestionComment
type: Comment
has text: In your code "if not pages", you haven't defined pages.
score: 0
comment on: http://stackoverflow.com/q/49803308

http://stackoverflow.com/a/49834833
type: AcceptedAnswer
downvote count: 0
has body: Why won't you do something like this? df.select([ myFunc(col_name).alias(col_name) if col_name in handle_null_cols else col_name for col_name in df.columns ]) reduce + withColumn is more cryptic but viable solution: from functools import reduce reduce( lambda df, col_name: df.withColumn(col_name, myFunc(col_name)), handle_null_cols, df) But it sounds a bit like you actually want na functions: df.na.fill(0, subset=handle_null_cols)
answers question: http://stackoverflow.com/q/49834798
score: 2
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49834798

http://stackoverflow.com/q/49902533
has answer: http://stackoverflow.com/a/49907471
has comment: http://stackoverflow.com/comment/86826622
accepted answer: http://stackoverflow.com/a/49907471
has comment: http://stackoverflow.com/comment/86822346
has comment: http://stackoverflow.com/comment/86826647
has comment: http://stackoverflow.com/comment/86826769
has comment: http://stackoverflow.com/comment/86826250
answer count: 1
has comment: http://stackoverflow.com/comment/86826467
has title: Launch separate process in Qt
type: Question
has comment: http://stackoverflow.com/comment/86825936
tagged with: qt
has comment: http://stackoverflow.com/comment/86826269
has comment: http://stackoverflow.com/comment/86820616
has comment: http://stackoverflow.com/comment/86822208
has comment: http://stackoverflow.com/comment/86825554
has comment: http://stackoverflow.com/comment/86824220
tagged with: python
has comment: http://stackoverflow.com/comment/86823201
has body: I'm attempting to run an python file from a Qt application however I have two problems. One it does not appear to launch the python tool. And secondly when I try doing a simple test using just notepad as an example, i notice that Notepad closes when i close my application. I'm not sure why the python tool is not launching and why the process is not truly independent from the Qt application. else if(QFileInfo(path).isFile() &amp;&amp; path.endsWith(".py", Qt::CaseInsensitive)) { QProcess::startDetached("C:/python27/python.exe", QStringList() &lt;&lt; "C:/Users/john/testing.py"); QProcess *proc = new QProcess(); proc-&gt;startDetached("notepad.exe"); } Update #1: Second attempt still failing.... I've research a bit more and even attempted the code below and it's now giving me the error: ImportError: No module named site Which is confusing to me because I'm setting the env paths. At the end of the day all im trying to do is run a shell command like the following, but from Qt. "C:/python27/python.exe" "C:/Users/john/testing.py" Latest code: QString program( "C:\\Python27\\python.exe" ); QStringList args = QStringList() &lt;&lt; "C:\\Users\\jmartini\\Desktop\\Trash\\testing.py"; QProcess process; QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert("PYTHONHOME", "C:\\Python27"); env.insert("PYTHONPATH", "C:\\Python27\\Lib"); process.setProcessEnvironment(env); process.execute(program, args);
has comment: http://stackoverflow.com/comment/86826351
tagged with: c++
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/87033019
type: Comment
has text: Yeah - I tried the windows encoding early on - no dice.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49953725

http://stackoverflow.com/comment/86744021
type: QuestionComment
has text: Everything is in 0s and 1s, but that doesn't mean it's useful to display everything as 0s and 1s.
score: 0
comment on: http://stackoverflow.com/q/49864293
type: Comment

http://stackoverflow.com/q/49878460
has comment: http://stackoverflow.com/comment/86826974
upvote count: 2
has answer: http://stackoverflow.com/a/49878510
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/49878593
has title: Multiplication of numbers in a list (Python)
has body: Is there any function in Python which could multiply numbers in a list with each other? input -&gt; A = [1,2,3,4] output -&gt; B = [1*1, 1*2, 1*3, 1*4, 2*2, 2*3, 2*4, 3*3, 3*4, 4*4] Or can someone help me with creating my own function? I've got over 8000 records and I wouldn't like to do it manually. So far the only thing I came up with is: for i in list: list[i] * list[i+1] But I know that it wouldn't work and I got no idea how to process this data.
type: AnsweredQuestion
tagged with: list
answer count: 2
downvote count: 4
accepted answer: http://stackoverflow.com/a/49878593
tagged with: multiplication
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49878510

python-itertools
tags question: http://stackoverflow.com/q/49873926
tags question: http://stackoverflow.com/q/49764959
tags question: http://stackoverflow.com/q/49880067
tags question: http://stackoverflow.com/q/49795270
tag name: python-itertools
tags question: http://stackoverflow.com/q/49890744
type: Tag
tags question: http://stackoverflow.com/q/49856426

http://stackoverflow.com/comment/86600018
type: Comment
comment on: http://stackoverflow.com/a/49781417
has text: Ah I just made the same change on the code. Yea that's what I was going for :) Cheers for the help. Will accept answer. Have a great day!
type: AnswerComment
score: 0

http://stackoverflow.com/q/49758199
linked to: http://stackoverflow.com/q/49879750
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: machine-learning
has title: How to use MongoDB with Sequence class or generator from Keras?
tagged with: keras
favorite count: 0
type: Question
has body: I'm going to store about 500K images in MongoDB and use this dataset to train a neural network with Keras. I've chosen database instead of separate images on disk to improve the data loading speed. Loading separate images for training has took about 1.5 hours - too much. Total data volume is about 1 Tb, it definitely does not fit in RAM, therefore the way to go is using method fit_generator of the model class or use keras.utils.Sequence. I'd like to stick to the Sequence. As the docs say, The use of keras.utils.Sequence guarantees the ordering and guarantees the single use of every input per epoch when using use_multiprocessing=True. Subclassing of the Sequence (as well as writing a generator), wrapping database connection, requires implementing __len__ and __get_item__. There are no problems with __len__ but __get_item__ confuses me, because it is me, the author, who is responsible for guarantee of ordering and single use. The main confusion is in object numbering in the MongoDB. The method __get_item__ of the Sequence subclass must return complete batch, and it must return the same batch repeatedly given the same input index. The database assigns unique identifiers (_id or ObjectID in pymongo) to the documents in the collection, and I would like to use them for collecting images in batches, but cannot figure out, how to do it. The arithmetics (max_object_id - min_object_id) / n_per_batch is impossible since the method of ObjectID creation makes no sense in subtracting them. I would like to get advices on what is the best method to split _ids into non-overlapping intervals and enumerate these intervals. I've got an old solution of similar problem for LMDB, borrowed from somewhere on Github, that creates additional pickle file, storing array of keys. I don't like it for that.
tagged with: python
accepted answer: http://stackoverflow.com/a/50407100
score: 4
has answer: http://stackoverflow.com/a/50407100
upvote count: 4
type: AnsweredQuestion
tagged with: mongodb

http://stackoverflow.com/q/49788888
has answer: http://stackoverflow.com/a/49789727
favorite count: 0
type: Question
tagged with: discord.py
has title: python discord bot event not working
has body: My distance calculator event is not working. It should ( if working ) calculate the distance between 2 places and give a message on how long the player should wait untill he go's there ( pokemon go related ) Not given me errors it just does nothing. i tryed different things but none seem to work. Anyone can help me out ? Would be great ! from discord.ext import commands import discord import gpxpy.geo import math import asyncio client = discord.Client(command_prefix='kaikai*') @client.async_event async def on_ready(): print("Logged in as:") print(client.user.name) print("ID:") print(client.user.id) print("Ready to use!") @client.async_event async def on_message(message) : if message.author == client.user: return elif message.content.startswith("kaikai*test") : await client.send_message(message.channel, "BOT READY!") @client.async_event class Distance: """Calculate the distance between two coordinates.""" def __init__(self, client): self.client = client @commands.command(pass_context=True) async def distance(self, ctx, *, message): """Calculate the distance between two coordinates and also provide you with a cooldown time.""" # Your code will go here def error_embed_1(self): embed=discord.Embed( title="Error:", description="Not enough data given. Did you give 4 different coordinates, seperated by spaces?", color=0x207cee) return embed def error_embed_2(self): embed=discord.Embed( title="Error:", description="Your message is invalid. Please use this format\n``!distance &lt;num1&gt; &lt;num2&gt; &lt;num3&gt; &lt;num4&gt;``\nWhich would look like this: ``!distance 51.301597 -0.598019 51.270664 -0.594132``", color=0x207cee) return embed def calc_embed(msg, msg2): embed=discord.Embed( title="", description=" ", color=0x207cee) embed.add_field( name="**Calculated Distance:**", value="{} Kilometers".format(msg), inline=False) embed.add_field( name="**Cooldown Timer:**", value="{} ".format(msg2), inline=False) return embed def calculate(lon1, lat1, lon2, lat2): dist = gpxpy.…
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49789727

http://stackoverflow.com/comment/86817070
score: 1
has text: Ok I probably misunderstood what you want to achieve. I hope the above will help. It may be worth editing the question to clarify. Good luck :-)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49900723

http://stackoverflow.com/a/49861503
type: Answer
score: 0
has body: A very rudimentary example of comparing dates in Python 3: set_a_start = datetime.datetime(2017, 1, 1) set_a_end = datetime.datetime(2017, 12, 31) set_b_start = datetime.datetime(2017, 4, 1) set_b_end = datetime.datetime(2017, 4, 30) if(set_a_start &lt;= set_b_start and set_a_end &gt;= set_b_end): print("Set B is within Set A") Update: added "&lt;=" for cases where both sets share the same start date (">=" for end dates)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86797141
answers question: http://stackoverflow.com/q/49860821
has comment: http://stackoverflow.com/comment/86852569
accepted answer of: http://stackoverflow.com/q/49860821
has comment: http://stackoverflow.com/comment/86824560

http://stackoverflow.com/comment/86794729
has text: If `a = [1, 2, 3, 4, 5, 6, 7, 8]` then `a[1:] `will return `a = [2, 3, 4, 5, 6, 7, 8]` Hope that helped, and make sure to mark this answer as accepted ;)
comment on: http://stackoverflow.com/a/49889306
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49826385
has body: I'm having some problem with this code.I have a Http request where I need to request some information from an API.I'm having troubles with the urllib request, I don't think I'm using the right library because the code I got it uses urllib2 put since python 3 is different I don't know which one to use. import urllib.request import json import os from pprint import pprint REST_URL = "http://data.bioontology.org" API_KEY = "MYAPIKEY" def get_json(url): opener = urllib.request.urlopen(url) opener.addheaders = [('Authorization', 'apikey token=' + API_KEY)] return json.loads(opener.open(url).read()) print(url) # Get list of search terms path = os.path.join(os.path.dirname("__file__"), 'classes_search_terms.txt') terms_file = open(path, "r") terms = [] for line in terms_file: terms.append(line) # Do a search for every term search_results = [] for term in terms: search_results.append(get_json(REST_URL + "/search?q=" + term)["collection"]) # Print the results for result in search_results: pprint(result)
has title: urllib.request HTTPError: Unauthorized
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86668495
tagged with: urllib
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86668543
tagged with: python
score: 0

http://stackoverflow.com/q/49784763
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49784903
has title: Django view not saving to model
answer count: 1
tagged with: django
tagged with: python
favorite count: 0
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49784903
downvote count: 0
has body: I have a view I am calling when a user clicks a button on the site, it pulls JSON data(from the Coinbase API) and converts it to a string and should save the string pulled to the current user's account. Whenever they click the button it will pull the string, but nothing is saved to the account, which is the issue. views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from ico_login.models import UserAddress from coinbase.wallet.client import Client @login_required() def generate_address_btc(request, *args, **kwargs): client = Client('api', 'key') r = client.get_addresses('account_id') address = r['data'][0]['address'] request.user.address = str(address) request.user.save() return HttpResponse(address) models.py from django.db import models from django.contrib.auth.models import User class UserAddress(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=300, default=' ') urls.py from django.contrib import admin from django.urls import path, include from ico_details import views urlpatterns = [ path('create_address/', views.generate_address_btc, name='generate') ]

http://stackoverflow.com/comment/86733890
comment on: http://stackoverflow.com/q/49859287
score: 3
has text: It's generally not true. Imagine a situation in which a critical section consist of non-atomic operation (i.e. several operations). Of course GIL does not allow to run same bytecode by 2 threads at once, but context may be switched between two threads accessing the same critical section.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49783565
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49781303
has body: From the Azure Notebooks docs: The simplest way to install packages is to do it from within a Jupyter Python notebook. Inside of the notebook your path will be setup to have both pip and conda on it pointing to the proper version of Python. So inside of a notebook you can simply do: !pip install &lt;pkg name&gt; or !conda install &lt;pkg name&gt; -y So just first execute a cell that contains: !pip install tweepy and you should be good to go.
score: 1

http://stackoverflow.com/comment/86775237
comment on: http://stackoverflow.com/a/49879759
type: AnswerComment
score: 0
type: Comment
has text: this won't work, a lot of those symbols need escaping.

http://stackoverflow.com/q/49913533
score: 0
has title: Psychopy script freezes with window and dialogue guis
answer count: 1
type: Question
tagged with: psych
has body: I want an experiment that displays a bunch of random dots, then asks the user to input the correct number of dots they saw. I want the experiment to loop. I can get this to work for 1 iteration, but something is wrong with the looping because the window and the dialogue are colliding, or the window isn't properly closing. When running this script Psychopy currently, the gui freezes. I've tried both python3 and python2 with my code. import random import psychopy.visual import psychopy.event import psychopy.core from psychopy import gui import time while True: win = psychopy.visual.Window( size=[500, 500], units="pix", fullscr=False ) myDlg = gui.Dlg(title="Response") n_dots = random.randint(5, 200) dot_xys = [] for dot in range(n_dots): dot_x = random.uniform(-250, 250) dot_y = random.uniform(-250, 250) dot_xys.append([dot_x, dot_y]) dot_stim = psychopy.visual.ElementArrayStim( win=win, units="pix", nElements=n_dots, elementTex=None, elementMask="circle", xys=dot_xys, sizes=10, contrs=random.random(), ) dot_stim.draw() win.flip() psychopy.event.clearEvents() time.sleep(4) win.close() myDlg.addField('How many dots did you see?') number = myDlg.show() if myDlg.OK: print(number) myDlg.close() psychopy.core.quit() I'm using the latest version of Psychopy. Please let me know if you have any suggestions. Thanks!
tagged with: python
tagged with: psychopy
accepted answer: http://stackoverflow.com/a/49915671
has answer: http://stackoverflow.com/a/49915671
type: AnsweredQuestion

http://stackoverflow.com/comment/86754999
type: Comment
comment on: http://stackoverflow.com/q/49869767
score: 0
has text: @ekhumoro I already did it :D
type: QuestionComment

http://stackoverflow.com/comment/86820400
comment on: http://stackoverflow.com/a/49899553
score: 0
type: Comment
has text: But now I have found that the correct rate of the predictions down by this regression is quite low, so I think there may be some mistakes with the algorithm :-(
type: AnswerComment

http://stackoverflow.com/comment/86819416
type: AnswerComment
comment on: http://stackoverflow.com/a/49882758
has text: I'll take a look. Thank you.
score: 0
type: Comment

http://stackoverflow.com/comment/86829598
type: Comment
type: QuestionComment
has text: Sorry, I just added some more information in my problem
score: 0
comment on: http://stackoverflow.com/q/49906129

http://stackoverflow.com/a/49819962
type: Answer
accepted answer of: http://stackoverflow.com/q/49819706
has body: Looks like you need. clients["age"].dt.days
downvote count: 0
answers question: http://stackoverflow.com/q/49819706
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/49845010
has body: For loop solution append rows to list and use DataFrame constructor: L = [] for i in train: new_row = [ i, train[i].mean(), np.var(train[i]), np.nanstd(train[i]) ] L.append(new_row) col_stats= ['Attribute', 'Mean', 'Var', 'Std'] stats = pd.DataFrame(L, columns=col_stats) Sample: train = pd.DataFrame({'B':[4,5,4,5,5,4], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0]}) L = [] for i in train: new_row = [ i, train[i].mean(), np.var(train[i]), np.nanstd(train[i]) ] L.append(new_row) col_stats= ['Attribute', 'Mean', 'Var', 'Std'] stats = pd.DataFrame(L, columns=col_stats) print (stats) Attribute Mean Var Std 0 B 4.500000 0.250000 0.500000 1 C 5.500000 6.916667 2.629956 2 D 2.833333 6.138889 2.477678 f1 = lambda x: x.var(ddof=0) f2 = lambda x: x.std(ddof=0) stats = train.agg(['mean',f1, f2]).T.reset_index() stats.columns = ['Attribute', 'Mean', 'Var', 'Std'] print (stats) Attribute Mean Var Std 0 B 4.500000 0.250000 0.500000 1 C 5.500000 6.916667 2.629956 2 D 2.833333 6.138889 2.477678
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49844960
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49844960

http://stackoverflow.com/comment/131318506
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/65123238
type: Comment
has text: If in `EarlyStopping` you specified a `min_delta` parameter, `np.argmax` might not find the returned epoch for the best weights. Is it safer to use `EarlyStopping.stopped_epoch-patience+1`

http://stackoverflow.com/a/49816378
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49774090
has body: Because the issue is open on github as Paul said I had to make a custom solution. I parsed the input using re and changed it from: Tue May 01 2018 13:23:00 GMT+0200 (CEST) to Tue May 01 2018 13:23:00 +0200, dateutil.parser.parse had no problem parsing this format.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49774090

http://stackoverflow.com/comment/86833147
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49908474
type: Comment
has text: Still doesn't solve the problem where they are very different output when visualized, or test using tf.equal.

http://stackoverflow.com/q/49854755
possible better answer: http://stackoverflow.com/a/49855077
tagged with: string
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49854882
has comment: http://stackoverflow.com/comment/86723981
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86733563
has title: Pythonic Way of replacing Multiple Characters
has body: I've created a onetime function a = lambda x: x.replace('\n', '') b = lambda y: y.replace('\t', '').strip() c = lambda x: b(a(x)) Is there a Pythonic and compact way (one liner?) to this to improve readability and performance. Mainly performance. (note: I know I can do lambda x: x.replace('\n').replace('\t\).strip() but doesn't do anything. Preferably there's a built-in method that deals with this type of issue that I wasn't aware of and I know that the performance improvements are negligible.) Input: 'my \t\t\t test, case \ntest\n LoremIpsum' Desired Output: 'my test, case test LoremIpsum'
has answer: http://stackoverflow.com/a/49855077
type: AnsweredQuestion
answer count: 2
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49854882

http://stackoverflow.com/q/49779076
has comment: http://stackoverflow.com/comment/86574586
has comment: http://stackoverflow.com/comment/86574138
has title: Alternative to eval in condition check scenarios
type: Question
has comment: http://stackoverflow.com/comment/86574409
has body: I have this json structure scenarios = [{"outcome_name":"outcome1", "checking_condition":[ { "db_key":"purchase_date", "operator":"&gt;" "db_value":"requested_date" }, { "db_key":"purchase_amount", "operator":"&lt;" "db_value":"5000" } ] outcome_selection_criteria:"index0 and index1" }] so if both checking conditions are true I'm marking outcome1 as being the choice selected, there may be any number of outcomes in scenarios list. Currently while I dynamically check conditions, I'm creating a string of the actual condition parameters like for the purchase amount , the string is : "4000 &lt; 5000" and I am performing an eval operation on this to get a boolean result. which I'm replacing in the outcome_selection_criteria string for its corresponding index value. then once all the criteria are replaced, i'm performing eval over the string to find the actual result of the outcome. However this I've heard is slow in terms of processing as eval is ineffecient. I'm not very sure how true this is. I'm going about this way as it allows to handle dynamically multiple types of conditional situations without changing the actual code I'm building. is there a better way to go about , rather than using eval. Additional Code Additions : while True: with open(outcome_name+".json","r") as jsonfile: scenarios_data = json.load(jsonfile) for each_outcome_dict in scenarios_data: outcome_name = each_outcome_dict["outcome_name"] for ind, each_condition in enumerate(each_outcome_dict["checking_condition"]): key = each_condition["db_key"] value = each_condition["db_value"] operator = each_condition["operator"] true_key = redis_db.get(key,key) true_val = redis_db.get(value,value) condition = true_key + " " + operator + " " + true_val result = str(eval(condition)) result_index = "index"+ind each_outcome_dict["outcome_selection_criteria"] = each_outcome_dict["outcome_selection_criteria"].replace(result_index, result) total_outcome = eval(each_outcome_dict["outcome_selection_criteria"]) if total_…
upvote count: 2
score: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49779329
favorite count: 0
has comment: http://stackoverflow.com/comment/86574754
has comment: http://stackoverflow.com/comment/86574668
has comment: http://stackoverflow.com/comment/86573936
tagged with: algorithm
tagged with: python
linked to: http://stackoverflow.com/q/43777551

http://stackoverflow.com/q/49782852
has title: Is there an easy way to have "checkpoints" in an extended python script?
accepted answer: http://stackoverflow.com/a/49782929
tagged with: architecture
tagged with: python
linked to: http://stackoverflow.com/q/17305173
has body: To preface my question let me give a bit of context: I'm currently working on a data pipeline that has a number of different steps. Each step can go wrong and many take some time (not a huge amount, but on the order of minutes). For this reason the pipeline is currently heavily supervised by humans. An analyst goes through each step, running the python code in a Jupyter notebook and upon experiencing problems will make minor code adjustments inline and repeat that section. In the long run, the goal here is to have zero human intervention. However, in the shorter term we'd like to make this process more seamless. The simplest way to do that seems like it would be to split each section into it's own script, and have a parent script that runs each bit and verifies output. However, we also need the ability to rerun the a file with an identical setup if it fails. For example: run a --&gt; ✅ run b --&gt; ✅ (b relies on some data produced by a) run c --&gt; ❌ (c relies on data produced by a and b) // make some changes to c run c --&gt; ✅ (c should run in an identical state to its original run) The most obvious way to do this would be to write output from each script to a file, and load all of these scripts into the next one. This would work, but seems a bit inelegant. A database seems another valid option, but a lot of the data doesn't fit cleanly into a db format. Does anyone have any suggestions for some ways to achieve what I'm looking for? If anything is unclear I'm also more than happy to clarify any points!
has answer: http://stackoverflow.com/a/49782929
favorite count: 0
score: 8
type: Question
has comment: http://stackoverflow.com/comment/86626279
answer count: 2
possible better answer: http://stackoverflow.com/a/49785936
downvote count: 0
has answer: http://stackoverflow.com/a/49785936
type: AnsweredQuestion
upvote count: 8

http://stackoverflow.com/q/49760882
accepted answer: http://stackoverflow.com/a/49771818
downvote count: 1
tagged with: plot
favorite count: 0
tagged with: networkx
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49761532
answer count: 3
score: 1
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49762285
tagged with: python
has body: Say I have two lists of words, list1 = ['Cat', 'Dog', 'Elephant', 'Giraffe' 'Monkey'] list2 = ['Cat', 'Dog', 'Eagle', 'Elephant', 'Monkey'] And I would like to create a plot that looks like this: Cat -&gt; Cat Dog -&gt; Dog Elephant \ Eagle Giraffe &gt; Elephant Monkey -&gt; Monkey Basically, a word 'ladder' plot with arrows connecting each common word between the two lists. If a given word in list1 doesn't have a counterpart in list2 (like Eagle and Giraffe in the example) then there is no arrow needed. I am not aware of a way to do this in matplotlib. Does anyone know how to do this in matplotlib (perhaps in conjunction with networkx?)? Bonus points if the plot works for an arbitrary number of lists (say with another set of arrows connecting list2 and list3 too, etc).
has answer: http://stackoverflow.com/a/49771818
has title: Python create word plot between two lists in matplotlib to show list commonality
possible better answer: http://stackoverflow.com/a/49761532
type: Question
has comment: http://stackoverflow.com/comment/86539148
linked to: http://stackoverflow.com/q/38987
upvote count: 2

http://stackoverflow.com/q/49802769
upvote count: 2
type: UnansweredQuestion
has body: I have this code so far that extracts text from the page URLs, using scrapy: class QuotesSpider(scrapy.Spider): name = "dialpad" def start_requests(self): urls = [ 'https://help.dialpad.com/hc/en-us/categories/201278063-User-Support', 'https://www.domo.com/', 'https://www.zenreach.com/', 'https://www.trendkite.com/', 'https://peloton.com/', 'https://ting.com/', 'https://www.cedar.com/', 'https://tophat.com/', 'https://www.bambora.com/en/ca/', 'https://www.hoteltonight.com/' ] for url in urls: BASE_URL = url yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): page = response.url.split("/")[2] filename = 'quotes-thing-{}.csv'.format(page) BASE_URL = response.url # with open(filename, 'wb') as f: # f.write(response.body) # # with open(filename, 'r') as f: with open(filename, 'w') as f: for selector in response.css('body').xpath('.//text()'): selector = selector.extract() f.write(selector) How can I also extract data from the links on those pages and write them to that filename that I create?
tagged with: python
has answer: http://stackoverflow.com/a/49803359
score: 1
tagged with: screen-scraping
answer count: 1
has title: How can I scrape links in all my webpages?
tagged with: scrapy
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49822422
accepted answer of: http://stackoverflow.com/q/49806594
has body: Assuming you can't restructure your app so this isn't necessary (e.g., by using multiprocessing instead of subprocess), there are three solutions: Ensure that the .exe contains the scripts as an (executable) zipfile—or just use pkg_resources—and copy the script out to a temporary directory so you can run it from there. Write a multi-entrypoint wrapper script that can be run as your main program, and also run as each script—because, while you can't run a script out of the packed exe, you can import a module out of it. Using pkg_resources again, write a wrapper that runs the script by loading it as a string and running it with exec instead. The second one is probably the cleanest, but it is a bit of work. And, while we could rely on setuptools entrypoints to some of the work, trying to explain how to do this is much harder than explaining how to do it manually,1 so I'm going to do the latter. Let's say your code looked like this: # main.py import subprocess import sys spam, eggs = sys.argv[1], sys.argv[2] subprocess.run([sys.executable, 'vikings.py', spam]) subprocess.run([sys.executable, 'waitress.py', spam, eggs]) # vikings.py import sys print(' '.join(['spam'] * int(sys.argv[1]))) # waitress.py import sys import time spam, eggs = int(sys.argv[1]), int(sys.argv[2])) if eggs &gt; spam: print("You can't have more eggs than spam!") sys.exit(2) print("Frying...") time.sleep(2) raise Exception("This sketch is getting too silly!") So, you run it like this: $ python3 main.py 3 4 spam spam spam You can't have more eggs than spam! We want to reorganize it so there's a script that looks at the command-line arguments to decide what to import. Here's the smallest change to do that: # main.py import subprocess import sys if sys.argv[1][:2] == '--': script = sys.argv[1][2:] if script == 'vikings': import vikings vikings.run(*sys.argv[2:]) elif script == 'waitress': import waitress waitress.run(*sys.argv[2:]) else: raise Exception(f'Unknown script {script}') else: spam, eggs = sys…
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86665565
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49806594
type: Answer

http://stackoverflow.com/comment/86729447
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49820591
has text: I still get the same error with or with out the secret key
type: Comment

python-2.7
tags question: http://stackoverflow.com/q/49821337
tags question: http://stackoverflow.com/q/49890010
tags question: http://stackoverflow.com/q/49761056
tags question: http://stackoverflow.com/q/49771030
tags question: http://stackoverflow.com/q/49862776
tags question: http://stackoverflow.com/q/49871187
tags question: http://stackoverflow.com/q/49802301
tags question: http://stackoverflow.com/q/49882563
tags question: http://stackoverflow.com/q/49783757
tags question: http://stackoverflow.com/q/49834062
tags question: http://stackoverflow.com/q/49889279
tags question: http://stackoverflow.com/q/49834671
tags question: http://stackoverflow.com/q/49796382
tags question: http://stackoverflow.com/q/49898585
tags question: http://stackoverflow.com/q/49874782
tags question: http://stackoverflow.com/q/49826341
tags question: http://stackoverflow.com/q/49906137
tags question: http://stackoverflow.com/q/49803221
tags question: http://stackoverflow.com/q/49893077
tags question: http://stackoverflow.com/q/49808911
tags question: http://stackoverflow.com/q/49910547
tags question: http://stackoverflow.com/q/49823117
tags question: http://stackoverflow.com/q/49914346
tags question: http://stackoverflow.com/q/49881448
tags question: http://stackoverflow.com/q/49765019
tags question: http://stackoverflow.com/q/49896788
tags question: http://stackoverflow.com/q/49846769
tags question: http://stackoverflow.com/q/49806184
tags question: http://stackoverflow.com/q/49881510
tags question: http://stackoverflow.com/q/49808828
tags question: http://stackoverflow.com/q/49901422
type: Tag
tags question: http://stackoverflow.com/q/49870594
tags question: http://stackoverflow.com/q/49770677
tags question: http://stackoverflow.com/q/49798329
tags question: http://stackoverflow.com/q/49846916
tags question: http://stackoverflow.com/q/49839669
tags question: http://stackoverflow.com/q/49896792
tags question: http://stackoverflow.com/q/49794765
tags question: http://stackoverflow.com/q/49893815
tags question: http://stackoverflow.com/q/49912262
tags question: http://stackoverflow.com/q/49780698
tags question: http://stackoverflow.com/q/49775199
tags question: http://stackoverflow.com/q/49764084
tags question: http://stackoverflow.com/q/49913065
tags question: http://stackoverflow.com/q/49764807
tags question: http://stackoverflow.com/q/49773873
tags question: http://stackoverflow.com/q/49902212
tags question: http://stackoverflow.com/q/49778642
tags question: http://stackoverflow.com/q/49768234
tags question: http://stackoverflow.com/q/49887288
tags question: http://stackoverflow.com/q/49914521
tags question: http://stackoverflow.com/q/49797288
tags question: http://stackoverflow.com/q/49788569
tags question: http://stackoverflow.com/q/49835133
tags question: http://stackoverflow.com/q/49823714
tags question: http://stackoverflow.com/q/49804230
tags question: http://stackoverflow.com/q/49833668
tags question: http://stackoverflow.com/q/49759309
tags question: http://stackoverflow.com/q/49837871
tags question: http://stackoverflow.com/q/49896202
tags question: http://stackoverflow.com/q/49832623
tags question: http://stackoverflow.com/q/49813128
tags question: http://stackoverflow.com/q/49769562
tags question: http://stackoverflow.com/q/49833283
tags question: http://stackoverflow.com/q/49808075
tags question: http://stackoverflow.com/q/49802662
tags question: http://stackoverflow.com/q/49842547
tags question: http://stackoverflow.com/q/49857105
tags question: http://stackoverflow.com/q/49792226
tags question: http://stackoverflow.com/q/49775390
tags question: http://stackoverflow.com/q/49895178
tags question: http://stackoverflow.com/q/49795137
tags question: http://stackoverflow.com/q/49895000
tags question: http://stackoverflow.com/q/49760359
tags question: http://stackoverflow.com/q/49914819
tags question: http://stackoverflow.com/q/49837608
tags question: http://stackoverflow.com/q/49899039
tags question: http://stackoverflow.com/q/49820099
tags question: http://stackoverflow.com/q/49809095

http://stackoverflow.com/a/49792407
answers question: http://stackoverflow.com/q/49791271
has body: You can use concurrent.futures import concurrent.futures import urllib.request from time import sleep from bs4 import BeautifulSoup import re import requests def scraper(url): list_counter = 0 try: scrape = requests.get(url, headers={"user-agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36"}, timeout=10) if scrape.status_code == 200: sleep(0.1) scrape = requests.get("http://data.alexa.com/data?cli=10&amp;dat=s&amp;url=" + url, headers={"user-agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36"}) html = scrape.content soup = BeautifulSoup(html, 'lxml') rank = re.findall(r'&lt;popularity[^&gt;]*text="(\d+)"', str(soup)) print("Server Status:", scrape.status_code, '-', u"\u2713", '-', list_counter, '-', url, '-', "Rank:", rank[0]) list_counter = list_counter + 1 else: print("Server Status:", scrape.status_code) list_counter = list_counter + 1 print(list_counter) pass except BaseException as e: exceptions.append(e) print() print(e) print() list_counter = list_counter + 1 print(list_counter) pass def load_url(url, timeout): with urllib.request.urlopen(url, timeout=timeout) as conn: return conn.read() list1 copy your list here(in order to save space) with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor: future_to_url = {executor.submit(load_url, url, 50): url for url in list1} for future in concurrent.futures.as_completed(future_to_url): url = future_to_url[future] try: data = future.result() except Exception as exc: print('%r generated an exception: %s' % (url, exc)) else: print('%r page is %d bytes' % (url, len(data))) with concurrent.futures.ProcessPoolExecutor() as executor: for n, p in zip(list1, executor.map(scraper, list1)): print(n, p) You will get output(just a few lines) http://www.coloradoindependent.com/169637/trump-pruitt-emissions-epa-pollution None Server Status: 200 - ✓ - 0 - https://thecrimereport…
score: 0
type: Answer

http://stackoverflow.com/comment/86605725
comment on: http://stackoverflow.com/q/49790070
type: Comment
type: QuestionComment
has text: @BryanOakley My bad, do you have an exemple or a link ?
score: 0

http://stackoverflow.com/a/49836753
has comment: http://stackoverflow.com/comment/93958639
has comment: http://stackoverflow.com/comment/96303111
has comment: http://stackoverflow.com/comment/86689271
score: 873
has comment: http://stackoverflow.com/comment/92179639
has comment: http://stackoverflow.com/comment/103223588
answers question: http://stackoverflow.com/q/49836676
has comment: http://stackoverflow.com/comment/90403326
downvote count: 8
has comment: http://stackoverflow.com/comment/90711328
has body: You must have inadvertently upgraded your system pip (probably through something like sudo pip install pip --upgrade) pip 10.x adjusts where its internals are situated. The pip3 command you're seeing is one provided by your package maintainer (presumably debian based here?) and is not a file managed by pip. You can read more about this on pip's issue tracker You'll probably want to not upgrade your system pip and instead use a virtualenv. To recover the pip3 binary you'll need to sudo python3 -m pip uninstall pip && sudo apt install python3-pip --reinstall If you want to continue in "unsupported territory" (upgrading a system package outside of the system package manager), you can probably get away with python3 -m pip ... instead of pip3.
accepted answer of: http://stackoverflow.com/q/49836676
type: Answer
upvote count: 881
has comment: http://stackoverflow.com/comment/94641477
has comment: http://stackoverflow.com/comment/98080196
has comment: http://stackoverflow.com/comment/87898926
has comment: http://stackoverflow.com/comment/86688849
has comment: http://stackoverflow.com/comment/87088136
type: AcceptedAnswer

colorbar
tags question: http://stackoverflow.com/q/49831961
tags question: http://stackoverflow.com/q/49761221
type: Tag
tags question: http://stackoverflow.com/q/49904296
tag name: colorbar

http://stackoverflow.com/a/49860067
has comment: http://stackoverflow.com/comment/86736541
score: 0
answers question: http://stackoverflow.com/q/49859091
has comment: http://stackoverflow.com/comment/86737510
has comment: http://stackoverflow.com/comment/86737652
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49859091
has body: Here is a function that works fine for all cases and return the list of all first candidates encountered if no choice can be made to separate them. def find_best(list_of_lists): i = 0 while len(list_of_lists[i]) == 0: i+=1 list_containing_candidates = list_of_lists[i][:] if len(list_containing_candidates) == 1 : return list_containing_candidates[0] else: if i+1 &lt; len(list_of_lists): for next_list in list_of_lists[i+1:]: for candidate in list_containing_candidates[:]: if candidate not in next_list: list_containing_candidates.remove(candidate) if len(list_containing_candidates) == 0: list_containing_candidates = list_of_lists[i][:] elif len(list_containing_candidates) == 1: return list_containing_candidates[0] return list_of_lists[i] # ambigous case, entire list of candidates returned print(find_best([[], [2, 3], [1], [1], [3]])) # 3 print(find_best([[5], [0, 8], [0, 8], [0, 8], [1]])) # 5 print(find_best([[0, 1], [0, 3], [0], [0], [2]])) # 0 print(find_best([[], [3, 6], [3, 5, 6], [6], [1]])) # 6 print(find_best([[], [3, 6], [3, 5], [6], [1]])) # 3 print(find_best([[1,3 ], [1, 3], [1,2,3], [1,3], []])) # [1,3]
has comment: http://stackoverflow.com/comment/86737109
has comment: http://stackoverflow.com/comment/86735811
type: Answer

http://stackoverflow.com/comment/86562582
has text: I'm not sure i need the timestamp as a feature. In my case i'm just trying to detect a pattern. From what i understand this has nothing to do with date/time (since the interval is conastant)
comment on: http://stackoverflow.com/q/49773491
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49805042
answers question: http://stackoverflow.com/q/49804996
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: Try people = re.findall(r'\bUsername:(\S+)\s+domain:(\S+).*(TECH-\d+)', data)

http://stackoverflow.com/comment/86712063
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49848407
has text: I don't think it will really be the same, `add_hunger` also calls `go_to_heaven()` if the hunger value exceed 100. Oh yes, is there a way to produce the ' ' in the format for `code`, I always do it by copying `code` and replace code with my contents, and I find it very inefficient.

http://stackoverflow.com/comment/86670915
score: 0
has text: Are u expecting alpha numeric sort ? i.e. img_9, img_10 and so on ?
type: Comment
comment on: http://stackoverflow.com/a/49827668
type: AnswerComment

http://stackoverflow.com/q/49813952
has answer: http://stackoverflow.com/a/49814584
accepted answer: http://stackoverflow.com/a/49814584
tagged with: tkinter
upvote count: 1
answer count: 1
downvote count: 0
has body: I'm trying to do a GUI to do a plot. The idea is that when I click "Submit" the plot will pop up, if I then click "Submit" again, the plot should close and open again. However, When I click "Submit" the plot shows up correctly, but I need to close the plot window manually for the button to release again? I've cleaned up my code to only contain the essentials: import matplotlib.pyplot as plt # import plot functions from mpl_toolkits.mplot3d import Axes3D from Tkinter import * ################################ TKINTER GUI ################################## root = Tk() label_1 = Label(root, text="File name:") entry_1 = Entry(root) entry_1.insert(0,"Input") label_1.grid(sticky=E) entry_1.grid(row=0, column=1, columnspan=3) def saveentry(): plt.close() name1 = entry_1.get() ################################### PLOTTING ################################## fig = plt.figure() ax = fig.gca(projection='3d') plt.show(fig) Button_1 = Button(root, text="Submit", command=saveentry) Button_1.grid(row=7,column=0, sticky=E) root.mainloop() # END OF SCRIPT What am I doing wrong?
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/4890159
score: 1
tagged with: python
has title: Close/Open Plot through Tkinter
type: Question

http://stackoverflow.com/a/49850984
answers question: http://stackoverflow.com/q/49850625
has comment: http://stackoverflow.com/comment/86717939
has body: You can round them in place using generator result = zip(layer, plateX, plateY, (round(x, 2) for x in plateM)) Saves memory and work for interpreter
score: 0
has comment: http://stackoverflow.com/comment/86718636
type: Answer

http://stackoverflow.com/comment/86727849
score: 0
comment on: http://stackoverflow.com/q/49856694
has text: I mean, @Ev.Kounis , why do you need to use "bears[bear]"
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86834758
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49908014
has text: @Joel Done as you asked. A straight line does seem to form, but it gets fuzzier as reach higher `k`s, and this is poisoning my plot and therefore the calculation of the scaling coefficient.

http://stackoverflow.com/comment/86761142
type: AnswerComment
has text: See the edit section, also you may be missing something as, trashed=false should be correct way. Look closely
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49872364

homebrew
tags question: http://stackoverflow.com/q/49788769
tag name: homebrew
tags question: http://stackoverflow.com/q/49905640
tags question: http://stackoverflow.com/q/49902332
tags question: http://stackoverflow.com/q/49786869
tags question: http://stackoverflow.com/q/49911259
tags question: http://stackoverflow.com/q/49793849
type: Tag

http://stackoverflow.com/a/49849629
has comment: http://stackoverflow.com/comment/86714056
downvote count: 0
upvote count: 1
has body: lambda is just a syntax shortcut to put a function as a parameter without defining it explicitly on the lines above. Lambdas are restricted Lambdas are restricted to a single expression. So for longer functions you do have to define them separately The code above could be re-written as def getKey(): return tup[0] sorted(authorlist, key = getKey, reverse = True) This code is functionally equivalent to the one you posted in the question. The purpose of lambda is to extract the first field from the tuple that you are sorting.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49849589

http://stackoverflow.com/comment/86620178
type: Comment
comment on: http://stackoverflow.com/a/49802293
type: AnswerComment
has text: @sciroccorics Well, if you wrote the program "right" in the first place, then you reduce (or, in some cases, remove) the preliminary work required to convert it from one interface to another.
score: 0

http://stackoverflow.com/comment/86747692
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49848871
has text: Are you sure about this?
type: AnswerComment

http://stackoverflow.com/q/49861625
has comment: http://stackoverflow.com/comment/86739093
has answer: http://stackoverflow.com/a/49861794
tagged with: python
has answer: http://stackoverflow.com/a/72175708
tagged with: interpreter
answer count: 2
has comment: http://stackoverflow.com/comment/86738526
upvote count: 1
type: UnansweredQuestion
has body: def main(): cmd = (raw_input('#&gt;&gt;')) if cmd=="SND_CMD_CREDITS": print "This language is made by Biohazard166 (Bioclassic23) or Dreadlurker36" main() if cmd=="SND_CMD_HELP": print"Unfinsihed" main() if cmd=="SND_CMD_VER": print"This language is in VrPre-Alpha TEST PHASE 1" main() else: print cmd, print " unknown command." main() print "Dreadscript Shell" main() everything from the SND_CMD_VER down does not work it does not even display an error message at all as the error msg is "unknown command" is the scripting wrong or is there a bug thats so obvious it makes me look like an idiot?
has comment: http://stackoverflow.com/comment/86738581
downvote count: 7
has comment: http://stackoverflow.com/comment/86738468
score: -6
favorite count: 0
has comment: http://stackoverflow.com/comment/86738532
type: Question
has title: Interpreter not working

http://stackoverflow.com/comment/86811748
type: Comment
type: QuestionComment
has text: If you use CPU only you could install `pytorch` in the Windows subsystem for Linux.
comment on: http://stackoverflow.com/q/49893932
score: 0

http://stackoverflow.com/comment/86599718
type: AnswerComment
comment on: http://stackoverflow.com/a/49792565
type: Comment
has text: This WOULD work for XL, because it takes the last word. But wouldn't work if the size is not the last word.
score: 0

http://stackoverflow.com/q/49905415
accepted answer: http://stackoverflow.com/a/49905499
type: Question
duplicate of: http://stackoverflow.com/q/38982640
has title: How do i set environment variable using python script
tagged with: scripting
tagged with: python
linked to: http://stackoverflow.com/q/8365394
linked to: http://stackoverflow.com/q/38982640
has answer: http://stackoverflow.com/a/49905499
type: AnsweredQuestion
tagged with: environment-variables
score: 0
duplicate of: http://stackoverflow.com/q/8365394
has comment: http://stackoverflow.com/comment/86826727
answer count: 1
has body: I tried both os.environ['TemporaryVar'] = "Apple" and os.putenv("TemporaryVar", "Apple") but after running the python script, when i run the command env or set in the command line, i do not see variable as TemporaryVar=Apple I also have a sleep(50) in the python script so that the script does not terminate while i am checking for set or env in command line. What i want is to write a python script that adds a variable to the environment variable. (I should be able to see it when i type env)

http://stackoverflow.com/comment/86838999
score: 0
type: Comment
has text: Another duplicate [Can I sort a list of objects by 2-keys](https://stackoverflow.com/questions/29678659/can-i-sort-a-list-of-objects-by-2-keys)
type: QuestionComment
comment on: http://stackoverflow.com/q/49911535

http://stackoverflow.com/a/70675488
answers question: http://stackoverflow.com/q/49758189
score: 0
type: Answer
has body: Async example with httpx, which is compatible with both asyncio and trio, and have a very similar interface to requests. import trio, time import httpx sites = [ 'https://www.yahoo.com/', 'https://www.cnn.com', 'https://www.python.org', 'https://www.jython.org', 'https://www.pypy.org', 'https://www.perl.org', 'https://www.cisco.com', 'https://www.facebook.com', 'https://www.twitter.com', 'https://www.macrumors.com/', 'https://arstechnica.com/', 'https://www.reuters.com/', 'https://abcnews.go.com/', 'https://www.cnbc.com/', ] async def link_user(url): print("starting to fetch", url) async with httpx.AsyncClient() as client: r = await client.get(url) print("finished fetching", url, len(r.content)) async def show_len(sites): t1 = time.time() async with trio.open_nursery() as nursery: for url in sites: nursery.start_soon(link_user, url) print("code took to run", time.time() - t1) if __name__ == "__main__": trio.run(show_len, sites)

http://stackoverflow.com/q/49852306
tagged with: matplotlib
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/86719163
has title: How to change the background to transparent in matplotlib without saving the figure?
answer count: 0
upvote count: 2
has body: I need to add a widget in a kivy GUI, but the plot looks very ugly with the default background. I tried to change the facecolor to black but it is still very monotonous and the edge of the plot cannot be changed. The background of the kivy canvas is good enough and how can I set the whole plot to be transparent without saving it as a file (as I need to update the plot constantly)? try: plt.plot(np.array(time_arr)[-10:], np.array(hum_data)[-10:]) except IndexError: plt.plot(np.array(time_arr),np.array(hum_data)) plt.xlabel('time') plt.ylabel('moisture') plt.title('Real-time Moisture') plt.ylim((0, 1200)) self.graph = FigureCanvasKivyAgg(plt.gcf()) super(MainScreen, self).__init__(**kwargs) self.ids.right.add_widget(self.graph) Clock.schedule_interval(self.reload, 10)
linked to: http://stackoverflow.com/q/36332349
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86719152
type: UnansweredQuestion
score: 1

neupy
tags question: http://stackoverflow.com/q/49908588
type: Tag
tag name: neupy

http://stackoverflow.com/q/49784102
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/68774
tagged with: python-2.7
tagged with: bash
downvote count: 0
score: 1
tagged with: netcat
has title: Process output of netcat and return back using python
type: Question
has comment: http://stackoverflow.com/comment/86583795
answer count: 0
tagged with: subprocess
has body: I run netcat to listen to a server in a bash shell: nc domain.com 1234 The server outputs three numbers; I need to perform arithmetic on them and send the result back to the server. I have this code: #!/usr/bin/env python import subprocess nccommand = "nc domain.com 1234 &gt; ncoutput.txt" subprocess.Popen(nccommand, shell=True) with open("ncoutput.txt") as f: lines = f.readlines() lines = [x.strip() for x in lines] lines = [int(x) for x in lines] result = (lines[0]*lines[1])/lines[2] *command to input result into the netcat stream goes here* ncouput.txt isn't created until the netcat command is closed, which is problem because I need to have it open to stream the calculation result Also, I'm not sure how to input a string into the command line whilst the netcat stream is still open. Should I just do subprocess.Popen(numinput, shell=True)?
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86610001

http://stackoverflow.com/a/49781350
has comment: http://stackoverflow.com/comment/86580788
type: Answer
accepted answer of: http://stackoverflow.com/q/49777214
has comment: http://stackoverflow.com/comment/86617863
has comment: http://stackoverflow.com/comment/86580275
has body: Your example is not very clear, but you always have to do the verifications, for this you can use assert import sys import requests from PyQt4.QtGui import QImage, QApplication, QLabel, QPixmap app = QApplication(sys.argv) href = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/OrteliusWorldMap.jpeg/800px-OrteliusWorldMap.jpeg" r = requests.get(href, stream=True) assert r.status_code == 200 img = QImage() assert img.loadFromData(r.content) w = QLabel() w.setPixmap(QPixmap.fromImage(img)) w.show() sys.exit(app.exec_()) Libraries: requests 2.18.4 PyQt4 4.12.1 Python 2.7.14 and Python 3.6.4 It is always good to verify the appropriate formats, for this you must use: print(QImageReader.supportedImageFormats())
answers question: http://stackoverflow.com/q/49777214
has comment: http://stackoverflow.com/comment/86580785
upvote count: 3
has comment: http://stackoverflow.com/comment/86580955
has comment: http://stackoverflow.com/comment/86580387
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86581036
has comment: http://stackoverflow.com/comment/86587863
has comment: http://stackoverflow.com/comment/86580625
has comment: http://stackoverflow.com/comment/86580728
score: 3
has comment: http://stackoverflow.com/comment/86580821
has comment: http://stackoverflow.com/comment/86587877

http://stackoverflow.com/comment/108184569
has text: why not just `sudo nano \`which pip\`` ?
comment on: http://stackoverflow.com/a/51462434
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86692799
has text: It says "ERROR: To modify pip, please run the following command: C:\Users\my name\Appdata\Local\Programs\Python\Python36\python.exe -m pip"
comment on: http://stackoverflow.com/a/49838201
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86657472
score: 0
comment on: http://stackoverflow.com/q/49821089
type: Comment
has text: I use python 3.6 and wget doesn't work
type: QuestionComment

http://stackoverflow.com/a/49842314
has comment: http://stackoverflow.com/comment/86699724
has body: The purpose of the virtual environment is to isolate the dependencies inside it so you don't have to worry about knowing the precise path to the correct Python interpreter or the libraries you have installed. So while using the absolute path is technically not incorrect, it completely bypasses the facilities of the virtualenv, and could eventually end up pointing to the wrong location if you hardcode it in a script today, and decide to move, migrate, or refactor your virtualenv tomorrow.
has comment: http://stackoverflow.com/comment/86699650
score: 0
has comment: http://stackoverflow.com/comment/86699587
has comment: http://stackoverflow.com/comment/86699560
has comment: http://stackoverflow.com/comment/86699524
type: Answer
answers question: http://stackoverflow.com/q/49842217
has comment: http://stackoverflow.com/comment/86700340

http://stackoverflow.com/q/49858717
linked to: http://stackoverflow.com/q/301134
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has body: I defined a directory named common in the root directory of my project. Basically, there isn't a main file, but rather lots of scripts which I want to directly run. What I want to do is something like that: from ../../common/ import &lt;python_file&gt; Is it possible without too much of a hustle? Would I need to put __init__.py to make it work?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86732988
has title: Import a python class from an upper directory
tagged with: python
has answer: http://stackoverflow.com/a/49858814
accepted answer: http://stackoverflow.com/a/49858814
type: AnsweredQuestion

http://stackoverflow.com/q/49819880
tagged with: python
tagged with: string
has comment: http://stackoverflow.com/comment/86654879
favorite count: 0
has comment: http://stackoverflow.com/comment/86654980
type: AnsweredQuestion
has title: remove string characters after first instance in python
has answer: http://stackoverflow.com/a/49820155
score: 1
linked to: http://stackoverflow.com/q/6005891
has comment: http://stackoverflow.com/comment/86655004
tagged with: replace
type: Question
has answer: http://stackoverflow.com/a/49820132
accepted answer: http://stackoverflow.com/a/49820132
answer count: 2
downvote count: 0
has body: I think this should be pretty simple, but its a friday afternoon and my brain isnt in gear clearly. I'm writing a small file parse, and the code below turns a set of strings in to a dataframe, splitting the strings up. Here are some example strings: 1. NC_002523_1 Serratia entomophila plasmid pADAP, complete sequence. 2. NZ_CM003366_0 Pantoea ananatis strain CFH 7-1 plasmid CFH1-7plasmid2, whole genome shotgun sequence. 3. NZ_CP014491_0 Escherichia coli strain G749 plasmid pG749_3, complete sequence. 4. NC_015062_0 Rahnella sp. Y9602 plasmid pRAHAQ01, complete sequence. I hadn't anticipated the . after sp in the 4th entry, and as you can see in the code below, I split on the . to get the first integer for the rank. Consequently I get a ValueError, that there were more columns than expected. # Define the column headers for the section since the file's are too verbose and ambiguous SigHit.Columns = ["Rank", "ID", "Description"] # Store the table of loci and associated data (tab separated, removing last blank column. # Use StringIO object to imitate a file, which means that we can use read_table and have the dtypes # assigned automatically (necessary for functions like min() to work correctly on integers) SigHit.Table = pd.read_table( io.StringIO(u'\n'.join([row.rstrip('.') for row in sighits_section])), sep='\.|\t', engine='python', names=SigHit.Columns) The simplest solution for this that I can think of (until some other edge case breaks it), is to replace every . except the first occurrence. How can this be done? I see that there is a maxreplace argument to .replace, but this would do the opposite of what I want, and would only replace the first instance. Any suggestions? (More robust parsing approaches also a valid option, but the less I have to change the code the better).
upvote count: 1
possible better answer: http://stackoverflow.com/a/49820155

http://stackoverflow.com/q/49850910
has body: I found out that on streaming DataFrames/Datasets in PySpark does not support stateful operations. Link -> Arbitrary Stateful Operations I've tons of python code already. And I a bit worried about the aspect of moving our code to Scala / Java language. Can someone clarify, will the python have stateful operations functionality in the next versions? If so when approximately will be available? Thanks
has comment: http://stackoverflow.com/comment/91345783
favorite count: 0
upvote count: 3
score: 3
tagged with: apache-spark-sql
tagged with: spark-streaming
tagged with: pyspark
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/91418518
answer count: 0
downvote count: 0
tagged with: apache-spark
has title: Will Structured Streaming(DataFrames/Datasets) in PySpark be supported stateful operations?
type: UnansweredQuestion

http://stackoverflow.com/q/49869142
has comment: http://stackoverflow.com/comment/86753706
has body: I have a data frame like this, import pandas as pd d = {'ID':["A","A","A","A","A","A","A","A","A","A","A","A"], 'date':["2017-01-01","2017-01-01","2017-01-01","2017-01-02","2017-01-02","2017-01-02","2017-01-03","2017-01-03", "2017-01-03","2017-01-04","2017-01-04","2017-01-04"], 'time':["00:00","06:00","12:00","00:00","06:00","12:00","00:00","06:00","12:00","00:00","06:00","12:00"], 'value':[23,100,330,57,122,477,46,99,469,37,118,499]} df = pd.DataFrame(data=d) df['date'] = pd.to_datetime(df['date']) print(df) ID date time value 0 A 2017-01-01 00:00 23 1 A 2017-01-01 06:00 100 2 A 2017-01-01 12:00 330 3 A 2017-01-02 00:00 57 4 A 2017-01-02 06:00 122 5 A 2017-01-02 12:00 477 6 A 2017-01-03 00:00 46 7 A 2017-01-03 06:00 99 8 A 2017-01-03 12:00 469 9 A 2017-01-04 00:00 37 10 A 2017-01-04 06:00 118 11 A 2017-01-04 12:00 499 I want to generate a new column contains historical data based on the time sequence. And the final data frame would be like this, ID date time value avg 0 A 2017-01-01 00:00 23 23 1 A 2017-01-01 06:00 100 100 2 A 2017-01-01 12:00 330 330 3 A 2017-01-02 00:00 57 23 4 A 2017-01-02 06:00 122 100 5 A 2017-01-02 12:00 477 330 6 A 2017-01-03 00:00 46 40 # (23+57)/2 = 40 7 A 2017-01-03 06:00 99 111 # (100+122)/2 = 111 8 A 2017-01-03 12:00 469 403.5 # (330+477)/2 = 403.5 9 A 2017-01-04 00:00 37 42 # (23+57+46)/3 = 42 10 A 2017-01-04 06:00 118 107 # (100+122+99)/3 = 107 11 A 2017-01-04 12:00 499 425.3 # (330+477+469)/3 = 425.333 The new column avg calculate the average value of the data on the same historical time point. So, the first two days are the same-- just copy the data of the first day. Then the third day will be the average of first two days, and so on. This is just a sample data set. I hope someone can have a general function to solve this problem. Thanks!
has title: How to aggregate data by historical time series values in python dataframe?
accepted answer: http://stackoverflow.com/a/49869417
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86753967
has answer: http://stackoverflow.com/a/49869417
type: AnsweredQuestion
tagged with: pandas
score: 0
answer count: 1
type: Question
tagged with: numpy

http://stackoverflow.com/q/49787069
answer count: 1
downvote count: 0
has body: I am using python 3.6.5 and Windows 10. I need to get the TLS version that the server selected (i.e. the one that will be used for the rest of the handshake and NOT the client's offered version). I did this: import socket, ssl context = context = ssl.create_default_context() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) domain = 'google.com' sslSocket = context.wrap_socket(s, server_hostname = domain) sslSocket.connect((domain, 443)) print('the selected version by the server: ', sslSocket.cipher()[1]) print("success") sslSocket.close() But the output is: the selected version by the server: TLSv1/SSLv3 success I need accurate version. i.e, in a connection to google.com, it is TLS 1.2 as the browser shows. How can I get accurate version in my code?
tagged with: pyopenssl
favorite count: 0
type: AnsweredQuestion
score: 3
tagged with: ssl
tagged with: python
tagged with: tls1.2
has title: How to get the server's selected TLS verison in python ssl
accepted answer: http://stackoverflow.com/a/49788076
type: Question
has answer: http://stackoverflow.com/a/49788076
upvote count: 3
tagged with: sockets

http://stackoverflow.com/q/49801773
has comment: http://stackoverflow.com/comment/86618134
has comment: http://stackoverflow.com/comment/86618186
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49802281
has body: How can I do this in python? a = 0 func(a+=1) # a = 1 func(a+=1) # a = 2 Now I have had to solve it like this: a = 0 a+=1 func(a) a+=1 func(a) ... and there must be a better way, right? Edit: Actually I also want to be able to pass it to different functions: a = 0 a+=1 func1(a) a+=1 func2(a) a+=1 func1(a) ...
has answer: http://stackoverflow.com/a/49802251
has comment: http://stackoverflow.com/comment/86618289
has answer: http://stackoverflow.com/a/49802170
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/86618180
has title: Pass a variable that increases as it is called?
has comment: http://stackoverflow.com/comment/86619564
score: 0
has comment: http://stackoverflow.com/comment/86618244
linked to: http://stackoverflow.com/q/1485841
has answer: http://stackoverflow.com/a/49801850
has comment: http://stackoverflow.com/comment/86618276
upvote count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/86781952
comment on: http://stackoverflow.com/q/49882948
has text: I don't understand the problem. How is it relevant that the struct is written to a compressed file? What's that about passing something as a parameter to a function? Which part of your code doesn't work as intended?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/86790401
comment on: http://stackoverflow.com/q/49887084
has text: In fact, you could replace this entire function with `return ''.join(random.choices('qwer', k=random.randint(10, 20)))`
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86608725
type: QuestionComment
comment on: http://stackoverflow.com/q/49797091
type: Comment
has text: ... but that still would read forward. the actual issue is lookup complexity.
score: 0

http://stackoverflow.com/comment/86874361
has text: And if you think about it carefully you'll realize that this is pretty much the only sensible way of dealing with subgroups. If the engine had to store every instance of captured text for a subgroup that could repeat thousands times and then had to *backtrack* to find the better match it would grind to a halt because of useless memory allocation/deallocation.
type: Comment
comment on: http://stackoverflow.com/a/49888220
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86542745
has text: There's no built-in for this, but you are hardly limited to built-in functions for the `key` parameter: `key=lambda item: item[1][1]`
comment on: http://stackoverflow.com/q/49763507
type: Comment
score: 4
type: QuestionComment

http://stackoverflow.com/q/49829614
score: 0
tagged with: filter
has title: I want to use 'keywords' to help me filter csv data
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49829907
accepted answer: http://stackoverflow.com/a/49829907
has comment: http://stackoverflow.com/comment/86674846
has comment: http://stackoverflow.com/comment/86674676
tagged with: python
has comment: http://stackoverflow.com/comment/86674908
has comment: http://stackoverflow.com/comment/86674428
type: Question
has body: I have to filter out csv data from given information and print it out. I am new to python and what I had in my head was, I would make keywords in a list, than I would write some function that if it has those words in the csv data it will print out my data. This is what I tried keywords = ("AIG","Baylor","CGG","Citi","EcconMobil","Flow-Cal Inc.", "Global SHop Solutions","Harris Count CTS","HCSS", "Hitachi Consulting", "HP Inc.","INT Inc.","JPMorgan Chase &amp; Co", "Leidos","McKesson","MRE Consulting Ltd.","NetIQ","PROS", "San Jacinto College","SAS","Smartbridge","Sogeti USA", "Southwest Research Institute","The Reynolds and Reynolds Company", "UH Enterprise Systems","U.S. Marine Corps","ValuD Consuting LLC","Wipro") pattern = (" ".join(keywords)) with f as filterf: for line in filterf: if not re.search(pattern,line): print(line.strip()) print(pattern) This is what I needed printed out 0 AIG,10,,,,Yes,,,Jr,,,MS,, 1 Baylor College of Medicine,19,Yes,Yes,,,,,,,,,,Recent 2 CGG,17,Yes,Yes,,,,,,,,MS,PhD,Recent 3 Citi,27/28,Yes,,,Yes,,,Jr,Sr,,,, 4 ExxonMobil,11,Yes,,,Yes,Fr,Soph,Jr,Sr,PB,,, 5 Flow-Cal Inc.,16,Yes,,,Yes,,,Jr,Sr,,,,All 6 Global Shop Solutions,18,Yes,,,Yes,,,,Sr,PB,,,All 7 Harris County CTS,22,Yes,,,Yes,,,Jr,Sr,PB,MS,PhD,All 8 HCSS,29,Yes,,,Yes,Fr,Soph,Jr,Sr,PB,MS,,Recent 9 Hitachi Consulting,13,Yes,,,,,,,Sr,,MS,, 10 HP Inc.,1,Yes,,,Yes,,,Jr,,,MS,,Recent 11 INT Inc.,20,Yes,Yes,,Yes,,,Jr,Sr,,MS,PhD, 12 JPMorgan Chase &amp; Co,3,Yes,,,Yes,,,Jr,Sr,,,, 13 Leidos,390,Yes,,,Yes,Fr,Soph,Jr,Sr,PB,MS,, 14 McKesson,26,Yes,,,,,,,Sr,,,, 15 MRE Consulting Ltd.,2,Yes,,,,,,,Sr,PB,MS,,All 16 NetIQ,7,,,,Yes,,Soph,Jr,Sr,PB,,, 17 PROS,21,Yes,,,,,,,Sr,,MS,PhD,All 18 San Jacinto College ,14,,,,Yes,,Soph,Jr,Sr,PB,MS,, 19 SAS,4,Yes,,,Yes,Fr,Soph,Jr,Sr,PB,MS,,Recent 20 Smartbridge,8,Yes,,,,,,,Sr,PB,MS,, 21 Sogeti USA,15,Yes,,,,,,,Sr,PB,MS,, 22 Southwest Research Institute,12,Yes,,,Yes,,,Jr,Sr,PB,MS,PhD,All 23 The Reynolds and Reynolds Company,23,Yes,Yes,,Yes,Fr,Soph,Jr,Sr,PB,,,All 2…
has comment: http://stackoverflow.com/comment/86674805
answer count: 1
has comment: http://stackoverflow.com/comment/86674440
type: AnsweredQuestion

http://stackoverflow.com/comment/95584427
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49898117
has text: `conda install -c menpo dlib` is fine.

http://stackoverflow.com/comment/86590256
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49787422
has text: Same thing was asked yesterday: https://stackoverflow.com/questions/49765578/transforming-a-list-to-a-column-vector-in-python

http://stackoverflow.com/a/49819833
answers question: http://stackoverflow.com/q/49819714
upvote count: 2
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49819714
has body: You can use a for-loop Ex: for i in range(1, 10): next_link = browser.find_element_by_xpath('//*[@title="Go to page {0}"]'.format(str(i+1))) #using str.format for page number next_link.click() time.sleep(30)
score: 1
type: Answer

http://stackoverflow.com/comment/86915768
comment on: http://stackoverflow.com/q/49901661
score: 0
type: Comment
type: QuestionComment
has text: then your example is not reproducible

http://stackoverflow.com/a/49789728
has comment: http://stackoverflow.com/comment/86601193
has comment: http://stackoverflow.com/comment/86601853
score: 0
has body: I suggest you to maintain a list of titles in your spider, and then inside pipeline, check if title already exists in that lists, then do not yield it. class CheckCsvPipeline(object): def __init__(self): pass def process_item(self, item, spider): if item['title'] in spider.allTitles: raise DropItem("This title exists: %s" % item) else: return item in your spider, do this class BooksSpider(scrapy.Spider): name = 'books' allowed_domains = ['books.toscrape.com'] start_urls = ['http://books.toscrape.com/'] allTitles = [] def parse(self, response): books = response.xpath('//h3/a/@href').extract() for book in books: absolute_url = response.urljoin(book) yield scrapy.Request(absolute_url, callback=self.parse_book) # process next page next_page_url = response.xpath('//a[text()="next"]/@href').extract_first() absolute_next_page_url = response.urljoin(next_page_url) yield scrapy.Request(absolute_next_page_url) def parse_book(self, response): title = response.css('h1::text').extract_first() self.allTitles.extend([ title ]) price = response.xpath('//*[@class="price_color"]/text()').extract_first() yield {'title':title, 'price': price}
answers question: http://stackoverflow.com/q/49773950
has comment: http://stackoverflow.com/comment/86599898
type: Answer

http://stackoverflow.com/comment/86794986
type: Comment
comment on: http://stackoverflow.com/q/49873801
score: 0
has text: before we trying to enumerate error cases, could you please check if you've included script2.py in the files to be staged? https://github.com/apache/beam/blob/master/sdks/python/apache_beam/options/pipeline_options.py#L620
type: QuestionComment

http://stackoverflow.com/comment/86833924
comment on: http://stackoverflow.com/a/49908880
score: 0
type: AnswerComment
type: Comment
has text: Thanks, that works well ! I now use `viddata = np.load(viddata_path, mmap_mode="r+")` . However, later on I need to convert my ndarray to `float32` dtype but I run into a MemoryError which is what I was trying to avoid in the first place. Any tips ?

http://stackoverflow.com/comment/86556662
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49770870
type: Comment
has text: oh -- did not find that info. Thanks

http://stackoverflow.com/comment/86638636
score: 0
type: QuestionComment
has text: Please give us your current code
type: Comment
comment on: http://stackoverflow.com/q/49811533

http://stackoverflow.com/a/49825549
answers question: http://stackoverflow.com/q/49810483
type: Answer
score: 0
has body: So pass two methods: one that is the meta-operation, which accepts the operation: def one_iteration(meta_op, my_op, data, ...): for i in range(...): ... meta_op(my_op, data) ... And let meta_op decide how to handle the results.

http://stackoverflow.com/comment/86782883
type: Comment
type: QuestionComment
has text: Can't you just do `np.cross(tangents_x[:,None,:], tangents_y)`?
score: 2
comment on: http://stackoverflow.com/q/49881468

http://stackoverflow.com/a/49842856
type: Answer
answers question: http://stackoverflow.com/q/49842718
has comment: http://stackoverflow.com/comment/134225952
upvote count: 3
score: 3
type: AcceptedAnswer
has body: You can use printing.default_latex, which returns the expression in LaTex as a string: from IPython.display import Math import sympy from sympy.interactive import printing x = sympy.var('x') f=(-2*x-1)/(pow(x,2)+2) Math('F(x) = {} + C'.format(printing.default_latex(sympy.integrate(f, x))))
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49842718

http://stackoverflow.com/q/49833636
has title: Download data from Yahoo! Finance
upvote count: 1
has answer: http://stackoverflow.com/a/49833737
has answer: http://stackoverflow.com/a/51273934
possible better answer: http://stackoverflow.com/a/51273934
favorite count: 0
tagged with: beautifulsoup
type: Question
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/14037540
score: 1
accepted answer: http://stackoverflow.com/a/49833737
tagged with: python
tagged with: yahoo-finance
has body: Hi I recently took up a project about bitcoin analysis and need to download financial data from Yahoo! Finance via Python. I tried fix_yahoo_finance and pandas datareader but there seems to be a bug on the website when downloading files. It always miss some days. So I decided to use beautiful soup, the code is as follow: import requests import time import pandas as pd from bs4 import BeautifulSoup def time_convert(dt): time.strptime(dt,'%Y-%m-%d %H:%M:%S') s = time.mktime(time.strptime(dt,'%Y-%m-%d %H:%M:%S')) return str(int(s)) s = requests.Session() start = time_convert("2016-02-15 00:00:00") end = time_convert("2018-02-15 00:00:00") r = s.get("https://uk.finance.yahoo.com/quote/BTC-USD/history?period1="+start+"&amp;period2="+end+"&amp;interval=1d&amp;filter=history&amp;frequency=1d" soup = BeautifulSoup(r.text, 'lxml') tables = soup.select('table') df_list = [] for table in tables: df_list.append(pd.concat(pd.read_html(table.prettify()))) df = pd.concat(df_list) df.to_excel("E:\PythonData\price_"+'.xlsx') It works but the data is not complete because the website loads the data when your mouse scroll s down to the end of the page, but codes doesn't do that. How can I fix this?
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/86795251
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49889591
score: 0
has text: You a list starts at 0, try: `for i in range (1, upper):`

http://stackoverflow.com/comment/86710831
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49846437
has text: I believe that there may have been a memory issue someplace on my machine cause it works like a charm now. Essentially I was attempting to just run through this file, add every other line to the previous line then number them just as a check that I covered everything. For some reason when the count was running it started at 2 when I had count initially set to 0. It wouldn't print out "1)" until I changed count to -1 initially. That print statement is an L, not a 1. I have no idea why it was doing that. I didn't get an error, it ran fine just with the wrong numbers for about 4-5 runs.
score: 0

http://stackoverflow.com/comment/86624625
comment on: http://stackoverflow.com/q/49804018
has text: @CristiFati Apologies! Hamming codes are a 2-dimensional extension of parity checks that allow error detection and correction in a stream of bits. In these codes, positions 1,2,4,8,16 are called parity locations and rest all data locations. I'm inserting P at these locations, and now I need to find these bits using the remaining bits indexes.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86563613
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49774165
has text: defaultdict. yes. better than mine :)

http://stackoverflow.com/q/49804037
tagged with: udp
has comment: http://stackoverflow.com/comment/87093577
has title: UDP server packet delay (python)
has comment: http://stackoverflow.com/comment/86623097
favorite count: 0
tagged with: server
type: Question
score: 0
has comment: http://stackoverflow.com/comment/86622718
answer count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
downvote count: 1
has body: I've created an UDP client-server system. The idea behind it is that multiple clients connect to the server and send it packets. The taks of the server is to send these packets to all the other clients. It's kinda working howerver there is a delay on the clients side where it recieves packets later then it is suspose to arrive. It's almost like the packets are queued and processed later. Is there anything that can be done against this delay? I made this for a game which needs multiplayer. The client his worldpostion to the server and the server sends it to the client. If the client recieves the package then apply the movement to the right user. This is where the delay happens! the way I initialize the server: self.server = socket.socket(socket.AF_INET, socket. self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server.bind((self.bind_ip, self.bind_port)) The listener request, addr = self.server.recvfrom(1024) if 'position' in decoded_request. self.latest_pos['init_connection']["{}:{}".format(addr[0],addr[1])] = decoded_request['position']['coordinates'] self.broadcast_message(request) Broadcast_message method: def broadcast_message(self, packet): for client in self.user_addresses.values(): self.server.sendto(packet, (client[0], client[1])) The client: data, addr = self.server.recvfrom(1024) data = json.loads(data.decode) ** here is the code that handles the packet ** a.k.a. apply the movement to the player if it recieves a json with the e.g. a worldposition then apply the movement to the user object that equals the ip.

http://stackoverflow.com/a/49824776
has comment: http://stackoverflow.com/comment/86665556
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49824684
has comment: http://stackoverflow.com/comment/86665581
score: 3
type: Answer
has body: This has nothing to do with daemons. main doesn't have access to my_file; you didn't pass the file in as an argument or anything.
accepted answer of: http://stackoverflow.com/q/49824684
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86665676

http://stackoverflow.com/q/49868468
has comment: http://stackoverflow.com/comment/86752599
has answer: http://stackoverflow.com/a/49868588
type: UnansweredQuestion
has title: Finding a strings that contain different substrings
tagged with: python
has comment: http://stackoverflow.com/comment/86752563
has comment: http://stackoverflow.com/comment/86752595
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86752431
type: Question
has body: The data i have is equivalent to this, fun_strings=[] fun_strings=['abc','cat','but','cab','mug','xyz'] I need to collect strings from this list that contain a 'u' or 't' my desired output is, ['cat','but','mug'] It seems i can do this the slow way with a list [x for x in fun_strings if 'u' in x or 't' in x] Can i do this a faster way with numpy?
tagged with: numpy
has answer: http://stackoverflow.com/a/49869411

http://stackoverflow.com/q/49881026
type: Question
type: UnansweredQuestion
tagged with: package
downvote count: 2
linked to: http://stackoverflow.com/q/31128333
has title: Import from the package from within the package
upvote count: 1
tagged with: python
has body: This question is similar to the following questions: python import class in init.py from file in same package how to import classes defined in init.py However, the solutions there did not work for me. At runtime I always get the following error: ImportError: no module named 'project' My project directory is simple project\ - project\ - __init__.py - views.py - modules.py When I try to import from the init.py file I use from . import app or from project import app I am getting the error I stated above. I can't seem to figure it out. please help!!!
tagged with: flask
has answer: http://stackoverflow.com/a/49882622
linked to: http://stackoverflow.com/q/582723
answer count: 1
score: -1
tagged with: import
favorite count: 0

http://stackoverflow.com/a/49833365
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49833237
type: Answer
has body: To avoid index out of range error you can follow this method: for itm in items: icon = itm.get('AssetStatusIcon', None) if icon: msg = "@everyone\n\n-----New Item!-----\n" + itm.get('AbsoluteUrl') print(msg) Note: Your existing json structure is invalid, you need to load it first with json.loads() and before that validate your json structure at jsonlint
accepted answer of: http://stackoverflow.com/q/49833237

bokeh
tags question: http://stackoverflow.com/q/49862782
tags question: http://stackoverflow.com/q/49759896
tags question: http://stackoverflow.com/q/49810470
tags question: http://stackoverflow.com/q/49828386
tags question: http://stackoverflow.com/q/49833824
tags question: http://stackoverflow.com/q/49769076
tags question: http://stackoverflow.com/q/49896792
type: Tag
tags question: http://stackoverflow.com/q/49895574
tags question: http://stackoverflow.com/q/49803577
tags question: http://stackoverflow.com/q/49868003
tags question: http://stackoverflow.com/q/49888938
tags question: http://stackoverflow.com/q/49916434
tags question: http://stackoverflow.com/q/49830196
tags question: http://stackoverflow.com/q/49853276
tags question: http://stackoverflow.com/q/49853567
tags question: http://stackoverflow.com/q/49876794
tags question: http://stackoverflow.com/q/49841626
tag name: bokeh
tags question: http://stackoverflow.com/q/49870786
tags question: http://stackoverflow.com/q/49823206
tags question: http://stackoverflow.com/q/49800444

http://stackoverflow.com/comment/137617490
type: AnswerComment
score: 0
type: Comment
has text: @JeffreyGoldberg Your answer is the correct answer. I'm using pyenv. The shim is not updated when I run `pip install --upgrade <package>` but when I run `python -m pip install --upgrade <package>` then it is updated.
comment on: http://stackoverflow.com/a/49868675

http://stackoverflow.com/a/49880861
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/49880743
type: Answer
answers question: http://stackoverflow.com/q/49880743
has body: You can use the format method in builtin strings, and zip_longest. from itertools import zip_longest ... # Assuming fruit is file_context.readlines() fruits = fruit.split("\n") vegs = veg.split("\n") for l1,l2 in zip_longest(fruits, vegs, fillvalue=""): print("{}\t{}".format(l1, l2)) zip_longest will take care of the situation where you have unequal number of fruits and vegs. NOTE: The above will work in python 3. For python 2, remember to replace: from itertools import zip_longest with: from itertools import izip_longest
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49896597
has title: reading txt file with multiple delimeters
has answer: http://stackoverflow.com/a/49896671
has answer: http://stackoverflow.com/a/49897594
has answer: http://stackoverflow.com/a/49896923
has body: I have a txt file with seven columns and no headers. There is a space separating the first two columns and then semicolons serve as the delimiter thereafter. Here is what I tried before realizing the file wasn't uniform: min17_q1 = open('ES 03-17.Last.txt', 'r') for line in min17_q1: fields = line.split(";") Date = fields[0] Time = fields[1] Open = fields[2] High = fields[3] Low = fields[4] Close = fields[5] Volume = fields[6] print(DateTime + Open + High + Low + Close + Volume) How can I read this file in and then be able to manipulate the data and/or append identical files to this one?
type: Question
answer count: 3
tagged with: python
possible better answer: http://stackoverflow.com/a/49896923
tagged with: append
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49896671
score: 0

http://stackoverflow.com/comment/132633882
type: QuestionComment
has text: `print(cars.columns)` to check for whitespace in column names
type: Comment
comment on: http://stackoverflow.com/q/49815001
score: 0

http://stackoverflow.com/comment/86653066
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49818553
has text: Could you share the directory structure of your project, including where the relevant files are?

http://stackoverflow.com/comment/86764181
type: Comment
type: QuestionComment
has text: Possible duplicate of [this question](https://stackoverflow.com/q/11696472/6632342). Please refer [this](https://docs.python.org/3/tutorial/inputoutput.html) as well.
score: 2
comment on: http://stackoverflow.com/q/49874349

http://stackoverflow.com/a/49813931
answers question: http://stackoverflow.com/q/49813265
has body: import requests import sqlite3 con = sqlite3.connect("COINS.db") cur = con.cursor() cur.execute('DROP TABLE IF EXISTS COINS') cur.execute( "CREATE TABLE COINS (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENTUNIQUE, symbol TEXT, description TEXT);") r = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json') to_db = r.json() des=to_db['bpi']['USD']['description'] code=to_db['bpi']['USD']['code'] cur.execute("INSERT INTO COINS (symbol, description) VALUES (?, ?);", (des,code)) con.commit() con.close() Check full code
score: 0
accepted answer of: http://stackoverflow.com/q/49813265
type: Answer
has comment: http://stackoverflow.com/comment/86642602
has comment: http://stackoverflow.com/comment/86645020
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86643408

http://stackoverflow.com/q/49895682
downvote count: 5
type: UnansweredQuestion
has title: Python date formatting
has answer: http://stackoverflow.com/a/49895762
tagged with: python
has comment: http://stackoverflow.com/comment/86806737
tagged with: date
has comment: http://stackoverflow.com/comment/86806880
upvote count: 0
has body: How would I get a function to take the date in terms of YYYY-MM-DD, YYYY/MM/DD and DD.MM.YYYY and return YYYY-MM-DD? I’ve tried a few ways which would work for one of the formats but then not the other
score: -5
answer count: 2
has answer: http://stackoverflow.com/a/49895770
linked to: http://stackoverflow.com/q/311627
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86829215

http://stackoverflow.com/comment/86562683
has text: I have not found a best way to actually share data on Stack Overflow
comment on: http://stackoverflow.com/q/49772495
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49911945
has comment: http://stackoverflow.com/comment/86839805
downvote count: 1
has title: Quick method to enumerate two big arrays?
favorite count: 0
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/49912465
tagged with: enumerate
tagged with: performance
has answer: http://stackoverflow.com/a/49912465
upvote count: 2
has body: I have two big arrays to work on. But let's take a look on the following simplified example to get the idea: I would like to find if an element in data1 is matched to an element in data2 and return the array index in both data1 and data2 if a match is found in form of a new array [index of data1, index of data2]. For example, with the below set of data1 and data2, the program will return: data1 = [[1,1],[2,5],[623,781]] data2 = [[1,1], [161,74],[357,17],[1,1]] expected_output = [[0,0],[0,3]] My current code is as follow: result = [] for index, item in enumerate(data1): for index2,item2 in enumerate(data2): if np.array_equal(item,item2): result.append([index,index2]) &gt;&gt;&gt; result [[0, 0], [0, 3]] This works fine. However, the actual two arrays that I am working on has 0.6 million items each. The above code would be extremely slow. Is there any method to speed up the process?
has answer: http://stackoverflow.com/a/49912426
tagged with: python
has comment: http://stackoverflow.com/comment/86839881
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86840147
answer count: 3
accepted answer: http://stackoverflow.com/a/49912284
has comment: http://stackoverflow.com/comment/86840311
score: 1
has answer: http://stackoverflow.com/a/49912284
has comment: http://stackoverflow.com/comment/86840312

http://stackoverflow.com/q/49769496
tagged with: python
tagged with: image
score: 0
has comment: http://stackoverflow.com/comment/86648511
answer count: 0
has title: Combining multiple datasets with different shapes from differen hdf5 files into one single hdf5 file
tagged with: hdf5
has body: I am working with 2D medical images in python stored in multiple hdf5 files with different shapes (e. g. [30,99,761,761], [20,30,99,761,761] and ..) and I want to combine all of them into a 3-dimensional array into a single hdf5 file (with shape [n,761,761]). At the moment I am doing this by reading each image [761,761] from each dataset of each hdf5 file and then writing the image into one single file. This process takes more than 24 hours since there are around 40000 images and I assume this the least optimized solution. Is there a faster way to selectively slice and copy data from an hdf5 files into another one? Here is the code. first creates the File that I want to combine the images from other files into: ip_augmented_shape = (((num_rotations)*(1+3+num_translations)*len(addrs)),img.shape[0],img.shape[1]) ip_augmented = h5py.File(ip_augmented_path, mode='w') ip_augmented.create_dataset("data1", ip_augmented_shape,np.int32) ip_augmented.create_dataset("Index1",(ip_augmented_shape[0],num_classes), np.float32) ip["Index1"][...] = labels print("Creating the data set \n") counter = 0 pbar = tqdm(total=ip_augmented_shape[0]) And now reading images one by one from each file and writing it to the target file. There is always a index for each image that get copied as well. for i in range(ip_rotated_flipped_h_shape[0]): for j in range(ip_rotated_flipped_h_shape[1]): ip_augmented['data1'][counter] = ip_rotated_flipped_h['images'][i][j] ip_augmented['Index1'][counter]= ip_rotated_flipped_h['Index1'][i][j] counter = counter+1 pbar.update(1) for i in range(ip_rotated_flipped_h_shape[0]): for j in range(ip_rotated_flipped_h_shape[1]): ip_augmented['data1'][counter] = ip_rotated_flipped_h['images'][i][j] ip_augmented['Index1'][counter]= ip_rotated_flipped_h['Index1'][i][j] counter = counter+1 pbar.update(1) for i in range(ip_rotated_flipped_v1_shape[0]): for j in range(ip_rotated_flipped_v1_shape[1]): ip_augmented['data1'][counter] = ip_rotated_flipped_v1['images'][i][j] ip_au…
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86637748

http://stackoverflow.com/comment/86663948
has text: That works perfectly! Thanks a million!
comment on: http://stackoverflow.com/q/49813012
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86590874
score: 0
type: Comment
type: QuestionComment
has text: Okay. Then how python differentiate or maintain reference count for Small and bigger objects.
comment on: http://stackoverflow.com/q/49787869

http://stackoverflow.com/q/49808547
tagged with: debian
upvote count: 1
tagged with: pypi
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86632464
tagged with: pip
has comment: http://stackoverflow.com/comment/86648914
tagged with: python
answer count: 0
has title: Python package installed as non root user return command not found when ran using sudo
score: 1
has body: I'm studying how to create Python packages and I'm facing a problem. I have a bash script to create Apache virtual hosts and I decided to rewrite it using Python. So far so good. I used to run my bash script like this $ sudo vhost myvhost.localhost myuser And I want to do the same with the Python version. I installed the package using pip as non root user and everything goes fine. When I try to run it, I got a command not found. I had the same problem with my bash scripts, I store them in $USER/bin so I added this directory to secure_path in /etc/sudoers and problem solved. Currently, I'm installing my package as root $ su - $ pip3 install vhost And then I can run the command as non root without the command not found message. The question is: How is the Python way of solving this issue? You can see my code here https://github.com/felipebool/vhost and I'm developing in a Debian machine. Thanks
downvote count: 0

http://stackoverflow.com/q/49896377
downvote count: 0
tagged with: scipy
has title: Python fsolve tempering with object
favorite count: 0
type: Question
tagged with: python
has body: I wrote a script in Python that finds the zero of a fairly complicated function using fsolve. The way it works is as follows. There is a class that simply stores the parameter of the function. The class has an evaluate method that returns a value based on the stored parameter and another method (inversion) that finds the parameter at which the function takes the supplied output. The inversion method updates the parameter of the function at each iteration and it keeps on doing so until the mismatch between the value returned by the evaluate method and the supplied value is zero. The issue that I am having is that while the value returned by the inversion method is correct, the parameter, that is part of the object, is always 0 after the inversion method terminates. Oddly enough, this issue disappears if I use root instead of fsolve. As far as I know, fsolve is just a wrapper for root with some settings on the solver algorithm and some other things enforced. Is this a known problem with fsolve or am I doing something dumb here? The script below demonstrates the issue I am having on the sine function. from scipy.optimize import fsolve, root from math import sin, pi class invertSin(object): def __init__(self,x): self.x = x def evaluate(self): return sin(self.x) def arcsin_fsolve(self,y): def errorfunc(xnew): self.x = xnew return self.evaluate() - y soln = fsolve(errorfunc, 0.1) return soln def arcsin_root(self,y): def errorfunc(xnew): self.x = xnew return self.evaluate() - y soln = root(errorfunc, 0.1, method = 'anderson') return soln myobject = invertSin(pi/2) x0 = myobject.arcsin_fsolve(0.5) #find x s.t. sin(x) = 0.5 using fsolve print(x0) #this prints pi/6 x0obj = myobject.x print(x0obj) #this always prints 0 no matter which function I invert myobject2 = invertSin(pi/2) x1 = myobject2.arcsin_root(0.5) #find x s.t. sin(x) = 0.5 using root print(x1) #this prints pi/6 x1obj = myobject2.x print(x1obj) #this prints pi/6
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49902401
upvote count: 2
tagged with: numerical-methods
has answer: http://stackoverflow.com/a/49902401
answer count: 1

http://stackoverflow.com/a/49763477
has body: This is a natural consequence of running a task in the background. See the bash reference: If a command is terminated by the control operator ‘&amp;’, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background. The shell does not wait for the command to finish, and the return status is 0 (true). When job control is not active (see Job Control), the standard input for asynchronous commands, in the absence of any explicit redirections, is redirected from /dev/null. Your answer is likely to redirect the information you want from somewhere else. The simplest way is to write a file with the input you want for each function: $ cat abcd &gt; first $ cat "Hello, this is a file" &gt; second $ python x.py &lt; first &amp; python x.py &lt; second
answers question: http://stackoverflow.com/q/49762048
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/86809966
type: AnswerComment
has text: Ok.But I want to print the csv data on UI.But It prints nothing
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49896779

http://stackoverflow.com/a/49815454
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49813234
answers question: http://stackoverflow.com/q/49813234
has body: The PolyCollection created by fill_between does not use any offset. It is simply a Collection of Paths in data coordinates. Three possible ways to update the "position" of the PolyCollection that is created via fill_between: Setting offset_position In case you want to set an offset in data coordinates you need to tell it to apply this offset in data coordinates via area.set_offset_position("data") import numpy as np import matplotlib.pyplot as plt p=plt.figure() area=plt.gca().fill_between((0,4), 1, 2, facecolor='red', alpha=0.25) area.set_offsets(np.array([[1.1, 2.1]])) area.set_offset_position("data") plt.show() Change the path You may change the Path if you like: import numpy as np import matplotlib.pyplot as plt p=plt.figure() area=plt.gca().fill_between((0,4), 1, 2, facecolor='red', alpha=0.25) offset = np.array([1.1, 2.1]) area.get_paths()[0].vertices += offset plt.gca().dataLim.update_from_data_xy(area.get_paths()[0].vertices) plt.gca().autoscale() plt.show() Change the transform import numpy as np import matplotlib.transforms import matplotlib.pyplot as plt p=plt.figure() area=plt.gca().fill_between((0,4), 1, 2, facecolor='red', alpha=0.25) offset = np.array([1.1, 2.1]) transoffset = matplotlib.transforms.Affine2D().translate(*offset) area.set_transform(transoffset + area.get_transform()) plt.show()
type: Answer

http://stackoverflow.com/a/49842655
score: 2
has comment: http://stackoverflow.com/comment/86700174
upvote count: 2
type: AcceptedAnswer
has body: re.search only returns the first match, as documented: Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. To find all the matches, use findall. Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. Here's an example from the shell: &gt;&gt;&gt; import re &gt;&gt;&gt; re.findall("&gt;(.*)\n", "&gt;test1\nxxx&gt;test2\nxxx") ['test1', 'test2'] Edit: I just read your question again and realised that you want "test1\ntest2" as output. Well, just join the list with \n: &gt;&gt;&gt; "\n".join(re.findall("&gt;(.*)\n", "&gt;test1\nxxx&gt;test2\nxxx")) 'test1\ntest2'
downvote count: 0
has comment: http://stackoverflow.com/comment/86699975
has comment: http://stackoverflow.com/comment/86699910
answers question: http://stackoverflow.com/q/49842536
type: Answer
has comment: http://stackoverflow.com/comment/86700002
accepted answer of: http://stackoverflow.com/q/49842536

http://stackoverflow.com/q/49871680
has comment: http://stackoverflow.com/comment/86758997
has answer: http://stackoverflow.com/a/49872188
possible better answer: http://stackoverflow.com/a/49871900
has answer: http://stackoverflow.com/a/49872964
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86759012
type: Question
has title: Unable to pass text to a text box
has comment: http://stackoverflow.com/comment/86759101
accepted answer: http://stackoverflow.com/a/49872280
tagged with: python
has answer: http://stackoverflow.com/a/49872280
has comment: http://stackoverflow.com/comment/86758618
has comment: http://stackoverflow.com/comment/86759179
has body: Follwing is the HTML code: Python selenium code: WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='field' and @id='search']"))).send_keys("12343545")
has answer: http://stackoverflow.com/a/49871900
has comment: http://stackoverflow.com/comment/86758535
has comment: http://stackoverflow.com/comment/86758699
has comment: http://stackoverflow.com/comment/86759186
answer count: 4
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86759389
tagged with: selenium
has comment: http://stackoverflow.com/comment/86758962
has comment: http://stackoverflow.com/comment/86759171
upvote count: 1
has comment: http://stackoverflow.com/comment/86759297

http://stackoverflow.com/a/49803962
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49803909
type: AcceptedAnswer
score: 4
answers question: http://stackoverflow.com/q/49803909
has body: This means that all data are returned as bytes objects, not str. Use b'some_pattern' instead of 'some_pattern'
downvote count: 0
type: Answer

http://stackoverflow.com/a/49914257
score: 0
answers question: http://stackoverflow.com/q/49913806
type: Answer
has body: If you want to delete particular element whose index is unknown from the list use remove(element) and if you want to delete element at particular index use del(list[index]).

http://stackoverflow.com/comment/86741788
has text: The problem is likely to be in the code you have not shown. And that is a [different question](https://stackoverflow.com/questions/ask).
comment on: http://stackoverflow.com/a/49828549
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49765676
type: UnansweredQuestion
has title: Matching dates in CSV file to get index
has comment: http://stackoverflow.com/comment/86546979
tagged with: python
has comment: http://stackoverflow.com/comment/86546932
has body: I have a CSV file with date, time, Positive and Negative columns. There are duplication of dates such as row 4 and 5 with different positive and negative value. I wanted to match the user input date with the dates in the csv file and return the index of the date in order for me to get the different positive and negative values. However, I tried to for loops but it always return me the first index of the date. The CSV file look like this: Date Pos Neg 20180402 1 0 20180402 0 1 20180401 0 1 20180402 1 0 for i in range(len(combine_list)): xdate = combine_list[i][0] print(xdate) if user_date3 ==xdate: print("yes") count_price +=1 index1 = date_list.index(xdate) print(index1) #index1.append(index1) Sorry if the code if messy as I just started to learn how to code. Any help is appreciated. Thanks! :)
score: 0
has answer: http://stackoverflow.com/a/49765783
has answer: http://stackoverflow.com/a/49765784
has comment: http://stackoverflow.com/comment/86547049
type: Question
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/86547616

http://stackoverflow.com/a/49804197
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49787648
answers question: http://stackoverflow.com/q/49787648
score: 3
has body: The docs say: importlib.import_module(name, package=None) ... Changed in version 3.3: Parent packages are automatically imported. Therefore, the 3.6.4 behaviour is correct and the 3.5.2 behaviour is buggy. You seem to be hitting #30876, and the issue says that was fixed in the version 5 micro i.e. v3.5.5. Credit to vaultah in room 6 for finding the ticket.
type: Answer
upvote count: 3
downvote count: 0

long-running-processes
tags question: http://stackoverflow.com/q/49913211
tag name: long-running-processes
type: Tag

http://stackoverflow.com/q/49823859
tagged with: python
has comment: http://stackoverflow.com/comment/86663672
tagged with: import
tagged with: python-3.x
tagged with: python-import
linked to: http://stackoverflow.com/q/5626193
answer count: 0
has comment: http://stackoverflow.com/comment/86664526
has comment: http://stackoverflow.com/comment/86663633
upvote count: 3
type: UnansweredQuestion
has body: I need to modify one line of an extremely nested python file in an imported library. I needed to handle 1 error exception not covered by the library, so I made a class that inherits the error throwing class (and adds a try/except block). Now I just need to swap my new class for the old one, but I'm sure its terrible pythonic form to actually modify an imported library source code.
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86664451
score: 3
has title: How to modify a few lines of Imported Python Library without editing the Library file?

http://stackoverflow.com/comment/107747033
type: AnswerComment
has text: It is ``pyserial`` on PyPi, not ``serial``.
type: Comment
comment on: http://stackoverflow.com/a/49918007
score: 3

http://stackoverflow.com/comment/86719582
has text: what i have to pass instead of seen parameters?
score: 0
comment on: http://stackoverflow.com/a/49852437
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49846799
type: Answer
accepted answer of: http://stackoverflow.com/q/49846769
has body: You can use advanced indexing which basically means extract the row and column indices from the index array and then use it to extract values from a, i.e. a[index[:,0], index[:,1]] - %timeit a[index[:,0], index[:,1]] # 12.1 µs ± 368 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit [a[i, j] for [i, j] in index] # 2.22 ms ± 105 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
score: 2
answers question: http://stackoverflow.com/q/49846769
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86781766
comment on: http://stackoverflow.com/a/49882888
score: 0
type: AnswerComment
has text: No, function calls are not pass by reference. If they were, assignment to variables passed in would be seen by the caller.
type: Comment

http://stackoverflow.com/comment/86871114
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49910624
has text: Clarification: you might be _observing_ that a cron job executes in Cloud Shell after you log out, but that won't happen for long because the VM is reclaimed after a period inactivity. I suspect the reason your cron job stops working immediately after you log out is that your credentials for bq are propagated into Cloud Shell from the web browser terminal, and once you log it cannot happen. You need to provide credentials to bq in a different way. Check out the various credential_file options in https://cloud.google.com/bigquery/docs/reference/bq-cli-reference.

http://stackoverflow.com/q/49800077
answer count: 0
tagged with: http://stackoverflow.com/tag/pdf
has comment: http://stackoverflow.com/comment/86633340
type: Question
has comment: http://stackoverflow.com/comment/86615595
tagged with: pdf2htmlex
has body: I have installed pdfminer and when I am trying to run pdf2txt.py test.pdf -t html -o test.html no error showing and command also not executing in windows. Please help me how can i convert true pdf files in html file. Thanks.
has title: pdfminer when I am trying to run pdf2txt.py not working in windows
type: UnansweredQuestion
tagged with: pdfminer
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/86615465
score: 0

http://stackoverflow.com/comment/86552446
score: 0
has text: Thanks for the suggestions. Why do I need to add another top node? In any case, even when I do that I get only output of the header rows into the csv, not the data. I will have a look at xslt also.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49762550

http://stackoverflow.com/q/49784795
has comment: http://stackoverflow.com/comment/86589323
has answer: http://stackoverflow.com/a/49796443
has title: Check if string matches dynamic regexp and find variables
score: 0
has body: In django web app, user may define urls with dynamic parameters, for example: /users/:id or /posts/:postid/:commentid now, I have given strings, for example: /users/mysername &lt;- it matches /users/:id - how can I exstract "myusername" from it? /users/mysuername/something &lt;- doesn't match /posts/10/382 - match, extract two variables - postid and commentid my models.py: class Server(BaseModel): url = models.CharField(verbose_name=_('URL'), max_length=64) in my view, I want to compare request's PATH_INFO: endpoint_url = request.META.get('PATH_INFO').lower().strip().lstrip('/') lets say I have a Server model instance with url: /users/:someid now, when request path is: /users/somestring0 I want to match it and extract variable someid to be "somestring0". Parmeters may contain anything - except slash (/) probably. How can I achieve something like that?
has comment: http://stackoverflow.com/comment/86591149
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: django
tagged with: python
type: UnansweredQuestion
tagged with: regex

http://stackoverflow.com/comment/86591594
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49788197
has text: Just a remark: in python you do not (usually) need to do `for i in range(len(thing))`. Most `things` support [iteration protocol](https://docs.python.org/3/library/stdtypes.html#iterator-types) so you can just do `for i in thing`.
type: Comment

http://stackoverflow.com/comment/86559522
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49772156
has text: I think you are over complicating by using re; I'm busy, will post answer in a while if no one else does :)
score: 0

http://stackoverflow.com/comment/86918649
score: 1
has text: Een keer samen zitten is natuurlijk altijd mogelijk! Mocht het qua afstand niet uitkomen is een discord/skype gesprek natuurlijk een goed alternatief! Laat maar iets weten dan stuur ik je mijn gegevens!
comment on: http://stackoverflow.com/a/49888389
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49865057
has comment: http://stackoverflow.com/comment/86766219
score: 0
has comment: http://stackoverflow.com/comment/86755383
tagged with: math
tagged with: integral
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86755451
has comment: http://stackoverflow.com/comment/86745823
has comment: http://stackoverflow.com/comment/86766166
has body: I would like to compute the integral of discrete signal segment Y (Y=[y1,y2,...y50]) and X is the following datetime64[ns] object: x=['2018-01-24T13:41:25.057000000' '2018-01-24T13:41:25.069000000' '2018-01-24T13:41:25.077000000' '2018-01-24T13:41:25.090000000' '2018-01-24T13:41:25.097000000' '2018-01-24T13:41:25.111000000' '2018-01-24T13:41:25.117000000' '2018-01-24T13:41:25.130000000' '2018-01-24T13:41:25.138000000' '2018-01-24T13:41:25.150000000' '2018-01-24T13:41:25.158000000' '2018-01-24T13:41:25.170000000' '2018-01-24T13:41:25.178000000' '2018-01-24T13:41:25.199000000' '2018-01-24T13:41:25.200000000' '2018-01-24T13:41:25.211000000' '2018-01-24T13:41:25.218000000' '2018-01-24T13:41:25.231000000' '2018-01-24T13:41:25.238000000' '2018-01-24T13:41:25.250000000' '2018-01-24T13:41:25.258000000' '2018-01-24T13:41:25.269000000' '2018-01-24T13:41:25.278000000' '2018-01-24T13:41:25.290000000' '2018-01-24T13:41:25.298000000' '2018-01-24T13:41:25.311000000' '2018-01-24T13:41:25.317000000' '2018-01-24T13:41:25.331000000' '2018-01-24T13:41:25.338000000' '2018-01-24T13:41:25.350000000' '2018-01-24T13:41:25.358000000' '2018-01-24T13:41:25.370000000' '2018-01-24T13:41:25.378000000' '2018-01-24T13:41:25.390000000' '2018-01-24T13:41:25.398000000' '2018-01-24T13:41:25.411000000' '2018-01-24T13:41:25.418000000' '2018-01-24T13:41:25.430000000' '2018-01-24T13:41:25.437000000' '2018-01-24T13:41:25.450000000' '2018-01-24T13:41:25.469000000' '2018-01-24T13:41:25.469000000' '2018-01-24T13:41:25.479000000' '2018-01-24T13:41:25.493000000' '2018-01-24T13:41:25.502000000' '2018-01-24T13:41:25.510000000' '2018-01-24T13:41:25.517000000' '2018-01-24T13:41:25.530000000' '2018-01-24T13:41:25.537000000' '2018-01-24T13:41:25.550000000'] My attempt is using the following python code: Case A, with the above x: f_x_tot_acc = Y x_n = x[-1] x_0 = x[0] h = (x_n - x_0) / (len(f_x_tot_acc) - 1) print('trapz [' + str(integrate.trapz(f_x_tot_acc, dx=h)) + ']') The Result is: trapz [6203255447 nanoseconds] C…
has comment: http://stackoverflow.com/comment/86745762
has title: how to calculate the integral with temporal data?
answer count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/q/49829322
tagged with: python
type: AnsweredQuestion
score: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/86675394
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/86674876
has comment: http://stackoverflow.com/comment/86674020
linked to: http://stackoverflow.com/q/517355
favorite count: 0
accepted answer: http://stackoverflow.com/a/49830027
type: Question
has title: How to add strings here
has answer: http://stackoverflow.com/a/49830027
has comment: http://stackoverflow.com/comment/86675074
has body: I have values stored in variables which i am trying to append in payload but it's not taking,please let me know how to do it r=(issues["fields"]["resolution"]["name"]) #print (r) p=(issues["fields"]["customfield_13709"]) #print (p) s=(issues["fields"]["summary"]) #print(s) k=(issues["key"]) #print(k) a=(issues["fields"]["assignee"]["name"]) #print (a) payload = "{\r\n\t\"fields\":{\r\n\"project\":{\"key\":\"SSETOPS\"},\r\n\"summary\":\"s\",\r\n\"description\":\"k+s\",\r\n\"issuetype\":{\"name\":\"Task\"},\r\n\"customfield_12610\":{\"value\":\"High\"},\r\n\"components\":[{\"name\":\"Other\"}],\r\n\"assignee\":{\"name\":\"rahsingh\"}\r\n}}"

http://stackoverflow.com/q/49908588
possible better answer: http://stackoverflow.com/a/49929692
score: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49925028
answer count: 2
has title: Trainable, Multi-Parameter Activ. Function (RBF) NeuPy / Theano
has body: How do I implement a custom activation function (RBF kernel with mean and variances adjusted by gradient descent) in Neupy or Theano for use in Neupy. {Quick Background: Gradient Descent works with every parameter in the network. I want to make a specialized features space that contains optimized feature parameters so Neupy} I think my problems is in the creation of parameters, how they are sized, and how they are all connected. Primary functions of interest. Activation Function Class class RBF(layers.ActivationLayer): def initialize(self): super(RBF, self).initialize() self.add_parameter(name='mean', shape=(1,), value=init.Normal(), trainable=True) self.add_parameter(name='std_dev', shape=(1,), value=init.Normal(), trainable=True) def output(self, input_value): return rbf(input_value, self.parameters) RBF Function def rbf(input_value, parameters): K = _outer_substract(input_value, parameters['mean']) return np.exp(- np.linalg.norm(K)/parameters['std_dev']) Function to shape? def _outer_substract(x, y): return (x - y.T).T Help will be much appreciated as this is will provide great insight into how to customize neupy networks. The documentation could use some work in some areas to say the least...
has answer: http://stackoverflow.com/a/49925028
downvote count: 0
has answer: http://stackoverflow.com/a/49929692
tagged with: machine-learning
upvote count: 1
tagged with: neupy
favorite count: 0
type: Question
tagged with: theano

logstash
tags question: http://stackoverflow.com/q/49883563
tag name: logstash
type: Tag

http://stackoverflow.com/q/49834632
type: Question
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/86688899
favorite count: 0
score: 2
has body: My goal here is to attach my top layers to a pre-trained model like VGG19 and make some prediction using the merged model. The merged model has 0 accuracy. Need a bit of help. my own top layers from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D from keras.layers import Dropout, Flatten, Dense from keras.models import Sequential vgg19top_model = Sequential() vgg19top_model.add(GlobalAveragePooling2D(input_shape=train_vgg19.shape[1:])) # shape=(7, 7, 512) vgg19top_model.add(Dense(255, activation='relu')) vgg19top_model.add(Dropout(0.35)) vgg19top_model.add(Dense(133, activation='softmax')) vgg19top_model.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= global_average_pooling2d_1 ( (None, 512) 0 _________________________________________________________________ dense_1 (Dense) (None, 255) 130815 _________________________________________________________________ dropout_1 (Dropout) (None, 255) 0 _________________________________________________________________ dense_2 (Dense) (None, 133) 34048 ================================================================= Total params: 164,863 Trainable params: 164,863 Non-trainable params: 0 trained my top model on bottleneck features and got 72% accuracy reloading those weights here code not shown load VGG19 bottom layers to merge with my top layers from keras import applications vgg19=applications.vgg19.VGG19(include_top=False, weights='imagenet',input_shape=(224, 224, 3)) vgg19.summary() Layer (type) Output Shape Param # ================================================================= input_3 (InputLayer) (None, 224, 224, 3) 0 _________________________________________________________________ ... ... _________________________________________________________________ block5_conv4 (Conv2D) (None, 14, 14, 512) 2359808 _________________________________________________________________ block5_po…
has comment: http://stackoverflow.com/comment/86696710
tagged with: deep-learning
has title: Transfer Learning - Merging my top layers with pretrained model drops accuracy to 0%
has answer: http://stackoverflow.com/a/65366678
answer count: 1
tagged with: python
tagged with: transfer-learning
tagged with: tensorflow

http://stackoverflow.com/comment/86596424
comment on: http://stackoverflow.com/a/49780950
score: 0
type: Comment
has text: `[...] File "xxx\dbf\ver_2.py", line 5404, in new return Table(filename, field_specs, memo_size, ignore_memos, codepage, default_data_types, field_data_types, dbf_type=self._versionabbr, on_disk=on_disk) File "xxx\dbf\ver_2.py", line 4785, in __init__ self.add_fields(field_specs) File "xxx\dbf\ver_2.py", line 5057, in add_fields length, decimals, flags = init(pieces, flags) File "xxx\dbf\ver_2.py", line 3898, in add_vfp_double decimals = int(format[0][1:-1]) if len(format) else 0 ValueError: invalid literal for int() with base 10: 'inar'`
type: AnswerComment

http://stackoverflow.com/comment/86625472
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49804654
has text: Try setting `export MACOSX_DEPLOYMENT_TARGET=10.7` environment variable before compiling.
type: Comment

http://stackoverflow.com/comment/86684787
has text: What is input_img exactly? Can you show its definition?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49834380

http://stackoverflow.com/comment/86824100
type: Comment
has text: Sorry I missed adding what I tried and have the same detailed below in Excel - Step 1 : Split each row with OR as the delimiter. So now I have each row with one column containing key followed by a blank column. Step 2 : on the blank column next to the key column copy pasted the Vlookup to lookup the key in the other table Step 3: Copy pasted around 2k times got exhausted. Is there a better way to do this?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49880971

http://stackoverflow.com/a/49801075
answers question: http://stackoverflow.com/q/49800452
has comment: http://stackoverflow.com/comment/86618239
type: Answer
accepted answer of: http://stackoverflow.com/q/49800452
score: 2
downvote count: 0
has body: TLDR; The issue of the above is related to the invocation of suprocess.check_output, with parameter shell=True, you should use string instead of a list of arguments Here are some details. UPDATE: I assume that the reason is that it's not invoked in the same shell session, so it didn't find an agent. Depending on what you're trying to achieve, you should either use the same session (for example as in this case) or use a python library like PyBluez to control the Bluetooth devices (which I would recommend)
type: AcceptedAnswer
upvote count: 2

http://stackoverflow.com/a/49810198
type: Answer
has comment: http://stackoverflow.com/comment/86636040
has comment: http://stackoverflow.com/comment/86636668
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86638300
upvote count: 1
has body: Add your variables as class variables in __init__, that way it will be accessible in other methods of class - import os import Tkinter as tk import ttk import sys class main_window(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title('Pilot Flight and Duty Tracker') self.geometry('1000x700+250+50') self.resizable(width = False, height = False) self._frame = None Login_Window = Login(self) Users = [('Admin','AdminPassword')] def switch_frame(self, frame_name): new_frame = frame_name(self) if self._frame is not None: self._frame.destroy() self._frame = new_frame self._frame.pack() class Login(tk.Toplevel): def __init__(self, master, *args, **kwargs): tk.Toplevel.__init__(self, master, *args, **kwargs) self.title('User Login') self.resizable(width = False, height = False) self.attributes('-topmost', True) self.geometry('230x200+625+275') self.title('User Login') self.grab_set() self.transient(master) userlabel = tk.Label(self, text="Employee ID:", font='arial 10 bold') userlabel.place(x=25, y=5) self.user_entry = tk.Entry(self, relief='groove', width=25, font='arial 10', bd=1) self.user_entry.place(x=25, y=30) passwordlabel = tk.Label(self, text="Password:", font='arial 10 bold') passwordlabel.place(x=25, y=70) self.password_entry = tk.Entry(self, relief='groove', width=25, font='arial 10', show="*", bd=1) self.password_entry.place(x=25, y=95) self.warn = tk.Label(self, font='arial 10 bold') self.warn.place(x=25, y=135) button = tk.Button(self, text="Login", relief='groove', width=12, font='arial 15 bold', justify='center', command=self.login) button.place(x=37, y=140) def login(self): self.username = self.user_entry.get() self.pw = self.password_entry.get() if (self.username, self.pw) in Users: if (self.username, self.pw) == ('Admin', 'AdminPassword'): '''LOAD FIRST TIME ADMIN LOGON???????''' self.destroy() else: '''LOAD NORMAL USER or NORMAL ADMIN WINDOW''' else: self.warn.config(text="Invalid Username or Password", fg="black"…
answers question: http://stackoverflow.com/q/49809264

http://stackoverflow.com/comment/86605791
type: QuestionComment
type: Comment
has text: Possible duplicate of [How to delete a file or folder?](https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder)
score: 3
comment on: http://stackoverflow.com/q/49795746

http://stackoverflow.com/comment/86657697
comment on: http://stackoverflow.com/q/49818688
type: Comment
score: 0
has text: On the error page there is a button to a copy-pastable version. Not much we can do with an image of a small subset of the screen.
type: QuestionComment

http://stackoverflow.com/comment/86597118
has text: Again I completely agree. Feel free to provide your own answer. I just fixed up the mistakes that was preventing the code from running so OP knows why it was failing.
comment on: http://stackoverflow.com/a/49786843
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86609577
comment on: http://stackoverflow.com/q/49797115
type: Comment
type: QuestionComment
has text: Does this also happen in a clean virtualenv?
score: 0

http://stackoverflow.com/comment/86664816
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49824349
has text: That's fair. I think then you should take @toheedNiaz's answer :)

http://stackoverflow.com/q/49758858
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/49753980
score: 1
possible better answer: http://stackoverflow.com/a/49758966
tagged with: loops
has answer: http://stackoverflow.com/a/49758966
has title: Python: How to fill an array with x repeated n times?
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
linked to: http://stackoverflow.com/q/49753980
tagged with: arrays
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49759060
has answer: http://stackoverflow.com/a/49759060
has body: I try do generate a series of x and repeat it n times: import numpy as np ​ x = [1,2,3,4] n = [1,2,3,4] ​ data = [] ​ for i,j in zip(x, n): data.append(np.repeat(i,j)) print(data) Out: [array([1]), array([2, 2]), array([3, 3, 3]), array([4, 4, 4, 4])] I want a "clean" array like: array([1,2,2,3,3,3,4,4,4,4]) Thanks a lot if someone could point me to a solution!

http://stackoverflow.com/a/49781843
has body: The first thing I would say is that it's somewhat of an antipattern to duplicate the storage of data in two places, since it violates the DRY principle of software development. Generally, with GUI designs like this, there's the concept of MVC, or Model, View, Controller. It's a pretty large topic, but the general idea is that you create a model object to store all your data, and then all the other parts of the GUI -- the many Views that display the data, and the Controllers that change the data -- all look at the model, so that the data is only stored and updated in one place. GUI elements are either designed to accept a model and refreshes are either manually triggered or there is some type of Listen/Callback/Event system to automatically trigger refreshes on the Views when the model changes. The specific way to handle that depends on the GUI framework you are using. One simple way to implement this would be to create a model class that both classes share and use python properties and a callback registry to trigger updates. class Model(): def __init__(self, text): self._text = text self._callbacks = [] def on_text_changed(callback): self._callbacks.append(callback) @property def text(self): return self._text @text.setter def text(self, value): self._text = text for callback in self._callbacks: callback() Then both other classes would need something like this class Label(): def __init__(self, model): self.model = model self.model.on_text_changed(self.refresh) def refresh(self): print(self.text) @property def text(self): return self.model.text @text.setter def text(self, value): self.model.text = value Then you would create them like this model = Model('The text') label = Label(model) another_class = AnotherClass(model) label.text = 'This will update text on all classes' another_class.text = 'So will this' model.text = "And so will this.
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/86579565
downvote count: 0
answers question: http://stackoverflow.com/q/49781422

http://stackoverflow.com/comment/86580013
comment on: http://stackoverflow.com/q/49782120
has text: The logistic function, which returns the probability of success, is given by `p(x) = 1/(1 + exp(-(B0 + B1X1 + ... BnXn))`. `B0` is in intercept. `B1` through `Bn` are the coefficients. `X1` through `Xn` are the features. Read the wiki page linked for a more rigorous explanation.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/86762193
comment on: http://stackoverflow.com/q/49852061
type: Comment
has text: Thanks, Daniel, I added github link in the description and again I am adding here also https://github.com/ternaus/kaggle_dstl_submission/blob/master/src/make_prediction_cropped_buildings.py
type: QuestionComment
score: 0

http://stackoverflow.com/comment/97498776
has text: It works, but it has a bug: It also fires every hour and dumps the entire database even when there is no change. causes the cost to go up when your database is big.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/53020497
score: 0

lxml
tags question: http://stackoverflow.com/q/49879722
tags question: http://stackoverflow.com/q/49808607
tags question: http://stackoverflow.com/q/49825610
tags question: http://stackoverflow.com/q/49880545
type: Tag
tags question: http://stackoverflow.com/q/49794765
tags question: http://stackoverflow.com/q/49896812
tags question: http://stackoverflow.com/q/49910982
tag name: lxml
tags question: http://stackoverflow.com/q/49805914
tags question: http://stackoverflow.com/q/49897682
tags question: http://stackoverflow.com/q/49800438

http://stackoverflow.com/a/49882701
has comment: http://stackoverflow.com/comment/86790978
has comment: http://stackoverflow.com/comment/86781866
score: 1
answers question: http://stackoverflow.com/q/49882469
downvote count: 0
type: Answer
upvote count: 1
has body: You don't need a cycle for that. Your function can work with numpy arrays as well as single values: def f(x,y): return np.sin(x + y) / np.sqrt(x**2 + y**2) x = [0.1, 0.2, 0.3, 0.4, 0.5] y = [0.1, 0.2, 0.3, 0.4, 0.5] print(f(x, y)) will return: [1.40480431, 1.37680175, 1.33087507, 1.26811839, 1.19001968] which is an array of function values for each pair of x and y
has comment: http://stackoverflow.com/comment/86781442

http://stackoverflow.com/q/49906370
type: Question
accepted answer: http://stackoverflow.com/a/49947596
type: AnsweredQuestion
score: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49947596
downvote count: 0
tagged with: widget
upvote count: 1
answer count: 1
has body: I want to display information from RowInstance. The following code snippets display most attributes. # type(line) is Orange.data.table.RowInstance for i, cell in enumerate(line.values()): print(cell.value) However, "metadata values" are not accessible from the method values(). Only the feature values are returned. How can I access metadata from RowInstance?
tagged with: orange
has title: How to read meta properties from RowInstance in Orange?

http://stackoverflow.com/comment/86592077
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49788464
score: 0
has text: Possible duplicate of https://stackoverflow.com/q/2151517/6622817

http://stackoverflow.com/q/49904121
favorite count: 0
has comment: http://stackoverflow.com/comment/86824215
type: Question
score: 3
has answer: http://stackoverflow.com/a/49904207
has body: I want just the country and the value capitalized. This is my full code: cities = { 'rotterdam': { 'country': 'netherlands', 'population': 6000000, 'fact': 'is my home town', }, 'orlando': { 'country': 'united states', 'population': 150000000, 'fact': 'is big', }, 'berlin': { 'country': 'germany', 'population': 25000000, 'fact': 'once had a wall splitting west from east (or north from south)', }, } for city, extras in cities.items(): print("\nInfo about the city " + city.title() + ":") for key, value in extras.items(): try: if extras['country']: print(key.capitalize() + ": " + value.title()) else: print(key.capitalize() + ": " + value) except(TypeError, AttributeError): print(key.capitalize() + ": " + str(value)) From the output this part works, this is how i want it: Info about the city Rotterdam: Country: Netherlands But i also get this: Fact: Is My Home Town How can i prevent every word in the value of ['fact']from being capitalized and have just the keys and only the ['country'] value capitalized using .title()? so that i get: Info about the city Rotterdam: Country: Netherlands Population: 6000000 Fact: Is my home town Hope that i am clear.
tagged with: python
tagged with: dictionary
has title: Python dictionary inside a dictionary .title()
has comment: http://stackoverflow.com/comment/86824409
type: AnsweredQuestion
upvote count: 3
answer count: 2
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/49904207
downvote count: 0
tagged with: nested
has comment: http://stackoverflow.com/comment/86824184
has answer: http://stackoverflow.com/a/49904427
has comment: http://stackoverflow.com/comment/86824612
possible better answer: http://stackoverflow.com/a/49904427

http://stackoverflow.com/comment/86846084
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49868725
has text: Thanks Everybody~~ I found problem.. first, I changed "posts" in post_detail.html to "post". second, I changed path for 'like_action' from '<int:pk>/like_action/' to 'post/<int:pk>/like_action/'.
score: 0

collaborative-filtering
tags question: http://stackoverflow.com/q/49881566
type: Tag
tag name: collaborative-filtering

http://stackoverflow.com/q/49908705
has title: How to use SMOTE for sequential data
favorite count: 0
has body: I am training LSTM RNN on sequential data. I have imbalanced dataset of ~2000 classes. I would like to use the combination of oversampling/undersampling. I downsampled more represented classes and wanted to use python implementation of SMOTE to oversample minority classes. However, with RNN, my input is a list of vectors, not a single vector. I tried to use basic example of SMOTE for the task, generating error: ValueError: Found array with dim 3. Estimator expected &lt;= 2. Is there any way to use SMOTE in this way? This is my current code: all_vector_inputs = [vector_pair[0] for vector_pair in all_user_vectors] all_vector_targets = [vector_pair[1] for vector_pair in all_user_vectors] inputs_res, targets_res = SMOTE(kind='svm').fit_sample( all_vector_inputs, all_vector_targets ) Any SMOTE substitution suggestions in Python welcome as well.
type: Question
score: 3
tagged with: python
type: UnansweredQuestion
tagged with: recurrent-neural-network
has comment: http://stackoverflow.com/comment/102342555
upvote count: 3
downvote count: 0
answer count: 0
tagged with: machine-learning

http://stackoverflow.com/comment/86674829
comment on: http://stackoverflow.com/a/49829440
has text: Actually, for this question, the code won't get bigger (have a look at my solution). Also, it's more difficult to get a generic solution using regex. There are so many factors to consider.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86793843
score: 0
has text: @RobertSeaman how can I change it to return the date instead of the days, for eg. if for the first test code above I need it to return 2010-01-02
type: QuestionComment
comment on: http://stackoverflow.com/q/49888412
type: Comment

http://stackoverflow.com/a/49772363
has comment: http://stackoverflow.com/comment/86560287
has body: Here is a more efficient way: def journal_parser(context): with open("/tmp/journal_slice.log") as f: data = f.read() words = re.findall(r"|".join(keywords), data, re.I) # case insensitive matching by passing the re.I flag (ignore case) count = dict(Counter(words)) print(count)
has comment: http://stackoverflow.com/comment/86593874
answers question: http://stackoverflow.com/q/49772156
has comment: http://stackoverflow.com/comment/86596090
score: 0
type: Answer

http://stackoverflow.com/q/49764897
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49764998
score: -2
tagged with: python
has body: I am currently working on a program for my robotics team the prints out a team key(a string) and a value that ranks how good it is. So the current output I have is a dictionary with the team key as the key and the value as the value. However the dictionary is not sorted. I have read that you can change it to a list of tuples which I have tried and worked, but I have just 1 issue. Currently the team key has 'frc' in front of the team number, and I remove it by doing [3:]. However when I do the same for the list of tuples, it doesn't work. So I was wondering if there was a way to sort the dictionary by its values without changing it to a list of tuples?
has answer: http://stackoverflow.com/a/49764998
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49764961
possible better answer: http://stackoverflow.com/a/49764961
answer count: 2
linked to: http://stackoverflow.com/q/20944483
has comment: http://stackoverflow.com/comment/86545413
downvote count: 3
has comment: http://stackoverflow.com/comment/86545388
upvote count: 1
has title: How to order a dictionary by its values without changing it to a list of tuples
has comment: http://stackoverflow.com/comment/86545437

http://stackoverflow.com/comment/86829413
type: AnswerComment
comment on: http://stackoverflow.com/a/49905889
score: 0
has text: You mean: `profile_form = RegisterUserInfoForm(instance=request.user)` ? Got it all the time
type: Comment

http://stackoverflow.com/a/49770870
downvote count: 0
has comment: http://stackoverflow.com/comment/86557000
has body: The reason is that remove changes the list, and does not return a new one, so you can't chain it. What about the following way? result = [item for item in df.columns if item != x] Please note that this code is not exactly equivalent to the one you provided, as it will remove all occurrences of x, not just the first one as with remove(x).
score: 3
has comment: http://stackoverflow.com/comment/86556803
has comment: http://stackoverflow.com/comment/86556733
type: Answer
has comment: http://stackoverflow.com/comment/86557197
has comment: http://stackoverflow.com/comment/86556761
answers question: http://stackoverflow.com/q/49770819
upvote count: 3
has comment: http://stackoverflow.com/comment/86556662

algorithm
tags question: http://stackoverflow.com/q/49787852
tags question: http://stackoverflow.com/q/49819314
tags question: http://stackoverflow.com/q/49906109
type: Tag
tag name: algorithm
tags question: http://stackoverflow.com/q/49882469
tags question: http://stackoverflow.com/q/49806787
tags question: http://stackoverflow.com/q/49796209
tags question: http://stackoverflow.com/q/49909039
tags question: http://stackoverflow.com/q/49791692
tags question: http://stackoverflow.com/q/49883623
tags question: http://stackoverflow.com/q/49890536
tags question: http://stackoverflow.com/q/49912464
tags question: http://stackoverflow.com/q/49781154
tags question: http://stackoverflow.com/q/49859091
tags question: http://stackoverflow.com/q/49904659
tags question: http://stackoverflow.com/q/49839547
tags question: http://stackoverflow.com/q/49822003
tags question: http://stackoverflow.com/q/49911754
tags question: http://stackoverflow.com/q/49776040
tags question: http://stackoverflow.com/q/49912025
tags question: http://stackoverflow.com/q/49865888
tags question: http://stackoverflow.com/q/49779076
tags question: http://stackoverflow.com/q/49877595

http://stackoverflow.com/a/49858285
answers question: http://stackoverflow.com/q/49857457
type: Answer
has body: The problem here is re.sub() expects the first argument as a regular expression, where as match[0] is '[id: 196]', which means *replaces any of the chars with your string: i, d, :, space, ... Knowing that, you have a couple of choices. Since I don't know enough context, I cannot make a decision which is better, you have to decice: Use the original 'reg` as first parameter string = re.sub(reg, "%s" % (entry.id, entry.name), string) Escape the match[0] parameter string = re.sub(re.escape(match[0]), "%s" % (entry.id, entry.name), string) Do a straight string replacement anchor = string.replace(match[0], "%s" % (entry.id, entry.name))
score: 0

http://stackoverflow.com/comment/86757617
has text: You can directly use `action="/return-files"` instead of `url_for`. I think some flask app setting is missing to make this magic function work `url_for`.
type: Comment
comment on: http://stackoverflow.com/a/49849505
score: 0
type: AnswerComment

http://stackoverflow.com/a/49780595
score: 0
answers question: http://stackoverflow.com/q/49765382
has body: Thanks for the answers. Tried using numpy.roll(arr, shift_amount). It also works, but elements that roll beyond the last position are re-introduced at the first. So, when (i+x) is less than shape[0], it can be used. if (i+x) &lt; arr1.shape[0]: arr2 = np.roll(arr1,x)
type: Answer

http://stackoverflow.com/comment/86839128
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/49911588
has text: Why are you using both `for k in a` and `e = next(a)`? Both do essentially the same thing. BTW, `StopIteration` means that you have reached the end of the file.

http://stackoverflow.com/q/49911259
tagged with: python
has body: I am running osx 10.11.6 (el-capitan) a long time ago I installed Python3 using the download on python.org (3.5.0) since then I've installed brew and would like to use brew to manage python3 instead. I have to upgrade to python3.6 because I'm getting the tlsv1 alert protocol version error. How do I uninstall my current python3 How do I get brew to install python 3.6 (it seems to only want to install 3.5.1) or is it better to just run different python versions beside one another? Thanks!
score: 2
upvote count: 2
has title: moving python3 to brew and updating
downvote count: 0
tagged with: homebrew
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49911429
type: UnansweredQuestion

http://stackoverflow.com/a/49917069
accepted answer of: http://stackoverflow.com/q/49916517
has comment: http://stackoverflow.com/comment/86855179
answers question: http://stackoverflow.com/q/49916517
type: AcceptedAnswer
type: Answer
has body: There is a visualization tool in Keras called plot_model. You can use it to save your model as an image where you can see the structure of your model including input and output dimensions. from keras.utils import plot_model plot_model(model, to_file='model.png') You can read more about it here: Keras Visualization
score: 0

http://stackoverflow.com/a/49877159
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49874829
has comment: http://stackoverflow.com/comment/86796029
type: Answer
accepted answer of: http://stackoverflow.com/q/49874829
has body: Compile the source to the .pyc bytecode, and then move the source somewhere inaccessible. Open a terminal window in the directory containing your script Run python -m py-compile &lt;yourfile.py&gt; (you should get a yourfile.pyc file) Move &lt;yourfile.py&gt; somewhere secure your script can now be run as python &lt;yourfile.pyc&gt; Note that is is not necessarily secure as such - there are ways to decompile the bytecode - but it does obfuscate it, if that is your requirement.

http://stackoverflow.com/a/49812949
has body: The problem is due to the name of your script "pandas.py" you can't have in your current folder files call pd or pandas, etc... In general avoid name for script, variable, etc... that are also use for library, module, function, etc...
score: 6
upvote count: 6
downvote count: 0
has comment: http://stackoverflow.com/comment/86643327
has comment: http://stackoverflow.com/comment/86641124
type: Answer
has comment: http://stackoverflow.com/comment/86640811
answers question: http://stackoverflow.com/q/49812802
has comment: http://stackoverflow.com/comment/86641037
has comment: http://stackoverflow.com/comment/86642685
has comment: http://stackoverflow.com/comment/86640505

http://stackoverflow.com/q/49885247
has comment: http://stackoverflow.com/comment/86786945
has answer: http://stackoverflow.com/a/50029883
answer count: 1
tagged with: logistic-regression
type: Question
has body: import numpy as np def sigmoid(x): return 1.0/(1+np.asmatrix(np.exp(-x))) def graD(X,y,alpha,s0,numda): m=np.size(X,0) n=np.size(X,1) X0=X[:,0] X1=X[:,1:] theta=np.asmatrix(np.zeros(np.size(X,1))).T s=100 lit=0 while abs(s)&gt;s0 and lit&lt;=10000: theta0=theta[0] theta1=theta[1:] theta0-=(float(alpha)/m)*X0.T*(sigmoid(X*theta)-y) theta1-=float(alpha)*((1.0/m)*X1.T*(sigmoid(X*theta)- y)+float(numda)/m*theta1) theta=np.vstack((np.asmatrix(theta0),np.asmatrix(theta1))) lit+=1 s=sum((float(1.0)/m)*X.T*(sigmoid(X*theta)-y))/float(n) return theta This is a logistic regression using the simple sigmoid function 1/(1+e^(-t)), I can not figure out what is the problem mainly with the function 'graD' part which does the regularized gradient descent, the result is not correct which is as follows: lg(X,y,0.01,0.1,30) Out[137]: matrix([[1000.10539375], [ 49.33333333]]) and the data I input is: (for X): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 (for y): 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/86786551
has comment: http://stackoverflow.com/comment/86786908
type: AnsweredQuestion
has title: machine learning, logistic regression
score: 0
accepted answer: http://stackoverflow.com/a/50029883

http://stackoverflow.com/q/49787901
tagged with: pip
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: argon2-ffi
has body: I am trying to install argon2_cffi in my python 3.5 virtual environment without using pip. I have downloaded the package from github . When I am trying to install this , python setup.py build or install , it fails with the error running install running bdist_egg running egg_info creating src/argon2_cffi.egg-info writing requirements to src/argon2_cffi.egg-info/requires.txt writing src/argon2_cffi.egg-info/PKG-INFO writing dependency_links to src/argon2_cffi.egg- info/dependency_links.txt writing top-level names to src/argon2_cffi.egg-info/top_level.txt writing manifest file 'src/argon2_cffi.egg-info/SOURCES.txt' reading manifest file 'src/argon2_cffi.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no previously-included files found matching 'src/argon2/_ffi.py' warning: no previously-included files found matching '.gitmodules' warning: no previously-included files found matching 'extras/libargon2/.git' warning: no previously-included files found matching 'appveyor.yml' warning: no previously-included files matching '*.pyc' found under directory 'tests' no previously-included directories found matching 'docs/_build' writing manifest file 'src/argon2_cffi.egg-info/SOURCES.txt' installing library code to build/bdist.linux-x86_64/egg running build_clib building 'libargon2' library x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict- prototypes -g -fstack-protector-strong -Wformat -Werror=format- security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -msse2 - Iextras/libargon2/src/../include -Iextras/libargon2/src/blake2 -c extras/libargon2/src/argon2.c -o build/temp.linux-x86_64- 3.5/extras/libargon2/src/argon2.o x86_64-linux-gnu-gcc: error: extras/libargon2/src/argon2.c: No such file or directory x86_64-linux-gnu-gcc: fatal error: no input files compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
tagged with: python
has answer: http://stackoverflow.com/a/49788684
has title: Unable to install Python argon2_cffi
type: AnsweredQuestion
upvote count: 2
score: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/49788684
downvote count: 0

http://stackoverflow.com/comment/86699700
has text: How would you make it so it also clicks on that particular item? Cause i get this error:
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49842389
type: Comment

http://stackoverflow.com/a/49880773
has comment: http://stackoverflow.com/comment/86803291
has comment: http://stackoverflow.com/comment/86818443
type: Answer
answers question: http://stackoverflow.com/q/49872545
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I tried some of fuzzywuzzy comparisons over 2 DFs and as far as my research went, there is no fast way to do it. The fact that you use 4 fuzz methods slow down your script too. One way could be to use 'process.extractOne()` and create a function such: from fuzzywuzzy import process def fw_process(row_df1): # Select the addresses from df2 with same postal_code df2_select_add = df2['address'][df2['postal_code'] == row_df1['postal_code']] ad_1 = row_df1['address'] # Find the best match for ad_1 in df2_select_add and get the ratio with [1] # for the name of df2_select_add , use [0] if process.extractOne(ad_1, df2_select_add)[1] &gt;= 80: return 'Y' else: return 'N' Then to create your column flag in df1, you do: df1['flag'] = df1.apply(fw_process , axis=1) NOTE: the name df2 is not called as parameter of the function which is not the cleaner way, but if it's define before in your code with this name it works. If you want to keep the 4 fuzz methods, then you can create the function on the same idea: from fuzzywuzzy import fuzz def fw_fuzz ( row_df1): # Select the addresses from df2 with same postal_code df2_select_add = df2['address'][df2['postal_code'] == row_df1['postal_code']] ad_1 = row_df1['address'] # Get the max of the max of the 4 fuzz comparison between ad_1 and df2_select_add if max (df2_select_add.apply(lambda x: max(fuzz.ratio(ad_1, x), fuzz.partial_ratio(ad_1, x), fuzz.token_sort_ratio(ad_1, x),fuzz.token_set_ratio(ad_1, x)))) &gt;= 80: return 'Y' else: return 'N' and then: df1['flag'] = df1.apply(fw_fuzz, axis=1)
accepted answer of: http://stackoverflow.com/q/49872545

http://stackoverflow.com/a/49922720
has comment: http://stackoverflow.com/comment/87103157
score: 0
has comment: http://stackoverflow.com/comment/87064923
answers question: http://stackoverflow.com/q/49863009
has comment: http://stackoverflow.com/comment/87086794
has body: You could try to install this package manually: Clone source code; Open setup.py and remove python logic which adds this flag. (in my version they are lines 16, and 17: StringListOption("CXXFLAGS", ["-Wno-sign-compare"], help="Any extra C++ compiler options to include"), Use python setup.py install to install the package with changed setup.py Hope this will help you.
has comment: http://stackoverflow.com/comment/87100110
type: Answer
has comment: http://stackoverflow.com/comment/87045340
has comment: http://stackoverflow.com/comment/87101227
has comment: http://stackoverflow.com/comment/87020293

http://stackoverflow.com/comment/86866338
comment on: http://stackoverflow.com/q/49907111
type: QuestionComment
has text: Ah yes! @roganjosh, thank you for pointing that out. I intuitively added it as a "comment". Easily brushed it off, so glad you mentioned it.
type: Comment
score: 0

http://stackoverflow.com/comment/86734529
has text: Check this answer https://stackoverflow.com/questions/39840030/distance-between-point-and-a-line-from-two-points#39840218
type: Comment
comment on: http://stackoverflow.com/q/49859625
score: 0
type: QuestionComment

xsd
tags question: http://stackoverflow.com/q/49783071
type: Tag
tag name: xsd

pdfkit
tags question: http://stackoverflow.com/q/49783892
tag name: pdfkit
type: Tag
tags question: http://stackoverflow.com/q/49881000

http://stackoverflow.com/comment/122439616
has text: If you need to check many lines, you need to build a high ladder from try-catch blocks. I don't think this is a good pattern.
type: AnswerComment
comment on: http://stackoverflow.com/a/49810145
score: 0
type: Comment

http://stackoverflow.com/comment/91347868
type: QuestionComment
type: Comment
has text: Thanks @ScottBoston ─ indeed it does help (a lot!). Quite a big chunk of code to get done what I wanted, but very flexible and comprehensive. It'll come in useful again.
comment on: http://stackoverflow.com/q/49832781
score: 1

http://stackoverflow.com/q/49904400
tagged with: python
has comment: http://stackoverflow.com/comment/86825095
has comment: http://stackoverflow.com/comment/86827828
has body: I have a data set that shows count of loads for each category. Given below is the data I have. Name,Count1,Count2,PercentDiff,Category Store A,10,4,0.4,Less than 1% Store B,20,26,1.3,Less than 5% Store C,12,48,4,Less than 5% Store D,30,180,6,Less than 10% I would like to get the count for each of the below categories 1. Less than 0 2. Less than 1% 3. Less than 5% 4. Less than 10% 5. More than 10% I have used the below rule to categorise each of these entries: new.loc[new['PercentDiff'] &lt; 0, 'Category'] = 'Less than 0%' new.loc[new['PercentDiff'] == 0, 'Category'] = 'Exact match' new.loc[new['PercentDiff'] &lt; 0.01, 'Category'] = 'Less than 1%' new.loc[new['PercentDiff'] &lt; 0.05, 'Category'] = 'Less than 5%' new.loc[new['PercentDiff'] &lt; 0.1, 'Category'] = 'Less than 10%' new.loc[new['PercentDiff'] == 0, 'Category'] = 'Exact match' new.loc[new['PercentDiff'] &gt; 0.1, 'Category'] = 'Greater than 10%' new['PercentDiff1'] = new['PercentDiff'].astype(int) Output1 = new.groupby(['Category']).agg(lambda x: x.mad()) Output1 = Output1.replace(np.nan, '', regex=True) SumMail = pd.value_counts(Output1['Category'].values) However, if the data set has no values for any of the categories I get an error stating no values found for a particular category. TypeError: 'str' object cannot be interpreted as an integer KeyError: 'More than 10%' Could anyone help me modify this code so that it returns 0 for categories that have no records. Thanks in advance.
score: 0
has comment: http://stackoverflow.com/comment/86830304
tagged with: pandas
tagged with: group-by
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49907635
has title: Pandas groupby/value_counts for no values
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49907558

http://stackoverflow.com/a/49897951
has body: if you need partial search for class use. s = """&lt;div class="i-stars i-stars--regular-5 rating-large" title="5.0 star rating"&gt; &lt;img class="offscreen" height="303" src="https://s3-media2.fl.yelpcdn.com/assets/srv0/yelp_design_web/9b34e39ccbeb/assets/img/stars/stars.png" width="84" alt="5.0 star rating"&gt; &lt;/div&gt;""" from bs4 import BeautifulSoup r = BeautifulSoup(s, "html.parser") rating = r.find_all('div') for i in rating: if "i-stars i-stars--regular-5" in " ".join(i["class"]): print(i.get('title', 'No title attribute')) Output: 5.0 star rating
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49897889
has comment: http://stackoverflow.com/comment/86811293
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/49847221
answers question: http://stackoverflow.com/q/49847143
has comment: http://stackoverflow.com/comment/139636080
upvote count: 3
has body: What about setting the dtype of your GaussMatrix to np.float64? GaussMatrix = np.array(GaussMatrix, dtype=np.float64)
downvote count: 0
has comment: http://stackoverflow.com/comment/86721861
score: 3
has comment: http://stackoverflow.com/comment/86709484
type: Answer
has comment: http://stackoverflow.com/comment/139628770

anaconda
tags question: http://stackoverflow.com/q/49916289
tags question: http://stackoverflow.com/q/49897527
tags question: http://stackoverflow.com/q/49822692
tags question: http://stackoverflow.com/q/49826019
tags question: http://stackoverflow.com/q/49793128
tags question: http://stackoverflow.com/q/49806573
type: Tag
tags question: http://stackoverflow.com/q/49889404
tags question: http://stackoverflow.com/q/49837535
tag name: anaconda
tags question: http://stackoverflow.com/q/49914882
tags question: http://stackoverflow.com/q/49851200
tags question: http://stackoverflow.com/q/49785938
tags question: http://stackoverflow.com/q/49810184
tags question: http://stackoverflow.com/q/49916115
tags question: http://stackoverflow.com/q/49813237
tags question: http://stackoverflow.com/q/49889502
tags question: http://stackoverflow.com/q/49772573
tags question: http://stackoverflow.com/q/49805906
tags question: http://stackoverflow.com/q/49892136
tags question: http://stackoverflow.com/q/49833649
tags question: http://stackoverflow.com/q/49839787
tags question: http://stackoverflow.com/q/49771377
tags question: http://stackoverflow.com/q/49914880
tags question: http://stackoverflow.com/q/49817284
tags question: http://stackoverflow.com/q/49883457
tags question: http://stackoverflow.com/q/49840675
tags question: http://stackoverflow.com/q/49819253
tags question: http://stackoverflow.com/q/49771424
tags question: http://stackoverflow.com/q/49829307
tags question: http://stackoverflow.com/q/49859885
tags question: http://stackoverflow.com/q/49830724
tags question: http://stackoverflow.com/q/49889855
tags question: http://stackoverflow.com/q/49759883
tags question: http://stackoverflow.com/q/49761751
tags question: http://stackoverflow.com/q/49799174

http://stackoverflow.com/comment/86558577
type: QuestionComment
has text: I tried to install it and I also find something wrong. My IDE (PyCharm) doesn't find any module named mdentropy, thus the import fails.
comment on: http://stackoverflow.com/q/49771560
score: 0
type: Comment

http://stackoverflow.com/a/70607967
has body: You do not need to await which function is running asynchronously async def getData(): retrienveData = thirdPartyAPIWrapper.data() return retrieveData
upvote count: 12
downvote count: 0
type: Answer
score: 12
answers question: http://stackoverflow.com/q/49822552

http://stackoverflow.com/a/49890565
type: Answer
has body: I try to move the gradient average and gradient descend to GPU:0. Because my GPUs have peer2peer connections, the data move is fast and the computation in GPU is also fast. Place all these ops in the first GPU nearly solve my problem. It is welcomed if anyone has other comments :D
answers question: http://stackoverflow.com/q/49843171
score: 0

http://stackoverflow.com/comment/86822600
score: 0
comment on: http://stackoverflow.com/q/49898476
has text: Thanks, I wil try it
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86632954
score: 3
comment on: http://stackoverflow.com/q/49808989
type: Comment
type: QuestionComment
has text: These links might help. The official docs say you cannot reliably modify locals(). https://stackoverflow.com/questions/8028708/dynamically-set-local-variable, https://docs.python.org/3/library/functions.html#locals

http://stackoverflow.com/q/49844117
has answer: http://stackoverflow.com/a/49844292
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/86703000
possible better answer: http://stackoverflow.com/a/49861447
tagged with: dataframe
tagged with: python
has title: Change the column values in pandas based on conditions from two or more columns
has answer: http://stackoverflow.com/a/49861447
has comment: http://stackoverflow.com/comment/86702854
has body: I want to replace column 'k' based on conditions from two columns, and found this code snippet on github.. This is the code snippet: df.loc[(df['column1'] == some_value) &amp; (df['column2'] == some_other_value), ['column_to_change']] = new_value This is the code I use: def merged_algo_A(cluster_array): rows,labels = readCluster(cluster_array) # reading the test data xtest = pd.DataFrame(np.array(rows).reshape(len(rows),11), columns = list("abcdefghijk")) ytest = pd.DataFrame(np.array(labels).reshape(len(labels),1),columns = list("l")) #print(xtrain['c']) xtest['SportYes'] = np.where(xtest['c']&lt;=16897, '200', '400') xtest['stateYes'] = np.where(xtest['k']&lt;=62, '200', '400') xtest['durYes'] = np.where(xtest['a']&lt;=0.0585, '200', '400') xtest.loc[(xtest['SportYes'] == 200) &amp; (xtest['stateYes'] == 200), 'k'] = 3 print(xtest)
tagged with: pandas
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/86702869
upvote count: 1
has comment: http://stackoverflow.com/comment/86702817
accepted answer: http://stackoverflow.com/a/49844292
favorite count: 0
score: -1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86702842

http://stackoverflow.com/comment/86626731
comment on: http://stackoverflow.com/q/49805900
type: Comment
has text: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_clipboard.html Use `df.to_clipboard()` then paste it here.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86580373
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49782111
has text: Is your goal to have these files installed somewhere accessible at `pip install` time, or to have them embedded in the package directory and access them the same way you can access submodules?
type: Comment

http://stackoverflow.com/q/49912659
tagged with: python
tagged with: google-cloud-dataflow
has answer: http://stackoverflow.com/a/53535369
has answer: http://stackoverflow.com/a/50041967
favorite count: 0
score: 3
upvote count: 3
tagged with: google-bigquery
type: Question
has title: Cloud Dataflow Writing to BigQuery Python Errors
answer count: 2
has body: I'm writing a simple Beam job to copy data from a GCS bucket over to BigQuery. The code looks like the following: from apache_beam.options.pipeline_options import GoogleCloudOptions import apache_beam as beam pipeline_options = GoogleCloudOptions(flags=sys.argv[1:]) pipeline_options.project = PROJECT_ID pipeline_options.region = 'us-west1' pipeline_options.job_name = JOB_NAME pipeline_options.staging_location = BUCKET + '/binaries' pipeline_options.temp_location = BUCKET + '/temp' schema = 'id:INTEGER,region:STRING,population:INTEGER,sex:STRING,age:INTEGER,education:STRING,income:FLOAT,statusquo:FLOAT,vote:STRING' p = (beam.Pipeline(options = pipeline_options) | 'ReadFromGCS' &gt;&gt; beam.io.textio.ReadFromText('Chile.csv') | 'WriteToBigQuery' &gt;&gt; beam.io.WriteToBigQuery('project:tmp.dummy', schema = schema)) Where we're writing into the table tmp.dummy in the project project. This is resulting in the following stacktrace: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 151, in _run_module_as_main mod_name, loader, code, fname = _get_module_details(mod_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 101, in _get_module_details loader = get_loader(mod_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 464, in get_loader return find_loader(fullname) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 474, in find_loader for importer in iter_importers(fullname): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py", line 430, in iter_importers __import__(pkg) File "WriteToBigQuery.py", line 49, in &lt;module&gt; | 'WriteToBigQuery' &gt;&gt; beam.io.WriteToBigQuery(str(PROJECT_ID + ':' + pipeline_options.write_file), schema = schema)) File "/Users/mayansalama/Documents/GCP/gcloud_env/lib/python2.7/site-package…
type: UnansweredQuestion
downvote count: 0
tagged with: apache-beam

http://stackoverflow.com/comment/86630980
type: Comment
score: 0
type: QuestionComment
has text: I'm voting to close this question as off-topic because malware is bad. Ok?
comment on: http://stackoverflow.com/q/49805800

http://stackoverflow.com/comment/86683934
comment on: http://stackoverflow.com/a/49834246
type: AnswerComment
has text: Thank you ver much jpp, that does it perfectly
score: 1
type: Comment

http://stackoverflow.com/comment/86828030
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49900237
has text: Starting with loop 1; what would be to code Id put in my search string to include the line in the file name? Right now im using var1. `url = 'https://www.example.com/Listings?st=' + var1 + '&sg=&c=&s=&lp=0&hp=999999&p={}'.format(i)` To make sure we have the same goal here; I want the outside file, author.txt to have each author listed to be inserted in the url where var1 is at.

http://stackoverflow.com/q/49802142
has comment: http://stackoverflow.com/comment/88460081
has answer: http://stackoverflow.com/a/49808744
has title: Is it possible to use a schema for a marshmallow custom field?
tagged with: python
tagged with: marshmallow
has body: Let's say that I have a UserSchema: class UserSchema(ma.ModelSchema): class Meta: model = User fields = ('email', 'fullname') and I have another Object Model Group that has a many-to-many relation with User and a method to return a subset of its users: class Group(db.Model): ... def get_active_members(self): active_members = ... return active_members I'm now try to write the marshmallow schema to serialize the Group model including also the active members. I know that I can use a custom field but if I do: class GroupSchema(ma.ModelSchema): members = fields.Function(lambda obj: obj.get_active_members()) I get is an error telling me that the User object is not serializable TypeError: Object of type 'User' is not JSON serializable If I try to use a nested field instead it just doesn't return anything since get_active_members is not a field. Is there a way to return the active members in this case? A possible solution I have found: class Group(db.Model): ... @property def members(self): return get_active_members() def get_active_members(self): active_members = ... return active_members class GroupSchema(ma.ModelSchema): members = fields.Nested(UserSchema, dump_only=True) But I'm not really sure if this is how Marshmallow should work.
tagged with: sqlalchemy
favorite count: 0
type: Question
downvote count: 0
type: UnansweredQuestion
answer count: 1
upvote count: 4
score: 4
tagged with: flask-sqlalchemy

http://stackoverflow.com/comment/86742599
score: 0
has text: Thanks for your Response . You mean column value will level 0 ,column year will level 1 etc
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49859182

http://stackoverflow.com/a/49889826
answers question: http://stackoverflow.com/q/49887707
score: 2
accepted answer of: http://stackoverflow.com/q/49887707
upvote count: 2
type: AcceptedAnswer
has body: Thanks for putting a complete code example, that is very helpful. Both suggestions made in my comment work: Option 1: use the right exception If you replace except IndexError in your code with except KeyError, your code will print "Index Error" five times. Snippet in question: for i in sorted(thresholds.keys()): try: current = current_data.loc[i, 'Recent-Server'] if current != '0': valor = thresholds[i] except KeyError: # &lt;------------------------ use the right exception print("Index Error") Option 2: check the index for membership before accessing Alternatively, you can check the dataframe's index before accessing, like so: for i in sorted(thresholds.keys()): if i in current_data.index: current = current_data.loc[i, 'Recent-Server'] if current != '0': valor = thresholds[i] Note here that I check the dataframe's index i in current_data.index. What you tried (i in current_data.loc.index) is a syntax error, since it's not loc that has the index but the dataframe current_data itself. Both these techniques work. I prefer #2.
downvote count: 0
has comment: http://stackoverflow.com/comment/86796107
type: Answer

http://stackoverflow.com/comment/86633107
type: QuestionComment
score: 2
has text: I guess the question is: why would you want a cursor? I think you should perhaps have a look at Flask-SQLAlchemy and SQLAlchemy documentation on how to use them.
comment on: http://stackoverflow.com/q/49797786
type: Comment

http://stackoverflow.com/q/49844928
type: AnsweredQuestion
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/49844997
accepted answer: http://stackoverflow.com/a/49844997
has body: I my code i am using sklearn kMeans algorithm. when i execute the code i got the error like "'KMeans' object has no attribute 'labels_'" Traceback (most recent call last): File ".\kmeans.py", line 56, in &lt;module&gt; np.unique(km.labels_, return_counts=True) AttributeError: 'KMeans' object has no attribute 'labels_' Here is my code : import pandas as pds import nltk,re,string from nltk.probability import FreqDist from collections import defaultdict from nltk.tokenize import sent_tokenize, word_tokenize, RegexpTokenizer from nltk.tokenize.punkt import PunktSentenceTokenizer from nltk.corpus import stopwords from string import punctuation from heapq import nlargest # import and instantiate CountVectorizer from sklearn.feature_extraction.text import CountVectorizer vect = CountVectorizer() from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer(ngram_range=(1,2),max_df=0.5, min_df=2,stop_words='english') train_X = vectorizer.fit_transform(x) from sklearn.cluster import KMeans import sklearn.cluster.k_means_ km = KMeans(n_clusters=3, init='k-means++', max_iter=100, n_init=1, verbose=True) import numpy as np np.unique(km.labels_, return_counts=True) text = {} for i,cluster in enumerate(km.labels_): oneDocument = X[i] if cluster not in text.keys(): text[cluster] = oneDocument else: text[cluster] += oneDocument _stopwords = set(stopwords.words('english')+ list(punctuation)) keywords = {} counts = {} for cluster in range(3): word_sent = word_tokenize(text[cluster].lower()) word_sent = [word for word in word_sent if word not in _stopwords] freq = FreqDist(word_sent) keywords[cluster] = nlargest(100, freq, key=freq.get) counts[cluster] = freq unique_keys={} for cluster in range(3): other_clusters = list(set(range(3))-set([cluster])) keys_other_clusters = set(keywords[other_clusters[0]]).union(set(keywords[other_clusters[1]])) unique=set(keywords[cluster])-keys_other_clusters unique_keys[cluster]= nlargest(100, unique, key=counts[cluster].get…
favorite count: 0
type: Question
upvote count: 6
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
score: 4
has title: 'KMeans' object has no attribute 'labels_'

http://stackoverflow.com/a/58916492
upvote count: 1
type: AcceptedAnswer
has body: I compared broadcast, threadpool and loop. In this case, ThreadPool had the best performance. # %% Import # Standard library imports import time from multiprocessing.pool import ThreadPool # Third party imports from numpy import zeros, complex128, allclose from numpy.fft import fft, ifft from numpy.random import standard_normal # %% Generate data n_row, n_col = 6000, 13572 ss = standard_normal((n_row, n_col)) + 1j * standard_normal((n_row, n_col)) sig = standard_normal(n_col) + 1j * standard_normal(n_col) ss_loop = zeros((n_row, n_col), dtype=complex128) ss_thread = zeros((n_row, n_col), dtype=complex128) # %% Loop processing start_time = time.time() for idx in range(n_row): ss_loop[idx, :] = ifft(fft(ss[idx, :]) * sig) print(f'loop elapsed time : {time.time() - start_time}') # %% Broadcast processing start_time = time.time() ss_broad = ifft(fft(ss, axis=1) * sig, axis=1) print(f'broadcast elapsed time : {time.time() - start_time}') # %% ThreadPool processing def filtering(idx_thread): ss_thread[idx_thread, :] = ifft(fft(ss[idx_thread, :]) * sig) start_time = time.time() pool = ThreadPool() pool.map(filtering, range(n_row)) print(f'ThreadPool elapsed time : {time.time() - start_time}') # %% Verify result if allclose(ss_thread, ss_broad, rtol=1.e-8): print('ThreadPool Correct') if allclose(ss_loop, ss_broad, rtol=1.e-8): print('Loop Correct') Result loop elapsed time : 5.102990627288818 broadcast elapsed time : 4.520442008972168 ThreadPool elapsed time : 1.6988463401794434
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49903741
answers question: http://stackoverflow.com/q/49903741
downvote count: 0

http://stackoverflow.com/q/49805467
answer count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/49806243
tagged with: http://stackoverflow.com/tag/html
has body: This is probably a basic question, but I haven't been able to figure it out. Still learning how to use beautifulsoup. I'm trying to parse HTML that looks like Tournament Name TCG Saturday Tournament ID 000002 Category TCG: Unlimited Registration 12:15PM to 1:15PM Status Complete so that only the li tag is read and the label tag is ignored. That is, the resulting text would be TCG Saturday 000002 TCG: Unlimited 12:15PM to 1:15PM Complete I've tried soup = BeautifulSoup(html) for lis in soup.find_all('li'): print(lis.text) but that results in also reading the text of the label tag and cating them together. It also reads a bunch of other text on the webpage and prints it. Tournament NameTCG Saturday Tournament ID000002 CategoryTCG: Unlimited Registration12:15PM to 1:15PM StatusComplete I can also get just the labels using soup = BeautifulSoup(html) for lis in soup.find_all('label'): print(lis.text) but that doesn't have the text afterwards (which is understandable). I don't understand how to parse this HTML so that I can get 1) Just the text in the li tag, excluding the text in the label tag (as in the expected above) or 2) The text in the li tag for a specific label (say, specifying the "Tournament ID" label and getting "000002" back).
has answer: http://stackoverflow.com/a/49806243
tagged with: python
has title: Exclude inner tag and specific label with beautifulsoup
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: web-scraping
upvote count: 1

http://stackoverflow.com/comment/86675057
comment on: http://stackoverflow.com/a/49829907
type: AnswerComment
has text: Wow you guys are so helpful, thank you so much. Now to figure out how to remove the spaces between them. Thank you so much!!!
score: 0
type: Comment

http://stackoverflow.com/q/49768997
has comment: http://stackoverflow.com/comment/128307059
has body: All documentations I found regarding TFRecords are generating tf.train.Example()s one by one, and writing them using writer = tf.python_io.TFRecordWrite(path) ex = generate_example(features) # Returns tf.train.Example() instance writer.write(ex.SerializeToString()) Since I'm dealing with very big data, I know that I'll pay a high overhead price for writing examples separately Is there any way to write multiple tf.train.Example() to a TFRecord at once?
tagged with: python
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/49769737
has comment: http://stackoverflow.com/comment/129454678
tagged with: tensorflow
type: Question
upvote count: 4
has title: Writing TFRecords in batches
type: UnansweredQuestion
downvote count: 0
tagged with: tfrecord
answer count: 1

http://stackoverflow.com/a/49837384
score: 3
upvote count: 3
type: Answer
has body: When you pass in a time without specifying the format, Pandas tries to guess at the format in a naive manner. It was assuming that what is your day is actually your month but then when it sees that it is month 13, realizes that can't be the month column and switches. The following should work but I like @cᴏʟᴅsᴘᴇᴇᴅ's solution better because it is simpler to just raise the dayfirst flag. To fix this, provide the current format to the to_datetime function. The documentation gives the following example which you can modify to fit your situation: pd.to_datetime('13000101', format='%Y%m%d', errors='ignore') See details here: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html Time format conventions (what %Y means and so on) are here: https://docs.python.org/3.2/library/time.html
answers question: http://stackoverflow.com/q/49837288
downvote count: 0

http://stackoverflow.com/q/49847181
has comment: http://stackoverflow.com/comment/86709314
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86709567
has comment: http://stackoverflow.com/comment/86709609
downvote count: 0
upvote count: 1
score: 1
tagged with: flask
answer count: 1
favorite count: 0
tagged with: ajax
has answer: http://stackoverflow.com/a/49847365
has body: I am trying to upload a csv file from the page and send it to the backend made of python and flask, all the gets working fine, knowing that because backend returns: 127.0.0.1 - - [15/Apr/2018 15:37:07] "GET /medal HTTP/1.1" 200 but nothing on the POST. Tried almost everything but no connections or messages. BACKEND POST: import pandas from calest import calest_app, client from flask import request, jsonify from..models.Medals import Medal db = client.estadisticas collection = db.medallas @calest_app.route('/result', methods = ["POST"]) def post_discipline(): csv_received = request.files['file'] csv_file = pandas.read_csv(csv_received) discipline_result = Medal(csv_file).get_medals_discipline() gender_result = Medal(csv_file).get_medals_gender() city_result = Medal(csv_file).get_medals_city() country_result = Medal(csv_file).get_medals_country() medals_result = Medal(csv_file).get_medals_by_medals() sport_result = Medal(csv_file).get_medals_by_sport() cursor = collection.insert({ "discipline": discipline_result, "gender": gender_result, "city": city_result, "country": country_result, "medal": medals_result, "sport": sport_result }) return jsonify("Added"), 201 FRONTEND AJAX: &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" &gt; &lt;/script&gt; &lt; script &gt; $("#form").on("submit", function (e) { var fileSelect = $("#csvFile"); var files = fileSelect[0].files; // Create a new FormData object. var formData = new FormData(); debugger; formData.append("#csvFile", files[0].name, files[0], files[0].name); &lt;!--csv_received = request.-- &gt; $.ajax({ url: "http://localhost:5000/result", method: "POST", data: formData, contentType: false, // The content type used when sending data to the server. cache: false, // To unable request pages to be cached processData: false, // To send DOMDocument or non processed data file it is set to false success: function (data) { debugger; }, error: function (XMLHttpRequest, textStatus, errorThrown) { deb…
has title: export .csv file in flask using ajax
type: Question

http://stackoverflow.com/a/49854576
type: Answer
answers question: http://stackoverflow.com/q/49854272
has body: you need to state c and d variables as global (by the way this is not a good idea ) def function(): global c,d a = [4, 3] b = [2, 1] c = 1 d = 2 def inner_function(): if a[0] &gt; b[0]: global c,d print("a[0] = {0}, b[0] = {1}".format(a[0], b[0])) tmp = c c = d d = tmp inner_function()
score: 0

http://stackoverflow.com/q/49760108
has answer: http://stackoverflow.com/a/49760481
has title: Sharing information in Django application
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
tagged with: django
has body: I have a very simple model that has data in it that I need to use in various places in my application: class Setting(models.Model): name = models.CharField() value = models.TextField() I'd like to be able to load this information into a dictionary, then ship that data around my application so I don't have to make duplicate calls to the database. My attempt at doing so was wrapping the logic in a module like so (the print statement is there for debugging): my_settings.py from myapp import models class Settings: __settings = {} def __init__(self): if(not self.__class__.__settings): print("===== Loading settings from table =====") qs = models.Setting.objects.all() for x in qs: self.__class__.__settings[x.name] = x.value def get(self, key, default=None): return self.__class__.__settings.get(key, default) def getint(self, key, default=0): return int(self.__class__.__settings.get(key, default)) Using this module would then look like the following: from my_settings import Settings # Down in some view somewhere... settings = Settings() data = settings.get("some_key") ... # Now we might be in a helper function somewhere, but still in the # same view context as above. Note that we should not have made # a database round trip here; we're using our memory store instead. settings = Settings() data = settings.get("another_key") This seems to work fine, but it has the drawback that the data is loaded once (and only once) at the initial instantiation. If any of the data in the settings database table should change, those changes won't be reflected in the corresponding dictionary held by this class. Is there a better approach here? I don't mind having a single database query per request, but I also don't want to have to pass the dictionary around from function to function. I was hoping a module-level wrapper would get me the "singleton"-ness that I desire, but it's apparently caching things more aggressively than I thought it would.
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86535642
score: 1
answer count: 1

http://stackoverflow.com/a/49825074
score: 3
has comment: http://stackoverflow.com/comment/86666217
type: Answer
upvote count: 3
downvote count: 0
has body: Your bounty message says Aran-Fey's answer "does not work with mutable types". (For future readers, the bounty message is "The current answer is good, but it does not work with mutable types. If the existing answer can be adapted, or another option solution put forward, to suit this purpose, this would be ideal.") The thing is, it does work for mutable types: &gt;&gt;&gt; d = DefaultDict(list) &gt;&gt;&gt; d[0] += [1] &gt;&gt;&gt; d[0] [1] &gt;&gt;&gt; d[1] [] &gt;&gt;&gt; 1 in d False What doesn't work is something like d[1].append(2): &gt;&gt;&gt; d[1].append(2) &gt;&gt;&gt; d[1] [] That's because this doesn't involve a store operation on the dict. The only dict operation involved is an item retrieval. There is no difference between what the dict object sees in d[1] or d[1].append(2). The dict is not involved in the append operation. Without nasty, fragile stack inspection or something similar, there is no way for the dict to store the list only for d[1].append(2). So that's hopeless. What should you do instead? Well, one option is to use a regular collections.defaultdict, and just not use [] when you don't want to store defaults. You can use in or get: if key in d: value = d[key] else: ... or value = d.get(key, sentinel) Alternatively, you can turn off the default factory when you don't want it. This is frequently reasonable when you have separate "build" and "read" phases, and you don't want the default factory during the read phase: d = collections.defaultdict(list) for thing in whatever: d[thing].append(other_thing) # turn off default factory d.default_factory = None use(d)
answers question: http://stackoverflow.com/q/49778527

http://stackoverflow.com/q/49897357
has comment: http://stackoverflow.com/comment/86810380
tagged with: mysql-python
has comment: http://stackoverflow.com/comment/86810217
tagged with: python
has answer: http://stackoverflow.com/a/49897614
has title: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86810259
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86810247
has comment: http://stackoverflow.com/comment/86810880
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/86809964
has comment: http://stackoverflow.com/comment/86810137
has body: (py5) C:\Users\NIKITA GULHANE\projects\ganesh&gt;python manage.py runserver Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x00000282C396CA60&gt; Traceback (most recent call last): File "C:\Users\NIKITA~1\Envs\py5\lib\site-packages\django\db\backends\mysql\base.py", line 15, in &lt;module&gt; import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\NIKITA~1\Envs\py5\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\NIKITA~1\Envs\py5\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\Users\NIKITA~1\Envs\py5\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\NIKITA~1\Envs\py5\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\NIKITA~1\Envs\py5\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\NIKITA~1\Envs\py5\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\NIKITA~1\Envs\py5\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\NIKITA~1\Envs\py5\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\NIKITA~1\Envs\py5\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 1006, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 983, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 967, in _find_and_load_unlocked File "&lt;frozen im…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86810091
tagged with: python-3.7
score: 1

http://stackoverflow.com/comment/86576202
type: Comment
score: 0
type: AnswerComment
has text: There is not a big deal whether you go for `urllib` or `requests`. I used `requests` because I'm comfortable with it. You can see the difference between the parsers if you follow [this link](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser). Thanks.
comment on: http://stackoverflow.com/a/49766769

http://stackoverflow.com/comment/86755151
type: Comment
type: QuestionComment
has text: @Aquarius_Girl When you perform a scaling a pixel will occupy more pixels, so there are several methods to create these new pixels, one of them is to copy the value of the pixel, and others calculate an average of the surrounding pixels, look at the following code, the change is smoother. https://gist.github.com/eyllanesc/5e79f469b82d9075d9bacb2409f410dd/archive/5a6b53acd3870c0bb61f180482780dd912d89a64.zip
comment on: http://stackoverflow.com/q/49869767
score: 0

http://stackoverflow.com/comment/86741363
type: Comment
comment on: http://stackoverflow.com/a/49863024
type: AnswerComment
score: 0
has text: thank you but I did like that and it does not working :(

http://stackoverflow.com/q/49866383
has title: How to check whether a key exist inside a nested dictionary and if yes delete
has comment: http://stackoverflow.com/comment/86748261
accepted answer: http://stackoverflow.com/a/49867117
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/49866424
possible better answer: http://stackoverflow.com/a/49866424
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49867117
has answer: http://stackoverflow.com/a/49866569
has comment: http://stackoverflow.com/comment/86748481
type: Question
has answer: http://stackoverflow.com/a/49866406
has body: I have this main_dict created and want to see if main_dict[x]["Description"] exists or not, and if yes, then delete it. Where x is 'pins', 'nails', 'board', etc ... main_dict = { 'pins': { 'Category': ['General'], 'Contact': ['Mark'], 'Description': ['This', 'is', 'a'] }, 'nails': { 'Category': ['specific'], 'Contact': ['Jon'], 'Description': ['This', 'is', 'a', 'description'] }, 'board': { 'Category': ['General'], 'Contact': ['Mark'], 'Description': ['This', 'is', 'a'] }, 'hammer': { 'Category': ['tools'], 'Contact': ['Jon'], 'Description': ['This', 'is', 'a', 'description'] } } I tried this: for x in main_dict: del main_dict[x]["Description"] This returns error if main_dict[x]["Description"] does not exist. Also this does not work: if main_dict[x]["Description"] in mainDict[x]: del main_dict[x]["Description"]

http://stackoverflow.com/comment/86534304
has text: Please post the actual stack trace.... it tells us exactly where the error is. Also, a good debug practice for python is to cut most of the clutter out in a test script to narrow down the problem. And that simplified example would be a good thing to post here.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49759618

http://stackoverflow.com/a/49784987
has body: tl;dr: struct is actually slow.. Instead of pickle use np.ndarray.tobytes() combined with np.frombuffer() to eliminate overhead. I'm not well versed in opencv, which is probably the best answer, but a drop-in approach to speeding up transfer could be to use struct to pack and unpack the data to be sent over the network instead of pickle. Here's an example of sending a numpy array of known dimensions over a socket using struct import numpy as np import socket import struct #----- server ------ conn = socket.socket() #connect socket somewhere arr = np.random.randint(0,256,(320,240,3), dtype="B") # unsigned bytes "B": camera likely returns 0-255 pixel values conn.write(struct.pack('230400B', *arr.flat)) #230400 unsigned bytes #----- client ------ conn = socket.socket() #connect socket somewhere data = conn.read(230400) #read 230400 bytes arr = np.array(struct.unpack('230400B', data), dtype='B').reshape((320,240,3),) EDIT A little digging shows numpy has a tobytes function that exposes a memory view of the data as a bytes object. This basically does the work of struct without needing the argument unpacking in the function call to encode. This prompted me to also see if we could do the unpacking too, and as long as you're okay with flying by the seat of your pants a little bit (interruptions or errors would not be caught gracefully), we can pack and unpack the data with almost zero overhead making the only limiting factor your network. testing script: arr = np.random.randint(0,256,(320,240,3), dtype="B") # unsigned bytes "B": camera likely returns 0-255 pixel values t = time() for _ in range(100): arr2 = pickle.loads(pickle.dumps(arr)) print(f'pickle pack, pickle unpack: {time()-t} sec') t = time() for _ in range(100): arr2 = np.array(struct.unpack('230400B', struct.pack('230400B', *arr.flat)), dtype='B').reshape((320,240,3),) print(f'struct pack, struct unpack: {time()-t} sec') t = time() for _ in range(100): arr2 = np.array(struct.unpack('230400B', arr.tobytes()), dtyp…
has comment: http://stackoverflow.com/comment/86586234
has comment: http://stackoverflow.com/comment/86585721
has comment: http://stackoverflow.com/comment/86625724
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86625634
downvote count: 0
has comment: http://stackoverflow.com/comment/86585671
accepted answer of: http://stackoverflow.com/q/49784551
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/86625133
type: Answer
has comment: http://stackoverflow.com/comment/86586241
answers question: http://stackoverflow.com/q/49784551
has comment: http://stackoverflow.com/comment/86625041
has comment: http://stackoverflow.com/comment/86586293
has comment: http://stackoverflow.com/comment/86625828
has comment: http://stackoverflow.com/comment/86585666

http://stackoverflow.com/q/49805576
has answer: http://stackoverflow.com/a/79214378
has comment: http://stackoverflow.com/comment/86626250
has comment: http://stackoverflow.com/comment/86626277
downvote count: 1
favorite count: 0
tagged with: quandl
type: Question
tagged with: numpy
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51056520
has answer: http://stackoverflow.com/a/51225714
has answer: http://stackoverflow.com/a/68152197
has answer: http://stackoverflow.com/a/70705423
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86626212
has comment: http://stackoverflow.com/comment/86627104
has comment: http://stackoverflow.com/comment/86626702
has comment: http://stackoverflow.com/comment/86628360
has answer: http://stackoverflow.com/a/67292263
tagged with: python
has answer: http://stackoverflow.com/a/49805801
score: 13
has answer: http://stackoverflow.com/a/70858024
answer count: 13
has answer: http://stackoverflow.com/a/72879805
has body: Trying to install quandl and need pandas, so I tried pip install pandas and get: Could not find a version that satisfies the requirement numpy==1.9.3 (from versions: 1.10.4, 1.11.0, 1.11.1rc1, 1.11.1, 1.11.2rc1, 1.11.2, 1.11.3, 1.12.0b1, 1.12.0rc1, 1.12.0rc2, 1.12.0, 1.12.1rc1, 1.12.1, 1.13.0rc1, 1.13.0rc2, 1.13.0, 1.13.1, 1.13.3, 1.14.0rc1, 1.14.0, 1.14.1, 1.14.2) No matching distribution found for numpy==1.9.3. I'm using python 3.4, win32
has title: Could not find a version that satisfies the requirement numpy == 1.9.3
has answer: http://stackoverflow.com/a/51196711
upvote count: 14
tagged with: pandas
has answer: http://stackoverflow.com/a/49836953
has comment: http://stackoverflow.com/comment/86628411
has comment: http://stackoverflow.com/comment/86626301
has answer: http://stackoverflow.com/a/49805826
has answer: http://stackoverflow.com/a/50177156
has comment: http://stackoverflow.com/comment/86628335

http://stackoverflow.com/comment/86719177
has text: how do you compare them ? if I write 'a=1st writing', 'b=2nd', then 'a==b' returns True.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49852271
type: QuestionComment

http://stackoverflow.com/a/54957675
answers question: http://stackoverflow.com/q/49853718
has body: Some example codes: from tensorflow.python.feature_column import feature_column_v2 as fc feature_layer = fc.FeatureLayer(your_feature_columns) model = tf.keras.Sequential([ feature_layer, tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dense(64, activation=tf.nn.relu), tf.keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) please refer to feature_cols_keras
score: 0
type: Answer

http://stackoverflow.com/comment/86690258
type: Comment
comment on: http://stackoverflow.com/q/49837453
score: 1
type: QuestionComment
has text: It's hard to say the "right" way to write something like this, because if we try to fix the things that don't make sense, it rapidly simplifies to `print(4)`.

http://stackoverflow.com/comment/86705741
score: 0
type: Comment
type: QuestionComment
has text: @TerryJanReedy then you don't see a fundamental problem in my code? Because that's what I thought initially
comment on: http://stackoverflow.com/q/49844907

http://stackoverflow.com/comment/86585529
comment on: http://stackoverflow.com/a/49763857
has text: Thanks Martineau. That's wow! a bit complex for me though I think I understand what you mean and the purpose of the encapsulation. I am going to remove all the `time.sleep(XX)` from my code and use after and encapsulation.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86642314
type: Comment
comment on: http://stackoverflow.com/q/49801522
score: 1
type: QuestionComment
has text: Luckily I am on a Windows machine and I managed to get MinGw to work. I could compile using `gcc -g -shared spellfix.c -I ~/sqlite-amalgation-3230100/ -o spellfix.dll`. Basically the error you get is msvc trying to find the include files in the amalgation package `sqlite3.h` and `sqlite3ext.h`. Use the `cl /I <path-to-amalgation> ext\misc\spellfix.c`... or something similar!

http://stackoverflow.com/q/49901504
score: -2
answer count: 1
accepted answer: http://stackoverflow.com/a/49901536
has title: Find key-value min number in a dictionary Python
has answer: http://stackoverflow.com/a/49901536
type: AnsweredQuestion
downvote count: 3
has body: I have this dictionary my_dict = {'x':500, 'y':5874, 'z': 560} key_min = min(my_dict.keys(), key=(lambda k: my_dict[k])) print('Minimum Value: ',my_dict[key_min]) I want to print key correspond to minimum value. How can I do that? print(my_dict.keys()[key_min])
has comment: http://stackoverflow.com/comment/86818589
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86818497
type: Question
tagged with: python

http://stackoverflow.com/comment/86667241
type: Comment
comment on: http://stackoverflow.com/a/49806631
type: AnswerComment
has text: You can loop through a list of account names and create one account for each name. You could store all those Account objects in a list named `accounts`, or in a dictionary where the keys are account names and the values are Account objects. I don't know what you mean by "calling all objects `account`" because you can have only one object with that name. If that object is some sort of container, however, you can add to it as many Account objects as you wish.
score: 0

http://stackoverflow.com/q/49783442
has title: Using Flask and Flask-SQLAlchemy, how could I change the database connection in a route?
tagged with: python
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/49797739
score: 0
type: UnansweredQuestion
answer count: 1
has body: Business case: We have multiple databases that need to be accessed and we don't know which until a URL/Route is called. The database server and database name are part of the route. example: http://&lt;flask_server&gt;/&lt;db_server&gt;/&lt;db_name&gt;/weeklyreport Since standard Flask-SQLAlchemy uses APP settings to define the DB connection and APP settings cannot (should not) be changed at runtime... how could one accomplish this?
tagged with: flask
tagged with: flask-sqlalchemy

http://stackoverflow.com/comment/86631671
has text: That is exactly what I needed! The only component I'm missing is how to add a title to the bar plot produced ?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49808296

http://stackoverflow.com/comment/86817936
comment on: http://stackoverflow.com/a/49900723
type: Comment
has text: I'm testing your code and it seems that the scan doesn't start processing until the source is completed. That's a main issue, scan should start in the moment the first value is emmited. I think that requirement is well defined in the marble diagram (let me know if it's confusing, thanks).
score: 0
type: AnswerComment

http://stackoverflow.com/a/49903532
type: Answer
answers question: http://stackoverflow.com/q/49903319
score: 1
has body: With math.ceil: from math import ceil def pad(l, n): return n*ceil(l/n) - l assert pad(59, 10) == 1 assert pad(60, 10) == 0 assert pad(61, 10) == 9
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86822719

http://stackoverflow.com/comment/86803166
comment on: http://stackoverflow.com/a/49893701
score: 0
has text: In that post he's killing the process. You may go for it ! But for that you should have admin privilege
type: Comment
type: AnswerComment

qt
tags question: http://stackoverflow.com/q/49760789
tags question: http://stackoverflow.com/q/49870499
tags question: http://stackoverflow.com/q/49775703
tags question: http://stackoverflow.com/q/49852012
type: Tag
tags question: http://stackoverflow.com/q/49761055
tags question: http://stackoverflow.com/q/49840304
tags question: http://stackoverflow.com/q/49799080
tags question: http://stackoverflow.com/q/49773685
tags question: http://stackoverflow.com/q/49813237
tags question: http://stackoverflow.com/q/49777812
tags question: http://stackoverflow.com/q/49854556
tags question: http://stackoverflow.com/q/49869767
tags question: http://stackoverflow.com/q/49777682
tags question: http://stackoverflow.com/q/49902533
tag name: qt
tags question: http://stackoverflow.com/q/49782429

http://stackoverflow.com/q/49865446
has body: I've a simple MNIST which I've successfully saved, being the code the next: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import tensorflow as tf sess = tf.InteractiveSession() tf_save_file = './mnist-to-save-saved' x = tf.placeholder(tf.float32, shape=[None, 784]) y_ = tf.placeholder(tf.float32, shape=[None, 10]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) y = tf.matmul(x, W) + b cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y)) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) saver.save(sess, tf_save_file) for _ in range(1000): batch = mnist.train.next_batch(100) train_step.run(feed_dict={x: batch[0], y_: batch[1]}) correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) saver.save(sess, tf_save_file, global_step=1000) print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})) Then, the next files are generated: checkpoint mnist-to-save-saved-1000.data-00000-of-00001 mnist-to-save-saved-1000.index mnist-to-save-saved-1000.meta mnist-to-save-saved.data-00000-of-00001 mnist-to-save-saved.index mnist-to-save-saved.meta Now, in order to use it in production (and so, for example, pass it a number image), I want to be able to execute the trained model by passing it any number image to make the prediction (I mean, not deploying yet a server but making this prediction "locally", having in the same directory that "fixed" number image, so using the model would be like when you run an executable). But, considering the (mid-low?) API level of my code, I'm confused about what would be the easiest correct next step (if restoring, using an Estimator, etc...), and how to do it. Although I've read the official documentation, I insist that they seem …
score: 0
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49866245
tagged with: tensorflow
type: Question
has title: Understanding next step after saving TensorFlow model
tagged with: mnist
has answer: http://stackoverflow.com/a/49865749
tagged with: python

http://stackoverflow.com/q/49845706
type: UnansweredQuestion
score: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/86738777
linked to: http://stackoverflow.com/q/48482483
tagged with: conv-neural-network
has title: Keras: ValueError: Dimension 0 in both shapes must be equal (VGGNets)
tagged with: python
has body: I am following a tutorial and I charged a VGGNet16 pre-trained model using Keras vgg16_model = keras.applications.vgg16.VGG16() model = Sequential() for layer in vgg16_model.layers: model.add(layer) model.layers.pop() for layer in model.layers: layer.trainable = False model.add(Dense(10, activation='softmax', name='predict')) #model.summary() I used model.save('path/model_1.h5') to save the model after of training it with model.fit_generator(...) Then I ran out of time in Colaboratory. So I wanted to use model = load_model('path/model_1.h5') to load again my model instead of loading the model again with vgg16_model = keras.applications.vgg16.VGG16()... And now I am getting this error: ValueError: Dimension 0 in both shapes must be equal, but are 4096 and 1000. Shapes are [4096,10] and [1000,10]. for 'Assign_61' (op: 'Assign') with input shapes: [4096,10], [1000,10]. What am I missing? Than you!
favorite count: 0
type: Question
answer count: 0
downvote count: 0
upvote count: 1
tagged with: machine-learning

http://stackoverflow.com/comment/86750447
type: AnswerComment
has text: Thanks. I guessed this wasn't officially supported. I got some simple examples working by linking against the pyrap_internal library for TF 1.6. I haven't run any decent tests on this yet, but I won't invest too much effort into debugging any problems that come up.
type: Comment
comment on: http://stackoverflow.com/a/49848294
score: 0

http://stackoverflow.com/q/49774630
has answer: http://stackoverflow.com/a/49774849
has answer: http://stackoverflow.com/a/49774745
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/86564124
has body: I have another beginner question where I cant find a solution by my own, especially because I may name things wrong. I have two python files. And I need to do this: File one: def Main(): def whatever(a,b): #do whatever Second file: Import Main Main.whatever(str a, str b) How do I do that?
tagged with: python
has comment: http://stackoverflow.com/comment/86564251
tagged with: import
has comment: http://stackoverflow.com/comment/86564123
answer count: 3
has answer: http://stackoverflow.com/a/49774860
has title: Python use Function of a Function inside another File
tagged with: function
downvote count: 3
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86753384
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49868576
has text: Ok will look into it. Cheers

http://stackoverflow.com/comment/86556269
score: 0
type: Comment
type: QuestionComment
has text: okay, are you aware of any other alternatives?
comment on: http://stackoverflow.com/q/49770113

http://stackoverflow.com/comment/86710306
has text: @jpp I added a bit more info to my answer. But yeah in general, if you aren't sure I'd say check, and don't rely on it being the case. AFAIK there isn't some characterization for all the free functions that behave like this.
score: 1
comment on: http://stackoverflow.com/a/49846698
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49787553
has comment: http://stackoverflow.com/comment/86614739
tagged with: list
answer count: 0
score: 1
has body: I have a 2D list similar to this (but much larger): data = [[ 1. data. data. data. ] [ 2. data. data. data. ] [ 3. data. data. data. ] [ 4. data. data. data. ] [ 1. data. data. data. ] [ 2. data. data. data. ] [ 3. data. data. data. ] [ 4. data. data. data. ] [ 1. data. data. data. ] [ 2. data. data. data. ] [ 3. data. data. data. ] [ 4. data. data. data. ] [ 1. data. data. data. ] [ 2. data. data. data. ] [ 3. data. data. data. ] [ 4. data. data. data. ]] And a reference list similar to this: reff = [X, Y, X, Y, Y, Y, Y, X, Y] Along with this, I have a list of indices similar to this: idxs = [i for i, x in enumerate(reff) if x == "X"] I used this to get a smaller 2D list: smaller_data = [data[I] for i in idxs] Within this smaller_data, I want to search the columns for consistent values (above a threshold) and then remove all of those instances from the original 2D list. For example if it is determined that in the third index of every inner-list (Essentially the entire fourth column of smaller_data) has the same value XYZ appearing at least 65% of the time, then I want to delete all instances (rows) of in data where the third index (fourth column) has a value of XYZ. This is the code I have: thresh = 0.65 to_remove = [] transposed = [list(i) for i in zip(*smaller_data)] col_idx = [] col_id = 0 for col in transposed: unique = set(col) for val in unique: freq = float(col.count(val))/float(len(col)) if freq &gt; threshold: to_remove.append(val) col_idx.append(col_id) col_id += 1 for row in data: for idx in col_idx: if row[idx] == to_remove[idx]: data.remove(row) return data This doesn't seem to work. I get a list index out of range error for the line if row[idx] == to_remove[idx]. I am unsure as to how to go about this. What am I missing?
favorite count: 0
type: Question
tagged with: nested-lists
has title: Delete row instances if column instance appears in the majority
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/86661541
has text: Please include the code you've attempted so far, show the output or if there is an error include the full traceback, and show what the desired output is for this input.
comment on: http://stackoverflow.com/q/49822857
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/86679067
type: Comment
has text: @AbhijitGhate That seems to be a different problem than the one in your question.
comment on: http://stackoverflow.com/a/49831251
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86777338
comment on: http://stackoverflow.com/q/49880743
type: QuestionComment
has text: Look at the [`zip`](https://docs.python.org/3/library/functions.html#zip) function.
type: Comment
score: 0

http://stackoverflow.com/a/50083558
answers question: http://stackoverflow.com/q/49829286
type: Answer
has body: For what it's worth - I ended up making the following function(s) to achieve what I wanted (requires math module): def convert(d): if isinstance(d,dict): yield {k:v for k,v in dict_convert(d)} elif isinstance(d,list): yield list_convert(d) else: yield d def list_convert(d): return [math.nan if i is None else i for i in d] def dict_convert(d): for key, value in d.items(): yield key, [i for i in convert(value)][0] #d_in = JSON data, containing nulls #d_out = JSON data, with null converted to nan d_out = [i for i in test_opennem.convert(d_in)][0] Seemed to work for any d_in JSON structure for me, (no matter how many nested components)... Though not widely tested, and probably not suit all cases etc. Also only converts null values in a list to NaN, (not dictionary keys or other strings to NaN) - which was also fine in my case.
score: 0

http://stackoverflow.com/comment/86659180
score: 0
has text: Thanks, I've put up examples of more lines. I can send the file if it is better
comment on: http://stackoverflow.com/q/49820691
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49764125
accepted answer: http://stackoverflow.com/a/49948090
has answer: http://stackoverflow.com/a/56131699
has answer: http://stackoverflow.com/a/50009470
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86551826
tagged with: python
has answer: http://stackoverflow.com/a/57827295
answer count: 4
has comment: http://stackoverflow.com/comment/94961287
tagged with: reticulate
tagged with: http://stackoverflow.com/tag/r
score: 9
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49948090
downvote count: 0
has comment: http://stackoverflow.com/comment/86564241
has body: I just started using the reticulate package in R, and I'm still getting a few of the kinks figured out. In particular, importing matplotlib is not going well. I've tried it two different ways, with different error messages for each. First, using repl_python in RStudio's interactive shell: library(reticulate) use_python('/home/craig/anaconda3/bin/python') py_discover_config() repl_python() import matplotlib.pyplot as plt The REPL Python shell that opens up seems to have the correct version and everything, but when I try to import matplotlib.pyplot, I see the following: ImportError: /lib/x86_64-linux-gnu/libz.so.1: version `ZLIB_1.2.9' not found (required by /home/craig/anaconda3/lib/python3.6/site-packages/matplotlib/../../.././libpng16.so.16) Installing zlib (using sudo apt-get install lib64z1-dev lib64z1) didn't seem to change anything. FWIW, import matplotlib worked just fine, as long as I don't need pyplot. I also tried doing the same thing in an R Markdown document: ```{r} library(reticulate) py_discover_config() ``` ```{python} import matplotlib.pyplot as plt ``` This time I saw: Error in py_get_attr_impl(x, name, silent): AtributeError: module 'matplotlib' has no attribute 'pyplot' Calls: ... $.python.builtin.object -> py_get_attr -> py_get_attr_impl -> .Call Execution halted Any ideas what might be going on here? Thanks! UPDATE: As I mentioned in the comments, installing the developer version of reticulate fixes some of the problems, but not all. If I try to run this Rmd: ```{r} library(reticulate) use_python('/home/craig/anaconda3/bin/python') ``` ```{python} import matplotlib.pyplot as plt ``` I get the following error messages: Error in py_run_string_impl(code, local, convert) : ImportError: /home/craig/anaconda3/lib/python3.6/site-packages/PyQt5/../../../libxcb-dri3.so.0: undefined symbol: xcb_send_request_with_fds Detailed traceback: File "&lt;string&gt;", line 1, in &lt;module&gt; File "/home/craig/anaconda3/lib/python3.6/site-packages/matplotlib/pyplot…
linked to: http://stackoverflow.com/q/48306849
has comment: http://stackoverflow.com/comment/86610892
favorite count: 0
type: Question
upvote count: 9
has comment: http://stackoverflow.com/comment/86586635
has title: Importing matplotlib with reticulate in R
possible better answer: http://stackoverflow.com/a/50009470
has comment: http://stackoverflow.com/comment/87030440

http://stackoverflow.com/a/49903966
has body: Here's a vectorized approach based upon searchsorted - # Get sorted index positions idx = np.searchsorted(rows, test) # Set out-of-bounds(invalid ones) to some dummy index, say 0 idx[idx==len(rows)] = 0 # Get invalid mask array found out by indexing data array # with those indices and looking for matches invalid_mask = rows[idx] != test # Get data indexed array as output and set invalid places with 0s out = data[idx] out[invalid_mask] = 0 Last couple of lines could have two alternatives, if you dig one-liners - out = data[idx] * (rows[idx] == test) # skips using `invalid_mask` out = np.where(invalid_mask, 0, data[idx])
accepted answer of: http://stackoverflow.com/q/49903830
type: Answer
answers question: http://stackoverflow.com/q/49903830
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49857893
score: 0
answers question: http://stackoverflow.com/q/49857856
type: Answer
has body: You can use in to check if key in dict. Ex: sc={'sen': 1,'lag': 1 } if "tep" in sc: print("1") else: print("0") or if one line use dict.get. Ex: print(sc.get("tep", "0"))

http://stackoverflow.com/q/49909573
answer count: 1
has body: I intend to create a method to slice a list, however I don't have the correct syntax here, and I haven't been able to come up with the correct search query to find out how to do this: class BarList(list): """Items in the list are always in ascending order of .date""" def trim(self, start:dt.datetime=None, end:dt.datetime=None): """Removes all bars before `start` and after `end`""" if start: for i, bar in enumerate(self): if bar.date &gt;= start: self = self[i:] break What's the proper way to do what I'm trying to express in the above pseudocode?
type: AnsweredQuestion
has title: What's the proper way to slice `self` within a method of a List subclass?
accepted answer: http://stackoverflow.com/a/49909849
has answer: http://stackoverflow.com/a/49909849
tagged with: python
tagged with: slice
type: Question
score: 0
tagged with: list

http://stackoverflow.com/q/49864298
tagged with: matplotlib
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/86744723
has body: Basically I am using matplotlib to generate charts that I want to then display directly to the user. The user fills out a form and the variables are passed to a few methods that create the chart. The code I currently have will show only the image and get rid of the form. Is it possible to display the image on the page so that the user can modify the queries/connections and see the results with each subsequent form submission? Here is my code: from flask import Flask, request, render_template, send_file, redirect, url_for import flask import MultipleDatabasesLib as mdl import subprocess import pandas as pd import matplotlib as plt from matplotlib import pyplot as plt app = Flask(__name__) xlabel = "" ylabel = "" graph_title = "" @app.route('/') def my_form(): return render_template('my-form.html') @app.route('/get_form_vals', methods=['POST', 'GET']) def form_vals(): df = pd.DataFrame() df_group = pd.DataFrame() fig_size = plt.rcParams["figure.figsize"] fig_size[0] = 15 fig_size[1] = 12 plt.rcParams["figure.figsize"] = fig_size base = "C:/Python36-32/GraphFactory/Final_csv.csv" conn1 = flask.request.args.get('conn1') conn2 = flask.request.args.get('conn2') sql1 = flask.request.args.get('sql1') sql2 = flask.request.args.get('sql2') charttype = flask.request.args.get('charttype') xlabel = flask.request.args.get('xLabel') ylabel = flask.request.args.get('yLabel') groupBy = flask.request.args.get('groupBy') #graph_title = charttype + "Chart" mdl.gen_csv(conn1, conn2, sql1, sql2) df = pd.read_csv(base) df_group = df.groupby(['YR', 'INSTANCE']).size() if charttype == "bar": mdl.bar_plot(xlabel, ylabel, 'Plot', df_group) elif charttype == "pie": mdl.pie_plot(xlabel, ylabel, 'Plot', df_group) elif charttype == "line": mdl.line_plot(xlabel, ylabel, 'Plot', df_group) elif charttype == "hist": mdl.hist_plot(xlabel, ylabel, 'Plot', df_group) #return send_file("plt.png", mimetype='image/gif') return flask.jsonify({"result":" "}) app.run(host='0.0.0.0', port=33) HTML: Graph Factor…
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86749819
has comment: http://stackoverflow.com/comment/86749846
answer count: 1
tagged with: web
has comment: http://stackoverflow.com/comment/86744549
upvote count: 1
has comment: http://stackoverflow.com/comment/86744605
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49864558
has comment: http://stackoverflow.com/comment/86744153
has title: How do I use Flask to show a generated matplotlib image on the same screen as the form?
has answer: http://stackoverflow.com/a/49864558

http://stackoverflow.com/a/76894105
score: 2
upvote count: 2
downvote count: 0
has body: Matt's Answer works. However I wanted to run from calling_notebook.ipynb the other called_notebook.ipynb and transfer data frame from called_notebook to calling_notebook WITHOUT displaying any of the output. I tried many options all did not work (tags etc). However this below worked (suppressed all output in called_notebook.ipynb). # to suppress output of the cell %%capture %run -n ./called_notebook.ipynb df = DFF() # function in called_notebook that returns a dataframe after doing all work df.info()
has comment: http://stackoverflow.com/comment/137932770
has comment: http://stackoverflow.com/comment/137777321
answers question: http://stackoverflow.com/q/49817409
type: Answer
has comment: http://stackoverflow.com/comment/137932807

http://stackoverflow.com/comment/104423331
type: QuestionComment
has text: The matter was Internet Explorer %)
score: 0
comment on: http://stackoverflow.com/q/49863561
type: Comment

http://stackoverflow.com/q/49817284
has comment: http://stackoverflow.com/comment/86649994
has comment: http://stackoverflow.com/comment/86656227
has comment: http://stackoverflow.com/comment/86651314
has title: Create 3 environments of Python 3 in Anaconda on offline mode
has comment: http://stackoverflow.com/comment/86649153
has comment: http://stackoverflow.com/comment/86658410
linked to: http://stackoverflow.com/q/49777621
upvote count: 3
linked to: http://stackoverflow.com/q/41577527
has comment: http://stackoverflow.com/comment/86657018
tagged with: anaconda
has comment: http://stackoverflow.com/comment/86649717
score: 1
has comment: http://stackoverflow.com/comment/86651436
has comment: http://stackoverflow.com/comment/86651366
tagged with: python
has comment: http://stackoverflow.com/comment/86651192
has body: In this guide of Conda, they explain how to setup different version of Python within Anaconda by creating different environment. so I proceed to create 3 environments: Python 3.4 Python 3.5 and Python 3.6. I setup the last version of Conda 4.4.10 (2018-02-09) What I've done: python 3.6 $conda create -n py36 python=3.6 anaconda --offline Solving environment: done Package Plan environment location: /opt/Anaconda/Anaconda3-5.1.0/envs/py36 added / updated specs: - anaconda - python=3.6 The following NEW packages will be INSTALLED: alabaster: 0.7.10-py36h306e16b_0 anaconda: 5.1.0-py36_2 .................OTHERs PKGS....................... Proceed ([y]/n)? y Preparing transaction: done Verifying transaction: done Executing transaction: done # # To activate this environment, use: # &gt; source activate py36 # # To deactivate an active environment, use: # &gt; source deactivate here we can see that I succefually create a py36 environment: $conda env list # conda environments: # base * /opt/Anaconda/Anaconda3-5.1.0 py36 /opt/Anaconda/Anaconda3-5.1.0/envs/py36 Python 3.5: $conda create -n py35 python=3.5 anaconda --offline Solving environment: failed PackagesNotFoundError: The following packages are not available from current channels: - python=3.5 Current channels: - https://repo.continuum.io/pkgs/main/linux-64 - https://repo.continuum.io/pkgs/main/noarch - https://repo.continuum.io/pkgs/free/linux-64 - https://repo.continuum.io/pkgs/free/noarch - https://repo.continuum.io/pkgs/r/linux-64 - https://repo.continuum.io/pkgs/r/noarch - https://repo.continuum.io/pkgs/pro/linux-64 - https://repo.continuum.io/pkgs/pro/noarch When I checked out the Python version I have, I get: $conda search python --offline Loading channels: done Name Version Build Channel python 3.3.0 3 defaults python 3.3.0 4 defaults python 3.3.0 pro0 defaults python 3.3.0 pro1 defaults python 3.3.1 0 defaults python 3.3.2 0 defaults python 3.3.2 1 defaults .....................ALL Versions between...............…
has comment: http://stackoverflow.com/comment/86653007
tagged with: conda
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86649388
downvote count: 2
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86659064

http://stackoverflow.com/q/49912163
has answer: http://stackoverflow.com/a/49926294
tagged with: visual-studio-code
has body: I have added a module within the extraPath options (/Applications/Autodesk/maya2018/devkit/other/pymel/extras/completion/py). It takes too long, because is a very long module, so I would like to know if there is any way to add that module into the preLoaded modules options, to improve the autocomplete time. Thanks!!
type: UnansweredQuestion
score: 0
answer count: 1
tagged with: python
has title: VsCode - Add Preloaded module from extraPath
type: Question

http://stackoverflow.com/q/49763571
tagged with: python
tagged with: flask
tagged with: flask-sqlalchemy
has body: I use a simple stack of Python (3.6.4), Flask (0.12.2), flask_admin (1.5.1) and flask_sqlalchemy (2.3.2). I chose SQLite as my DB. The structure of my project is rather simple: 1) shared_db.py from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() 2) models.py from shared_db import db class City(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) def fill_data(app): with app.app_context(): db.create_all() db.session.add(City(name="Moscow")) db.session.add(City(name="New York")) db.session.add(City(name="London")) db.session.add(City(name="Paris")) db.session.commit() 3) model_views.py from flask_admin.contrib.sqla import ModelView from models import City class CityView(ModelView): column_display_pk = True # to force ids to appear in the Admin panel column_hide_backrefs = False column_list = ("id", "name") def create_views(admin, db): admin.add_view(CityView(City, db.session)) 4) app.py import os from flask_admin import Admin from flask import Flask, jsonify, make_response, request from shared_db import db from models import fill_data from model_views import create_views app = Flask(__name__) app.config["SECRET_KEY"] = "123456790" app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////&lt;path to the project&gt;/myDB' app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(app) fill_data(app) admin = Admin(app, 'My app') create_views(admin, db) if __name__ == "__main__": port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True) Finally, I delete the myDB-file if it exists and I run the app with python3 app.py. Surprisingly, eventually, I got 8 cities instead of 4! I perform some debug with DB Browser and find out that duplicated 4 cities creates right after the very last line of code - app.run(...) - executes. How do I run the flask app correctly with a pre-filled database?
accepted answer: http://stackoverflow.com/a/49764263
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49764263
has title: Flask app.run creates entity duplicates?
tagged with: sqlite
linked to: http://stackoverflow.com/q/25504149
linked to: http://stackoverflow.com/q/2546207
favorite count: 0
type: Question
upvote count: 2
duplicate of: http://stackoverflow.com/q/25504149
duplicate of: http://stackoverflow.com/q/2546207
tagged with: flask-admin
downvote count: 0
answer count: 1

http://stackoverflow.com/a/49812711
downvote count: 0
upvote count: 1
score: 1
has body: age is the static class variable You can directly access the age variable using Class name &gt;&gt;ClassTester.age=20 &gt;&gt;ClassTester.age &gt;&gt;20 Static class variables in Python
has comment: http://stackoverflow.com/comment/86640025
type: Answer
answers question: http://stackoverflow.com/q/49812261
has comment: http://stackoverflow.com/comment/86640237

http://stackoverflow.com/q/49797743
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49798145
has comment: http://stackoverflow.com/comment/86611252
linked to: http://stackoverflow.com/q/68282
answer count: 1
tagged with: frame
tagged with: image
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86612039
type: Question
tagged with: tkinter
has body: I have created a python class which inherits Tk from tkinter library. I want to add a label with an image to it but it only works when I create a Photoimage as variable to 'self'. This code works: class HMIDrawer(Tk): def __init__(self): super().__init__() self.frame = Frame(self) self.img = PhotoImage(file='resources/platoontomtom_empty.png') self.label = Label(self.frame, image=self.img, bg='white') self.label.pack() self.frame.pack() self.mainloop() And this code doesn't work: class HMIDrawer(Tk): def __init__(self): super().__init__() self.frame = Frame(self) img = PhotoImage(file='resources/platoontomtom_empty.png') self.label = Label(self.frame, image=img, bg='white') self.label.pack() self.frame.pack() self.mainloop() Can anyone explain why the first code does work and the second code doesn't?
accepted answer: http://stackoverflow.com/a/49798145
has comment: http://stackoverflow.com/comment/86610075
upvote count: 1
tagged with: python
tagged with: label
has title: Why doesn't a local name with a PhotoImage object work, for a tkinter label image?

http://stackoverflow.com/comment/86540654
score: 0
comment on: http://stackoverflow.com/q/49762550
type: Comment
type: QuestionComment
has text: The best solution for this job would be using XSLT. There [are many XML to CSV solutions](https://stackoverflow.com/search?q=%5Bxslt%5D+XML+to+CSV) here on SO.

http://stackoverflow.com/a/49877797
type: Answer
answers question: http://stackoverflow.com/q/49877595
has comment: http://stackoverflow.com/comment/86771255
score: 0
has body: No. This solution is not in place. Two new objects (lists) are created, which you continually appended to according to the logic you have specified. As far as I am aware, you cannot get an in-place view of your data using only the standard library. If an in place solution is important to you, you can use a 3rd party library such as numpy. If an O(n) solution is important, you should use a generator or list.append in a for loop to 2 lists.
has comment: http://stackoverflow.com/comment/86771350

http://stackoverflow.com/q/49887257
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/44838538
has title: Overcoming a StaleElementReferenceException in python?
tagged with: selenium
downvote count: 0
score: 1
upvote count: 1
tagged with: webdriver
has comment: http://stackoverflow.com/comment/86811806
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86821666
tagged with: staleelementreferenceexception
type: Question
has comment: http://stackoverflow.com/comment/86821655
has comment: http://stackoverflow.com/comment/86793272
answer count: 0
has body: Intention: My aim is to scrape football data from whoscored.com. Match pages (see example here) contain a timeline view (div id = match-centre-timeline) which has timeline handles in turn (div class = timeline-handle). The handles can be dragged and dropped so to set the timeline to show the match stats for. For example, I'd like to set the lower timeline bound to represent 10 minutes and the upper to represent 30 minutes. Setup &amp; Hypothesis: I'm using selenium with chrome on OSX 10. The code below moves the lower timeline handle but throws a StaleElementReferenceException. My belief is that the page application becomes confused by the sudden drag and drop. Question: Is there any way to simulate a slower mouse drag? Is this even the problem? How can this be overcome? Thanks in advance! Python 3 code: url = "https://www.whoscored.com/Matches/1190514/Live" time_to_wait = 20 wanted_element_id = "match-centre-timeline" opts = ChromeOptions() opts.add_experimental_option("detach", True) opts.add_argument("disable-infobars") opts.add_argument("disable-notifications") driver = webdriver.Chrome(executable_path="/Users/david/Dropbox/Code/gitCode/driver/chromedriver", chrome_options=opts) driver.set_page_load_timeout(time_to_wait) example_loaded = bool(True) while example_loaded: try: driver.get(url) WebDriverWait(driver,time_to_wait).until(EC.presence_of_element_located((By.ID, wanted_element_id))) print("[STATUS]\tFound " + wanted_element_id + ".") example_loaded= False except TimeoutException: print("[WARNING]\tCannot find the " + wanted_element_id + ". Retrying.") tlh = driver.find_element_by_xpath("//*[@id='match-centre-timeline']/div[1]/div[2]/div[2]/div[2]/div[1]/span") tuh = driver.find_element_by_xpath("//*[@id='match-centre-timeline']/div[1]/div[2]/div[2]/div[2]/div[2]/span") driver.execute_script("arguments[0].scrollIntoView();", tlh) actions = ActionChains(driver) # move to the lower timeline handle actions.move_to_element(tlh) actions.perform() print("[NOTE]\…
tagged with: python

http://stackoverflow.com/a/61882344
score: -1
answers question: http://stackoverflow.com/q/49889404
upvote count: 0
type: Answer
has body: After a lot of research, I found the solution for installing fbprophet on windows 10. Step 1: Check the kernel in jupyter. Locate the folder \jupyter\kernels\python3 and check the python exe location used by the kernel. Mine was pointing to - Programs\Python\Python37\python.exe open CMD prompt and go to above dir. I am skipping pystan installation as I already installed pystan using pip command. Step 2 : Download the file "Twisted-20.3.0-cp37-cp37m-win_amd64.whl" from https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted python -m pip install /Twisted-20.3.0-cp37-cp37m-win_amd64.whl Step 3 : pip install fbprophet Installing collected packages: fbprophet Successfully installed fbprophet-0.6 Step 4 : python import fbprophet fbprophet.version '0.6'
has comment: http://stackoverflow.com/comment/109452515
downvote count: 1

http://stackoverflow.com/a/49842233
score: 0
has body: You've already done most of the work in your last paragraph. There are a few ways of doing this: Naïve for loop: objects = [] for index in range(1, 9): size = input("Size: ") weight = input("Weight: ") shape = input("Shape: ") objects.append(["Object" + str(index), size, weight, shape]) Nested for loop: names = ["Size", "Weight", "Shape"] objects = [] for index in range(1, 9): object = ["Object" + str(index)] for name in names: object.append(input(name + ": ")) Nested list comprehension names = ["Size", "Weight", "Shape"] objects = [ ["Object" + str(index)] + [ input(name + ": ") for name in names ] for index in range(1, 9) ] You can see that each version is based on the last. A list comprehension is a neat way of building a list; you may or may not have come across it before.
has comment: http://stackoverflow.com/comment/86699281
has comment: http://stackoverflow.com/comment/86699253
type: Answer
answers question: http://stackoverflow.com/q/49842027

http://stackoverflow.com/q/49909224
has comment: http://stackoverflow.com/comment/86855462
score: 4
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86853610
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/49924911
has body: I have a Django Rest API and then, separately, a client that consume this API. I pass a custom header using requests in the client: r = requests.get(url, params=params, headers={'license': '12345'}) Then in API, in my custom permission, I get the header like: app_license = request.META['HTTP_LICENSE'] I know django rewrites the custom headers for security reasons, so it works fine. My problem is when I write the unittests in Django rest API: response = self.client.get(self.url, params=params, headers={'license': '12345'}) Then it raise: KeyError: 'HTTP_LICENSE' But if I change the code like this, the test passes without problem but the consumer doesn't work: request.META['headers']['license'] I can check if there is 'headers' key or not but I don't want to change the code only to pass the unittest, it must be some way to write a unittest that matches reality, right? I tried to use: from django.test import TestCase And: from rest_framework.test import APITestCase Both with same result. There is any solution? Thank you!
favorite count: 0
has answer: http://stackoverflow.com/a/49924911
tagged with: rest
has comment: http://stackoverflow.com/comment/86834401
type: Question
downvote count: 0
tagged with: django
tagged with: python
answer count: 1
has title: Django rest framework: custom headers are different in client than unittests

http://stackoverflow.com/a/49840381
upvote count: 16
score: 16
has body: Change: plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral) to: plt.scatter(X[0, :], X[1, :], c=y.ravel().tolist(), cmap=plt.cm.Spectral) This flattens the array y to be one-dimensional, and then turns it into a list, which to_rgba is happy to digest as something it can hash. Coursera Deep Learning students: You'll likely find the offending line(s) of code in one of the *util*.py files. Look for scatter in the traceback to get the filename. I saw this question raised about 8 times on the forum. Please upvote both question and answer if they've been useful.
has comment: http://stackoverflow.com/comment/92499352
answers question: http://stackoverflow.com/q/49840380
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86717005
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49850924
has text: Anytime my friend!
score: 1

http://stackoverflow.com/a/49861759
has body: (Updated answer based on comments and subsequent testing.) The actual answer to your question how to make sure that, if we have 1 million rows, the query ... is optimized so that the 1st condition (CPU-expensive) is only tested if the easy-to-test second condition is already True? depends on the actual conditions in the WHERE clause, and how clever the SQLite query optimizer is in estimating the cost of those conditions. A simple test should tell you whether your query would be sufficiently "optimized" for your needs. The good news is that SQLite will perform the easy (inexpensive) condition first, at least under certain circumstances. For a test table "mytable" CREATE TABLE mytable ( description TEXT(50) NOT NULL, column2 INTEGER NOT NULL, CONSTRAINT mytable_PK PRIMARY KEY (column2) ); containing a million rows description column2 ----------- ------- row000000 0 row000001 1 row000002 2 ... row999999 999999 the Python test code import sqlite3 import time log_file_spec = r'C:\Users\Gord\Desktop\log_file.txt' def myfunc(thing): with open(log_file_spec, 'a') as log: log.write('HODOR\n') return(int(thing[-6:])) with open(log_file_spec, 'w'): pass # just empty the file cnxn = sqlite3.connect(r'C:\__tmp\SQLite\test.sqlite') cnxn.create_function("myfunction", 1, myfunc) crsr = cnxn.cursor() t0 = time.time() sql = """\ SELECT COUNT(*) AS n FROM mytable WHERE myfunction(description) &lt; 500 AND column2 &lt; 1000 """ crsr.execute(sql) num_rows = crsr.fetchone()[0] print(f"{num_rows} rows found in {(time.time() - t0):.1f} seconds") cnxn.close() returns 500 rows found in 1.2 seconds and counting the lines in log_file.txt we see C:\Users\Gord&gt;find /C "HODOR" Desktop\log_file.txt ---------- DESKTOP\LOG_FILE.TXT: 1000 indicating that our function was only called one thousand times, not one million times. SQLite has clearly applied the column2 &lt; 1000 first, and then applied the myfunction(description) &lt; 500 condition on the subset of rows from the first condition. (Origin…
has comment: http://stackoverflow.com/comment/86741687
has comment: http://stackoverflow.com/comment/86744836
has comment: http://stackoverflow.com/comment/86742444
has comment: http://stackoverflow.com/comment/86740041
score: 2
has comment: http://stackoverflow.com/comment/86787860
upvote count: 2
has comment: http://stackoverflow.com/comment/86739543
answers question: http://stackoverflow.com/q/49861513
has comment: http://stackoverflow.com/comment/86772704
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86739896
has comment: http://stackoverflow.com/comment/86745184
accepted answer of: http://stackoverflow.com/q/49861513
has comment: http://stackoverflow.com/comment/86741542
type: Answer

http://stackoverflow.com/q/49895663
type: Question
accepted answer: http://stackoverflow.com/a/49895765
has comment: http://stackoverflow.com/comment/86806781
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49895765
has title: How to shift values using pandas in python dataframe?
tagged with: numpy
possible better answer: http://stackoverflow.com/a/49896616
linked to: http://stackoverflow.com/q/10982089
has body: I have a dataframe like this, d = {'ID': ["A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F"], 'value': [23, 23, 52, 52, 36, 36, 46, 46, 9, 9, 110, 110]} df = pd.DataFrame(data=d) ID value 0 A 23 1 A 23 2 B 52 3 B 52 4 C 36 5 C 36 6 D 46 7 D 46 8 E 9 9 E 9 10 F 110 11 F 110 Basically, I replicate original data set(n rows). The dataframe I want to get seems like this, ID value 0 A 23 1 B 23 2 B 52 3 C 52 4 C 36 5 D 36 6 D 46 7 E 46 8 E 9 9 F 9 Move column of value one unit down and remain all pairs of values. So, I lost first of A, last of F and last two value 110. Finally, I have 2n-2 rows.
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49896616
answer count: 3
downvote count: 0
upvote count: 1
score: 1
duplicate of: http://stackoverflow.com/q/10982089
favorite count: 0
has answer: http://stackoverflow.com/a/49895788

http://stackoverflow.com/comment/86724263
comment on: http://stackoverflow.com/q/49853626
type: QuestionComment
score: 0
has text: @MaxU I have modified the question
type: Comment

http://stackoverflow.com/a/49772261
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49772087
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86560092
answers question: http://stackoverflow.com/q/49772087
has body: It sounds like you need to override the label_to_instance method of ModelChoiceField. from django import forms class ScientificNameChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.getScientifName() Then use your custom field in your form. class ScientifNameForm(forms.Form): scientifName = ScientificNameChoiceField( queryset=Referencebank.objects.all(), help_text="Select the bacteria", label='Scientific Name', )
type: Answer
has comment: http://stackoverflow.com/comment/86559994
has comment: http://stackoverflow.com/comment/86562752

http://stackoverflow.com/comment/86598987
score: 3
comment on: http://stackoverflow.com/q/49792265
type: Comment
type: QuestionComment
has text: You can't have multiple keys which are the same thing. See your first and third key.

http://stackoverflow.com/comment/86590922
has text: Sort after calling `list(set(...))`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49787852
score: 1

http://stackoverflow.com/q/49808801
accepted answer: http://stackoverflow.com/a/49808880
has comment: http://stackoverflow.com/comment/86632432
score: -6
favorite count: 0
type: Question
has title: Removing a substring from a string in python
possible better answer: http://stackoverflow.com/a/49808855
upvote count: 0
has comment: http://stackoverflow.com/comment/86632580
tagged with: python
tagged with: regex
has body: import string def remove_all(substr, str): index = 0 length = len(substr) while string.find(str, substr) != -1: index = string.find(str, substr) str = str[0:index] + str[index+length:] return str s = "ABC_Y6N02.20.0025D_BF3DAC.tgz.bin" print(s) s = remove_all(r'_bf3dac',s.lower()) print(s) The output of this program is ABC_Y6N02.20.0025D_BF3DAC.tgz.bin abc_y6n02.20.0025d.tgz.bin I want to drop the d from 0025d as well. Or basically I want to drop the last letter from before .tgz.bin how do I do this? Basically I want the output to be abc_y6n02.20.0025.tgz.bin instead of abc_y6n02.20.0025d.tgz.bin
has answer: http://stackoverflow.com/a/49808880
has comment: http://stackoverflow.com/comment/86651830
downvote count: 6
has comment: http://stackoverflow.com/comment/86632563
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86632524
answer count: 2
has comment: http://stackoverflow.com/comment/86632438
has answer: http://stackoverflow.com/a/49808855

http://stackoverflow.com/q/49824498
duplicate of: http://stackoverflow.com/q/613183
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49824573
has body: See My code below: import operator mydict = {'carl': 4, 'alan': 2, 'bob': 1, 'danny': 3} for i in sorted(mydict,key=operator.itemgetter(1),reverse=True): print ("%s: %d" % (i,mydict[i])) I got output: bob: 1 alan: 2 carl: 4 danny: 3 I am expecting: bob: 1 alan: 2 danny: 3 carl: 4 What's wrong here?
has comment: http://stackoverflow.com/comment/86664861
favorite count: 0
has title: Dictionary Sorting In Incorrect Order
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/49824544
linked to: http://stackoverflow.com/q/613183
downvote count: 2
has answer: http://stackoverflow.com/a/49824544
upvote count: 1
tagged with: python
score: -1
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/49824573

http://stackoverflow.com/a/49857384
has body: Category.objects.filter(id__in=[1,2,3]).category_product.order_by('price').values('id', 'price')[:3]
type: Answer
has comment: http://stackoverflow.com/comment/86731353
score: 0
answers question: http://stackoverflow.com/q/49857271

http://stackoverflow.com/a/49989346
type: Answer
has body: Eventually I just stripped all the single quotes then made a list of all the tables probably could have done this without BS but it works.
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49911592

http://stackoverflow.com/q/49868470
favorite count: 0
has answer: http://stackoverflow.com/a/49868505
possible better answer: http://stackoverflow.com/a/49868504
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49868504
tagged with: temporary-files
tagged with: python
has answer: http://stackoverflow.com/a/49868502
type: Question
answer count: 3
upvote count: 3
has title: Using NamedTemporaryFile
downvote count: 0
has body: with NamedTemporaryFile(suffix='.shp').name as tmp_shp: df.to_file(tmp_shp) In code above, I get this error: AttributeError: __enter__ How can I use a named temporary file using with statement? and since tmp_shp is just a path, does it still stay available outside of with?
accepted answer: http://stackoverflow.com/a/49868505
has comment: http://stackoverflow.com/comment/86752455

http://stackoverflow.com/a/49866701
downvote count: 0
score: 1
upvote count: 1
has body: Also, if you want to access any attribute of user from the client, you can use this. But imust say, I don't know how this can be useful for you: class User: def __init__(self, x, y): self.x = x self.y = y self.client = Client(self) class Client: def __init__(self, user): self.user = user self.z = 10 def __getattr__(self, item): __no_attr_marker = object() # allow a None in a User attribute user_item = getattr(self.user, item, __no_attr_marker) if user_item is not __no_attr_marker: return user_item else: return self.__getattribute__(item) testing: user = User(1, None) print(user.x) print(user.y) print(user.client.x) print(user.client.z) print(user.client.client) 1 None 1 10 &lt;__main__.Client object at 0x7f4e904bf8d0&gt;
answers question: http://stackoverflow.com/q/49866519
type: Answer

http://stackoverflow.com/comment/86843995
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49914123
has text: @Barmar the single quotes are from the shell_exec(), i put double quotes on the expected output, my bad
score: 0

http://stackoverflow.com/comment/86586326
comment on: http://stackoverflow.com/q/49778057
score: 0
has text: @ngoldbaum why use np.intp_t instead? I am pretty new to C types so if you have any references to help that would be great also.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49869250
has comment: http://stackoverflow.com/comment/86753867
has comment: http://stackoverflow.com/comment/86754319
has answer: http://stackoverflow.com/a/49869782
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86753894
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/86754291
favorite count: 0
type: Question
score: -6
has comment: http://stackoverflow.com/comment/86753906
has comment: http://stackoverflow.com/comment/86753857
downvote count: 8
has comment: http://stackoverflow.com/comment/86753872
has comment: http://stackoverflow.com/comment/86754339
has title: Python: Is there any reason a subset of a list would sort differently than the original list?
tagged with: python
tagged with: sorting
has comment: http://stackoverflow.com/comment/86753850
accepted answer: http://stackoverflow.com/a/49869782
has body: edit: FYI for all you paranoid people, the repro code no longer uses eval. I'm not going to say I discovered a bug in Python (which would get me instantly downvoted), but this is some preeetty weird behavior. I have a list pairs and call sort on it with a custom key function that does not change state. Then I take a subset of pairs (in the same order), and call sort again with the same key function. The result is different from the original subset. Is this possible? I have provided a repro for you all as a GitHub Gist. Steps to prepare: Download all 4 files (dpd.txt, index_map.txt, ids.txt and weirdsortbehavior.py) and place them in the same directory Run the Python program (note: with Python 3, have not tested for Python 2). For me it printed out 0 1916 1 0 Marvel at this behavior. What is the explanation for this and what can I do to fix it? Thanks.
has comment: http://stackoverflow.com/comment/86754160

http://stackoverflow.com/q/49767227
has comment: http://stackoverflow.com/comment/86550205
has title: How do I drop duplicates and keep the first value on pandas?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49767669
has answer: http://stackoverflow.com/a/49767434
tagged with: dataframe
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 0
downvote count: 2
has body: I want to drop duplicates and keep the first value. The duplicates that want to be dropped is A = 'df' .Here's my data A B C D E qw 1 3 1 1 er 2 4 2 6 ew 4 8 44 4 df 34 34 34 34 df 2 5 2 2 df 3 3 7 3 df 4 4 7 4 we 2 5 5 2 we 4 4 4 4 df 34 9 34 34 df 3 3 9 3 we 4 7 4 4 qw 2 2 7 2 So the result will be A B C D E qw 1 3 1 1 er 2 4 2 6 ew 4 8 44 4 **df** 34 34 34 34 we 2 5 5 2 we 4 4 4 4 **df** 34 9 34 34 we 4 7 4 4 qw 2 2 7 2
answer count: 3
accepted answer: http://stackoverflow.com/a/49767434
tagged with: pandas
has comment: http://stackoverflow.com/comment/86549939
has answer: http://stackoverflow.com/a/49768277
possible better answer: http://stackoverflow.com/a/49768277
has comment: http://stackoverflow.com/comment/86549782

http://stackoverflow.com/comment/86702450
has text: You could use `"$regex"` and search for a regex string instead.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49843914
type: Comment

http://stackoverflow.com/comment/86790808
has text: [This](http://jinja.pocoo.org/docs/2.10/templates/#builtin-tests) might be helpful!
score: 0
comment on: http://stackoverflow.com/q/49887289
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49891600
type: Question
tagged with: numpy
has title: python - sum list of columns, even if not all there
downvote count: 0
tagged with: python
type: AnsweredQuestion
has body: I have a dataframe that looks like this A B C D G 0 9 5 7 6 1 1 1 4 7 3 1 2 8 4 1 3 1 generated by this: df = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD')) x=np.array([[1,2]]) df['G'] = np.repeat(x,5) Suppose there are times when a certain column 'E' exists, and sometimes it doesn't depending on the time frame of the data. So sometimes we have A B C D E G 0 9 5 7 6 2 1 1 1 4 7 3 3 1 2 8 4 1 3 4 1 So either way, I'd like to sum the rows from columns A, C, and E, and groupby column G. So when column E exists , I just use df.groupby('G')['A', 'C', 'E'].sum() but when E doesn't exist, like in the first dataframe, it doesn't work. What do I need to do in order to sum even if a column is missing?
accepted answer: http://stackoverflow.com/a/49891665
tagged with: pandas
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/49891665
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/86827860
has text: That's a desired behaviour. I do not think I need help with that though. I am just trying to explain how it should be structured.
comment on: http://stackoverflow.com/a/49904426
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49850392
upvote count: 1
has comment: http://stackoverflow.com/comment/86715745
has comment: http://stackoverflow.com/comment/86715645
has body: This is one way using list comprehension: lst = [[random.randint(0, 5) for x in range(3)] for y in range(4)] print(lst) print(len([item for sublst in lst for item in sublst if item%2 == 0])) # [[4, 3, 4], [4, 2, 2], [5, 3, 4], [5, 1, 1]] # 6 We form a list containing only even numbers from lst. Then, len() counts the number of items in that list.
answers question: http://stackoverflow.com/q/49850320
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86715419
downvote count: 0
has comment: http://stackoverflow.com/comment/86715709

http://stackoverflow.com/comment/86708244
has text: It has to do with it being a pandas Series. If you did `np.var(df["A"].tolist())` you would get `nan`.
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49846534

http://stackoverflow.com/comment/86610965
has text: I tried both of these solutions and it returned an empty output, same as I received before.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49797947

http://stackoverflow.com/comment/86532540
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49758725
type: QuestionComment
has text: You should have a look at a [python tutorial](https://docs.python.org/3.6/tutorial/).

http://stackoverflow.com/a/60721447
answers question: http://stackoverflow.com/q/49768770
has body: The answers of installing pip via: curl https://bootstrap.pypa.io/get-pip.py |sudo python or curl https://bootstrap.pypa.io/get-pip.py | python did not work for me as I kept on getting the error: Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping ERROR: Could not find a version that satisfies the requirement pip (from versions: none) ERROR: No matching distribution found for pip I had to install pip manually via: Go the pip distribution website Download the tar.gz version Unpack the file locally and cd into the directory run python setup.py install
score: 2
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/86568208
score: 0
has text: Possible duplicate of [OpenCV in Android Studio](https://stackoverflow.com/questions/27406303/opencv-in-android-studio)
comment on: http://stackoverflow.com/q/49764614
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49814983
has comment: http://stackoverflow.com/comment/86644236
answer count: 0
type: UnansweredQuestion
has title: How can I have a regex search and replace with space
linked to: http://stackoverflow.com/q/15601563
has body: So I'm trying to get a regex to search for a screen name that can have a leading whitespace, wrapped in whitespace and a traling one. Right now this is what I have and it's working but it's an ugly solution: # Start of text self.tweet_text = re.sub(r'(?i)%s\s' % screen_name, profile_link + " ", self.tweet_text) # One space before self.tweet_text = re.sub(r'\s(?i)%s' % screen_name, " " + profile_link, self.tweet_text) # Wrapped in spaces self.tweet_text = re.sub(r'\s(?i)%s\s' % screen_name, " " + profile_link + " ", self.tweet_text) Would It be possible to have all of these conditions in a single regex ? I'm using Python 3.6
duplicate of: http://stackoverflow.com/q/15601563
score: 0
has comment: http://stackoverflow.com/comment/86644133
tagged with: python
tagged with: regex
type: Question

http://stackoverflow.com/a/49796045
score: 0
has body: Okay so this is my solution: I've added the bytes UID to the mail object and changed the copy function to use this bytes uid. This solved all problems I've also made a fork of the easyimap wrapper with my implentations So with a new feature to copy mails to another mailbox https://github.com/UGxMvH/easyimap
answers question: http://stackoverflow.com/q/49783326
type: Answer

http://stackoverflow.com/q/49808108
has comment: http://stackoverflow.com/comment/86632028
answer count: 0
has title: Why does calling a Tkinter method directly work, but not from another method?
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86631449
score: 0
has comment: http://stackoverflow.com/comment/86631535
has body: I am creating a simple program that for the purposes of this question, is simply opening up a file dialog box to ask the user to select a directory, which I will then use for other purposes. The way I implement this method getSaveLocation(), is I have used TKinter to create the main GUI using Tk(), hide it using withdraw() and then get the directory by using filedialog.askdirectory() which will ask the user to select a directory on their computer, and stores that directory path in a variable called directory. This is shown in the code below. I have included the full program in a pastebin here: Pastebin Link When I call this method getSaveLocation() on its own (see pastebin lines 49 and 50 for following) at the bottom, the method works fine. The dialog box is generated and the directory path selected is successfully stored in the directory variable, which I have tested using print(). However, when I instead call this method from another method, say main(), and then run main(), nothing happens. In my mind, there seems to be no difference other than modularity. What am I doing wrong? def getSaveLocation(): root = tk.Tk() root.withdraw() directory = filedialog.askdirectory() return directory
downvote count: 1
favorite count: 0
type: Question
tagged with: tkinter

http://stackoverflow.com/comment/86754772
score: 4
comment on: http://stackoverflow.com/q/49869559
type: Comment
type: QuestionComment
has text: You can read about errors and exceptions here: https://docs.python.org/3/tutorial/errors.html

http://stackoverflow.com/q/49903773
answer count: 5
downvote count: 0
has answer: http://stackoverflow.com/a/49904894
tagged with: python
has title: Pandas DataFrame to HTML: Formatting the values to display centered
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/63841067
possible better answer: http://stackoverflow.com/a/49904894
has answer: http://stackoverflow.com/a/73961835
tagged with: http://stackoverflow.com/tag/html
tagged with: dataframe
has body: I have a pandas DataFrame and am using the DataFrame.to_html method to generate a table I can send within an HTML email message. I simply want the values in certain columns to be centered, but would also like to know in general how to apply formatting to the table. I have tried applying the documentation found HERE as well as using df.style before using to_html like so: df.style.set_properties(**{'text-align':'center'}) But i am still getting all of my values left-aligned (other than the headers, which are centered). What is the correct way to center all (or a subset) of my column values, and what are the other options available for formatting? (e.g. bolding text, changing background or border colors, etc.) Further, at what stage should this formatting be applied? Within the to_html method or prior to it as I tried with df.style?
has answer: http://stackoverflow.com/a/75880231
favorite count: 0
score: 8
type: Question
tagged with: pandas-styles
accepted answer: http://stackoverflow.com/a/49903930
upvote count: 8
has answer: http://stackoverflow.com/a/49903930

http://stackoverflow.com/comment/86796859
type: Comment
has text: You just answered the question, probably because when you are fetching the html, it is an unauthenticated request and hence does not have that table
type: AnswerComment
comment on: http://stackoverflow.com/a/49890383
score: 0

http://stackoverflow.com/q/49834883
favorite count: 0
type: Question
has title: Scatter plot form dataframe with index on x-axis
possible better answer: http://stackoverflow.com/a/71974457
tagged with: pandas
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/49835113
tagged with: python
has answer: http://stackoverflow.com/a/49835113
upvote count: 42
type: AnsweredQuestion
has body: I've got pandas DataFrame, df, with index named date and the columns columnA, columnB and columnC I am trying to scatter plot index on a x-axis and columnA on a y-axis using the DataFrame syntax. When I try: df.plot(kind='scatter', x='date', y='columnA') I ma getting an error KeyError: 'date' probably because the date is not column df.plot(kind='scatter', y='columnA') I am getting an error: ValueError: scatter requires and x and y column so no default index on x-axis. df.plot(kind='scatter', x=df.index, y='columnA') I am getting error KeyError: "DatetimeIndex(['1818-01-01', '1818-01-02', '1818-01-03', '1818-01-04',\n '1818-01-05', '1818-01-06', '1818-01-07', '1818-01-08',\n '1818-01-09', '1818-01-10',\n ...\n '2018-03-22', '2018-03-23', '2018-03-24', '2018-03-25',\n '2018-03-26', '2018-03-27', '2018-03-28', '2018-03-29',\n '2018-03-30', '2018-03-31'],\n dtype='datetime64[ns]', name='date', length=73139, freq=None) not in index" I can plot it if I use matplotlib.pyplot directly plt.scatter(df.index, df['columnA']) Is there a way to plot index as x-axis using the DataFrame kind syntax?
has answer: http://stackoverflow.com/a/62887498
answer count: 3
has answer: http://stackoverflow.com/a/71974457
has comment: http://stackoverflow.com/comment/120257713
downvote count: 0
linked to: http://stackoverflow.com/q/20084487
score: 42

http://stackoverflow.com/q/49843218
type: Question
has comment: http://stackoverflow.com/comment/86701353
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/86701445
favorite count: 0
has body: I was trying to make a plot with proportions using matplotlib. When i try adding error bars (errors are en and ew), it gives me a ValueError[Scalar | N, N*1, N*2 array-like]. import matplotlib.pyplot as plt import numpy as np pcd = np.array([0.25,0.56,0.66,0.75,0.88]) wpcd = np.array([0.40,0.53,0.80]) wf = np.array([0.33,0.50,0.60,0.80,0.88]) wf1 = np.array([0.50,0.60,0.80]) en = np.array([0.108,0.124,0.122,0.108,0.08]) ew = np.array([0.126,0.128,0.103]) plt.plot(wf,pcd,'o') plt.errorbar(wf,pcd,yerr = en, fmt = 'o') plt.plot(wf1,wpcd,'*') plt.errorbar(wf1,wpcd,yerr = ew, fmt = 'o') plt.show()
has comment: http://stackoverflow.com/comment/86709340
tagged with: matrix
has comment: http://stackoverflow.com/comment/86701696
tagged with: matplotlib
score: -1
has answer: http://stackoverflow.com/a/49843316
has title: Plotting error bar in matplotlib
has comment: http://stackoverflow.com/comment/86701586

airflow
tags question: http://stackoverflow.com/q/49858685
tags question: http://stackoverflow.com/q/49902599
tags question: http://stackoverflow.com/q/49791036
tag name: airflow
tags question: http://stackoverflow.com/q/49838439
tags question: http://stackoverflow.com/q/49758962
type: Tag

http://stackoverflow.com/a/49900646
downvote count: 0
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49898899
answers question: http://stackoverflow.com/q/49898899
has body: This is what the zip builtin was made for. zip takes an arbitrary number of iterables and returns tuples with items from corresponding indices. &gt;&gt;&gt; a = ['a', 'b', 'c'] &gt;&gt;&gt; b = [1, 2, 3] &gt;&gt;&gt; c = ['red', 'green', 'blue'] &gt;&gt;&gt; list(map(list, zip(a, b, c))) [['a', 1, 'red'], ['b', 2, 'green'], ['c', 3, 'blue']] The tuples zip generates are explicitly converted to lists here because you requested lists. If there's no particular reason for having lists instead of tuples, just use &gt;&gt;&gt; list(zip(a, b, c)) [('a', 1, 'red'), ('b', 2, 'green'), ('c', 3, 'blue')]

http://stackoverflow.com/comment/86609497
has text: Add that to your question, so show an expected output dataframe. That helps greatly. Thank you.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49796539
type: QuestionComment

http://stackoverflow.com/q/49864056
has body: I have this code that extracts a bunch of stuff from urls and follows some links but I would like to get all existing text on the websites. In response.css(), is there an attribute that lets you choose every existing tag? import scrapy from bs4 import BeautifulSoup import nltk import lxml.html import pandas as pd from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class QuotesSpider(scrapy.Spider): name = "dialpad" def start_requests(self): #pass in your URLs here urls = [ 'https://www.dialpad.com/', 'https://www.domo.com/' ] allowed_domains = [i for i in urls] for url in urls: BASE_URL = url rules = (Rule(LinkExtractor(allow=(r'{}/.*'.format(url), ))), ) yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): #enter your path to where you want to save results root_path = "~/Desktop/DataSci/results_scrape" page = response.url.split(".")[1] filename = 'quotes-thing-{}.csv'.format(page) BASE_URL = response.url with open(filename, 'w') as f: for h in response.css('body').xpath('.//text()'): selector = h.extract() f.write(selector) for href in response.css("li &gt; a::attr('href')"): url = response.urljoin(href.extract()) yield scrapy.Request(url, callback = self.parse) for thing in response.css('body').xpath('.//text()'): thing = thing.extract() f.write(thing)
tagged with: web-scraping
tagged with: python
tagged with: text
score: 0
has title: How can I scrape all existing text on a page with scrapy?
has answer: http://stackoverflow.com/a/49864178
answer count: 1
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/49825104
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/86667483
score: 0
has body: You need to remove self. Remember you are using functions not clases. @api_view(['GET', 'POST']) def stock_list(request, format=None): if request.method == 'GET': stocks = Stock.objects.all() serializer = StockSerializer(stocks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = StockSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
has comment: http://stackoverflow.com/comment/86666625
accepted answer of: http://stackoverflow.com/q/49824899
has comment: http://stackoverflow.com/comment/86666515
answers question: http://stackoverflow.com/q/49824899
has comment: http://stackoverflow.com/comment/86667293
has comment: http://stackoverflow.com/comment/86666244

http://stackoverflow.com/comment/86828640
type: Comment
has text: the issue i seem to be running into is that my program runs through each new line of price data like a loop and therefor makes "start_time" a different value every time the script progresses down the line of data. How do I make it so that start time remains the same every time the scrpit runs through a new line?
type: AnswerComment
comment on: http://stackoverflow.com/a/49862889
score: 0

http://stackoverflow.com/comment/86774014
has text: Is the solution provided in [this comment](https://github.com/celery/celery/issues/3895#issuecomment-294320123) not valid?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49867908
type: QuestionComment

http://stackoverflow.com/q/49846231
tagged with: subplot
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49848523
type: AnsweredQuestion
has body: I'm looking for something similar toplt.subtitle() that puts a "main title" above two subplots of my choice which are in a grid. In my plot, the title Development of model parameter and Final model parameter should be something like a main title for the two axes. Is there a function for that? Or a smooth workaround?
has title: Python: title above two axes, but not above figure
score: 1
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/49848523
tagged with: title
favorite count: 0
type: Question

http://stackoverflow.com/comment/86620736
comment on: http://stackoverflow.com/q/49803081
type: Comment
type: QuestionComment
score: 0
has text: Train:2083, Test: 893, I will try another random seed right away - just wanted to verify if my whole approach is wrong.

http://stackoverflow.com/comment/86787239
type: QuestionComment
has text: what the type of `testing_features` ?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49885598

http://stackoverflow.com/comment/121707561
type: Comment
has text: Brilliant answer!
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/57206412

http://stackoverflow.com/q/49804779
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49805015
has body: How would you simplify and give this shell script a nice look? Maybe using loops etc.. #!/usr/bin/env bash echo 'Testing 1' CONF_PATH=/var/..../test_1 python27 -m unittest test1 CONF_PATH=/var/..../test_1 python27 -m unittest test2 CONF_PATH=/var/..../test_1 python27 -m unittest test3 CONF_PATH=/var/..../test_1 python27 -m unittest test4 CONF_PATH=/var/..../test_1 python27 -m unittest test5 CONF_PATH=/var/..../test_1 python27 -m unittest test6 echo 'Testing 2' CONF_PATH=/var/..../test_2 python27 -m unittest test1 CONF_PATH=/var/..../test_2 python27 -m unittest test2 CONF_PATH=/var/..../test_2 python27 -m unittest test3 CONF_PATH=/var/..../test_2 python27 -m unittest test4 CONF_PATH=/var/..../test_2 python27 -m unittest test5 CONF_PATH=/var/..../test_2 python27 -m unittest test6
answer count: 2
has answer: http://stackoverflow.com/a/49804855
score: 1
downvote count: 0
tagged with: shell
has comment: http://stackoverflow.com/comment/86625380
favorite count: 0
type: Question
has title: Simplify the execution of a python test within a shell script
type: UnansweredQuestion

http://stackoverflow.com/a/49885372
score: 2
has comment: http://stackoverflow.com/comment/86787529
upvote count: 2
has comment: http://stackoverflow.com/comment/86791551
has comment: http://stackoverflow.com/comment/86787552
accepted answer of: http://stackoverflow.com/q/49885266
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86787467
downvote count: 0
answers question: http://stackoverflow.com/q/49885266
has comment: http://stackoverflow.com/comment/86787678
has comment: http://stackoverflow.com/comment/86786925
has comment: http://stackoverflow.com/comment/86794133
type: Answer
has comment: http://stackoverflow.com/comment/86787075
has body: You may use ^#(\d+(?:,\d+)?)\s*([^(]*) See the regex demo. Details ^ - start of string # - a hash symbol (\d+(?:,\d+)?) - Group 1: one or more digits and an optional sequence of , followed with 1+ digits \s* - 1+ whitespace chars ([^(]*) - Group 2: any 0+ chars other than ( Python demo: import re rx = r"^#(\d+(?:,\d+)?)\s*([^(]*)" s = "#31,456 in this category (Top 100 of category)" m = re.search(rx, s) if m: print("Group 1: {}; Group 2: {}".format(m.group(1), m.group(2))) # =&gt; Group 1: 31,456; Group 2: in this category

http://stackoverflow.com/comment/86652904
has text: @Paul Rooney Thats what I did initially however whenever I retrieved the ability I couldn't retrieve its "AP" attribute which was needed for the next line of code where that value is put into an Algorithm to work out damage. I thought about using a chain of If's however that was impractical as in it would be repeating code a lot
score: 0
comment on: http://stackoverflow.com/q/49818650
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86739286
type: QuestionComment
has text: That's a pity, but obviously necessary. Thanks!
comment on: http://stackoverflow.com/q/49843541
score: 0
type: Comment

http://stackoverflow.com/comment/86840978
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49912671
type: Comment
has text: There could be some missing ';'

http://stackoverflow.com/a/49848887
downvote count: 0
type: Answer
upvote count: 1
has body: As has been mentioned, if you create a key's value as a string, you can't use append on it, but you can if you make the key's value a list. Here is one way to do so: newcategory=input("Enter new category: ") oscars[newcategory]=[] addnewnominees = 'yes' while addnewnominees.lower() != "no": nominees=input("Enter new nominee: ") oscars[newcategory].append(nominees) addnewnominees = str(input("Do you want to enter more nominees: (yes/no):"))
answers question: http://stackoverflow.com/q/49848688
score: 1

http://stackoverflow.com/q/49882642
has comment: http://stackoverflow.com/comment/86783410
type: UnansweredQuestion
has body: I am working on deep learning. I created an autoencoder network with NSL-KDD dataset. i wanna train network in true way. but during train my loss function show weird number that i can not understand. this is my source code: import os import numpy as np from keras.layers import Dense, Input from keras.models import Model def load_nsl_kdd_cup_dataset(filename): with open(filename, 'r')as f: list1 = [] list2 = [] for i in f: list1.append(i) for i in list1: i = str(i) labels = i.split(sep=',') list2.append(labels[:41]) arraylist = np.array(list2) return arraylist dirs = './NSL_KDD-master' train_X = load_nsl_kdd_cup_dataset(os.path.join(dirs,'KDDTrain+.txt')) test_X = load_nsl_kdd_cup_dataset(os.path.join(dirs, 'KDDTest+.txt')) print(train_X.shape) print(test_X.shape) Preprocessing phase 1. Convert nominal values to numeric values def convert_nominal_to_numerical(sets): list1 = [] col1, col2, col3 = [], [], [] for i in sets: # print(i[1]) if i[1] == 'tcp': i[1] = 1 elif i[1] == 'udp': i[1] = 2 elif i[1] == 'icmp': i[1] = 3 if i[2] == 'http': i[2] = 1 elif i[2] == 'private': i[2] = 2 elif i[2] == 'domain_u': i[2] = 3 elif i[2] == 'smtp': i[2] = 4 elif i[2] == 'ftp_data': i[2] = 5 elif i[2] == 'eco_i': i[2] = 6 elif i[2] == 'other': i[2] = 7 elif i[2] == 'ecr_i': i[2] = 8 elif i[2] == 'telnet': i[2] = 9 elif i[2] == 'finger': i[2] = 10 elif i[2] == 'ftp': i[2] = 11 elif i[2] == 'auth': i[2] = 12 elif i[2] == 'Z39_50': i[2] = 13 elif i[2] == 'uucp': i[2] = 14 elif i[2] == 'courier': i[2] = 15 elif i[2] == 'bgp': i[2] = 16 elif i[2] == 'whois': i[2] = 17 elif i[2] == 'uucp_path': i[2] = 18 elif i[2] == 'iso_tsap': i[2] = 19 elif i[2] == 'time': i[2] = 20 elif i[2] == 'imap4': i[2] = 21 elif i[2] == 'nnsp': i[2] = 22 elif i[2] == 'vmnet': i[2] = 23 elif i[2] == 'urp_i': i[2] = 24 elif i[2] == 'domain': i[2] = 25 elif i[2] == 'ctf': i[2] = 26 elif i[2] == 'csnet_ns': i[2] = 27 elif i[2] == 'supdup': i[2] = 28 elif i[2] == 'discard': i[2] = 29 elif i[2] == 'http_443': i[2] = 30…
has title: Weird loss function during network training
tagged with: loss-function
has comment: http://stackoverflow.com/comment/86783352
tagged with: python
has comment: http://stackoverflow.com/comment/86782727
has comment: http://stackoverflow.com/comment/86781957
has comment: http://stackoverflow.com/comment/86781300
has comment: http://stackoverflow.com/comment/86783073
score: 0
tagged with: deep-learning
answer count: 0
has comment: http://stackoverflow.com/comment/86781755
has comment: http://stackoverflow.com/comment/86782055
has comment: http://stackoverflow.com/comment/86782546
tagged with: neural-network
has comment: http://stackoverflow.com/comment/86783482
type: Question
has comment: http://stackoverflow.com/comment/86781379
has comment: http://stackoverflow.com/comment/86782654

http://stackoverflow.com/a/49904341
answers question: http://stackoverflow.com/q/49904120
downvote count: 1
has comment: http://stackoverflow.com/comment/86825101
type: Answer
score: -1
has body: As easy as: import re with open('in.txt') as f: for line in f: print (re.sub(r'^([^,]+),(.*)', r'"\1","\2"', line.strip("\n"))) "group-a","cats" "group-b","dogs" "group-c","snakes, turtles, lizards" "group-d","fish, eels" "group-e","people"
upvote count: 0

http://stackoverflow.com/comment/86588802
type: Comment
type: QuestionComment
has text: here is the dict which the for loop print:{'38': 0.35454617782747228, '17': 0.022222222222222147, '1': 0.022222222222222147, '_id': '67712c550b63cf58b68d1b5b576c45c2', 'keywords': " '兩岸', '十九大', '中評社', '涉台', '中共', '武統', '變化', '講 話', '和平', '統一', '研討會', '憂慮', '給蔡', '社會', '大陸' ", 'url': 'news.pchome.com.tw/politics/cdnews/20171029/index- 50924602295654250001.html', '5': 0.4152023790580624, 'content': '中評社29日刊登《快評》，全文如下：中共十九大結束之後，各種學習、從我們中評智庫顯地感到，........相信這些變化才剛剛開始，未來還會有更多、更顯明的變化。中央網路 報', 'unix_time': 1509261251}
score: 0
comment on: http://stackoverflow.com/q/49769929

http://stackoverflow.com/comment/86606480
has text: hey I'm Linux user, you should add the correct path for target folders. Linux file system is so far different from window, so i can't help in what is actual path of them, hope it's not a big deal to you.
type: Comment
comment on: http://stackoverflow.com/a/49795877
type: AnswerComment
score: 0

http://stackoverflow.com/q/49819812
upvote count: 2
type: UnansweredQuestion
has title: Flask/Python Login
tagged with: flask
downvote count: 1
favorite count: 0
tagged with: ldap
has answer: http://stackoverflow.com/a/49841691
score: 1
has answer: http://stackoverflow.com/a/49820591
tagged with: python
has body: I have Python/Flask application with a login screen. My goal is to utilize LDAP authentication in unison with my Python/Flask app. The issue that I am running into is this: raise RuntimeError('The session is unavailable because no secret ' RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret. I have a secret key, and I still get the same error when I comment it out. Here is my code: import token from flask import Flask, session from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager app = Flask(name) #app.secret_key = 'welfhwdlhwdlfhwelfhwlehfwlehfelwehflwefwlehflwefhlwefhlewjfhwelfjhweflhweflhwel' app.config['SESSION_TYPE'] = 'filesystem' app.config['LDAP_AUTH_SERVER'] = 'LDAPLocation.com' app.config['LDAP_PORT'] = '636' app.config['LDAP_TOP_DN'] = 'CN=something here,OU=somethingHere,OU=SomeService Accounts,dc=magic,dc=pumpum,DC=com Xe' app.config['LDAP_BIND_USER_PASSWORD'] = 'pssword' app.register_blueprint(token, url_prefix='/auth') db = SQLAlchemy(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' from app.auth.views import auth app.register_blueprint(auth)
type: Question
answer count: 2

http://stackoverflow.com/comment/86710564
has text: But, how would i do it in a manner to work with each line individually? for example i will be outputting information from the first line (the name), then computing a quiz average of the second line and out putting that, and so on and so forth and then on the fifth line it will be a new name of a new student. So how would i go about seperating each line individually so it could receive it's own for-loop
comment on: http://stackoverflow.com/a/49847761
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49881318
has comment: http://stackoverflow.com/comment/86778474
has title: Finding the fft of a inputted wav. file
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86778534
tagged with: python
has answer: http://stackoverflow.com/a/49881599
score: -1
has comment: http://stackoverflow.com/comment/86778938
type: Question
has body: Im doing a project on a raspberry pi 3, the goal is to apply a band-pass filter to the signal but i am currently having trouble getting the fft of the given signal. I am using python3, here is my code thus far: import scipy from scipy.io.wavfile import read from scipy.signal import hann from scipy.fftpack import rfft import matplotlib.pyplot as plt import numpy as np from threading import * input_data = read("/home/pi/Music/doorbell-1.wav") np.array(input_data[1],dtype=float) audio = input_data[1] #apply a Hanning window window = hann(1024) audio = audio[0:1024] * window # fft mags = abs(rfft(audio)) # convert to dB mags = 20 * scipy.log10(mags) # normalise to 0 dB max mags -= max(mags) # plot plt.plot(mags) # label the axes plt.ylabel("Magnitude (dB)") plt.xlabel("Frequency Bin") # set the title plt.title("doorbell Spectrum") plt.show() #ERROR /usr/lib/python3/dist-packages/numpy/lib/scimath.py:310: RuntimeWarning: divide by zero encountered in log10 return nx.log10(x) MaynoothTest.py:18: RuntimeWarning: invalid value encountered in multiply mags = 20 * scipy.log10(mags) MaynoothTest.py:20: RuntimeWarning: invalid value encountered in subtract mags -= max(mags) [ True True True ..., True True True] /usr/lib/python3/dist-packages/numpy/core/numeric.py:531: ComplexWarning: Casting complex values to real discards the imaginary part return array(a, dtype, copy=False, order=order)
upvote count: 0
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/49904884
score: 0
has comment: http://stackoverflow.com/comment/86838899
has comment: http://stackoverflow.com/comment/86839352
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86871960
has comment: http://stackoverflow.com/comment/86834823
answers question: http://stackoverflow.com/q/49898084
type: Answer
has comment: http://stackoverflow.com/comment/86838866
has comment: http://stackoverflow.com/comment/86839308
has comment: http://stackoverflow.com/comment/86838424
accepted answer of: http://stackoverflow.com/q/49898084
has body: this line in home() causing the exception, return Response({'place_list': place_list, 'preferred_list': preferred_list, 'disliked_list': disliked_list, 'place_order': place_order, }) In this statement, you are passing Place instances/queryset to the response, which is not JSON Serializable. So What you have to do is, serialize the queryset before returning. example, Replace the above statement with following, return Response({'place_list': PlaceSerializer(place_list,many=True).data})

http://stackoverflow.com/q/49898398
answer count: 2
has answer: http://stackoverflow.com/a/49898711
downvote count: 0
tagged with: css-selectors
tagged with: selenium
type: AnsweredQuestion
has title: How to use selenium to call angular function (ng-click)
accepted answer: http://stackoverflow.com/a/49898711
tagged with: angular
has answer: http://stackoverflow.com/a/49898511
possible better answer: http://stackoverflow.com/a/49898511
tagged with: python
has body: I am trying to call a angular ng-click using selenium. This question is based on this javascript: 100% This I turned into: driver.find_element_by_css_selector("[ng-click=getHope(1,'pray','smile')]").click() I even tried adding span: driver.find_element_by_css_selector("[ng-click=getHope(1,'pray','smile')]").click() and adding : driver.find_element_by_css_selector("span[ng-click=getHope(1,\'pray\',\'smile\')]").click() But I can the following error: selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified I tried to mimic this link, but it does not work. What am I doing wrong?
favorite count: 0
type: Question
upvote count: 2
score: 2
tagged with: xpath

http://stackoverflow.com/q/49785496
tagged with: list
answer count: 2
has body: I have these: pixels = [(255, 255, 255, 0), (255, 255, 255, 0), (255, 255, 255, 0), (255, 255, 255, 0), (255, 255, 255, 0), (204, 204, 204, 255), (204, 204, 204, 255), (119, 119, 119, 255), (119, 119, 119, 255), (204, 204, 204, 255), (204, 204, 204, 255), (255, 255, 255, 0), (255, 255, 255, 0), (255, 255, 255, 0), (255, 255, 255, 0), (255, 255, 255, 0)......] It's a list with a lot of tuples and I want to convert it into an image. I can't find any solution.
downvote count: 3
has comment: http://stackoverflow.com/comment/86748087
has title: I have a list with RGBA tuples and I want convert it to and image and save it
favorite count: 0
has answer: http://stackoverflow.com/a/49785530
type: Question
has answer: http://stackoverflow.com/a/49785886
upvote count: 0
type: UnansweredQuestion
tagged with: rgba
score: -3
tagged with: python
tagged with: image

http://stackoverflow.com/comment/86828968
comment on: http://stackoverflow.com/q/49884890
has text: there's probably a dozen different ways to do it. Do some research, try things out (by hand, maybe), and come back with more specific questions.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86757965
score: 0
comment on: http://stackoverflow.com/a/49870935
has text: well yes I want it like that.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49807378
has body: The answer lies in caffe.proto. Each parameter that you include in a layer is listed in that file. For Eltwise layer, the parameters are operation, coeff, stable_prod_grad. The parameter operation takes 3 values 0, 1 or 2 whose mappings are defined by an enum EltwiseOp. As far as the parameter name is concerned, you will find it in LayerParameter. I couldn't find any documentation on this. It's just something you learn along the way. I hope this clears your doubts.
score: 1
type: Answer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86629677
answers question: http://stackoverflow.com/q/49806879

http://stackoverflow.com/a/49811719
score: 0
has comment: http://stackoverflow.com/comment/86639428
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86645712
has comment: http://stackoverflow.com/comment/86638302
answers question: http://stackoverflow.com/q/49811222
type: Answer
accepted answer of: http://stackoverflow.com/q/49811222
has body: Another way of doing it using pure Python would be this: values = [-3, 1, 4, -1] values = [i[0] for i in sorted(enumerate(values), key=lambda i: i[1])] print(values) Output: [0, 3, 1, 2]

http://stackoverflow.com/a/49948751
has body: From your question, it is not clear what you are attempting to accomplish. Note that full Python is supported in PyTorch, but what you are doing is creating a map object in your last line of code. The following should work for your purposes (? I'm guessing) though: import torch import torch.nn as nn n, d, h, w = 20, 3, 32, 32 embedding = torch.randn(n, d, h, w) padder = nn.ReflectionPad2d(padding=1) embedding = padder(embedding) new = [embedding[:,:, (i-1):(i+2), (j-1):(j+2)] for i, j in zip(range(1,h), range(1,w))] Note however, that there are more elegant ways to chunk up a tensor (e.g. torch.chunk() or to operate on patches with convolutions (e.g. torch.nn.Conv2d)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49877655

http://stackoverflow.com/q/49889113
has answer: http://stackoverflow.com/a/57902210
tagged with: text
has answer: http://stackoverflow.com/a/76809906
has title: converting spacy token vectors into text
answer count: 3
tagged with: spacy
upvote count: 3
has answer: http://stackoverflow.com/a/49936164
has body: I am using spacy to create vectors of a sentence. If the sentence is 'I am working', it gives me a vector of shape (3, 300). Is there any way to get back the text in the sentence using those vectors? Thank in advance, Harathi
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86877066
score: 3
tagged with: vector
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86812553
tagged with: python
tagged with: nlp

http://stackoverflow.com/q/49905003
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49908973
tagged with: python
score: 4
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/49908973
tagged with: sqlite
has title: Should I expect Python sqlite3 user defined functions to persist in a SQLite database?
answer count: 1
downvote count: 0
has body: I register a user defined function: conn.create_function("geocode", 4, geocode) The function is used in a trigger, and the trigger fires correctly after an insert, but the function isn't found: sqlite3.OperationalError: no such function: geocode My understanding of this usage pattern may be wrong, is it possible to persist Python functions in the database?

http://stackoverflow.com/a/49801051
accepted answer of: http://stackoverflow.com/q/49799998
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86765435
answers question: http://stackoverflow.com/q/49799998
has comment: http://stackoverflow.com/comment/86776285
has comment: http://stackoverflow.com/comment/86617837
upvote count: 2
type: Answer
has body: One simple solution could be to create 2 Dataset objects, one for labels, one for data, then batch the data by groups of 3 and use tf.data.interleave to interleave the two datasets back together, producing the results you want. If that's not easy to do then you could try the following process of mapping one element onto multiple. You would have to create a batch of 3 elements (with 3 labels), then split that in a map function into 3 sets of the data each against one of the labels you received. The recipe for doing that is in the following SO question, though it's a little more involved than the first suggestion: In Tensorflow&#39;s Dataset API how do you map one element into multiple elements?
has comment: http://stackoverflow.com/comment/86852651
score: 2
has comment: http://stackoverflow.com/comment/86656516
has comment: http://stackoverflow.com/comment/86863993

http://stackoverflow.com/comment/86734770
score: 0
type: Comment
has text: What you posted there isn't valid python code. Please post a [mcve] that shows how that exception is thrown and how you're catching it.
type: QuestionComment
comment on: http://stackoverflow.com/q/49859915

http://stackoverflow.com/q/49843903
type: Question
has comment: http://stackoverflow.com/comment/86703647
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/86703532
type: UnansweredQuestion
tagged with: python
has body: I have a function which loads 8 GB of data and then return 6 MB of data (a list). But then i launch multiprocess based functions and the whole 8 GB gets passed to all processes where as i need only the 6 MB returned by function.Due to this , the memory usage is 8*process_count . How can i remove unneeded data worth 8 GB. Pseudo Code: def fun(): uses another function to load a big json file and get keys from it. something like this: return [k for k,v in ext function returning a big dictionary created from big json file] def main(): list_ll = copy.deepcopy(fun()) # done to remove reference to fun gc.collect() launch multiprocess functions each of which takes a part of list. All 8 GB data is being copied.Memory usage too high.
has title: Delete not needed data from memory
tagged with: python-2.7
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/86703401
has comment: http://stackoverflow.com/comment/86703669

http://stackoverflow.com/a/49801979
has body: I'm assuming your output shape is (samples, boxes, 5). Solution def custom_loss(y_true,y_pred): cross = K.mean(K.binary_crossentropy(y_true[:,:,:1], y_pred[:,:,:1]), axis=-1) mse = K.mean(K.square(y_pred[:,:,1:] - y_true[:,:,1:]), axis=-1) return cross + mse If you still get an incompatibility due to cross having a different shape from mse, you should probably take a further K.mean() until both of them keep shapes either like (samples, boxes) or just (samples,). If you're not going to use any kind of sample weighting, you can just remove the axis=-1 from the means. Wrong dimension Don't forget that the first dimension of a tensor is the samples, so you need to take a from the last dimension (since the second is "boxes"): y_true[:,:,:1] has shape (samples, boxes, 1) y_true[:,:,1:] has shape (samples, boxes, 4) I'm using :1 to keep the last dimension, if you use only 0, the shape will be (samples, boxes).
has comment: http://stackoverflow.com/comment/86658047
answers question: http://stackoverflow.com/q/49801165
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49801165
has comment: http://stackoverflow.com/comment/86655448
type: Answer

http://stackoverflow.com/comment/86585671
type: AnswerComment
has text: I'll give you a plus, since this avoids the unnecessary overhead of pickling the data. It's quite relevant to OpenCV too, since the Python bindings use `numpy.array`s to represent the image. I'd probably pack some metadata (size + channel count) before the pixel array to make the protocol more flexible (doesn't cost much). | Overall I don't really think this is a solution based on what OP mentioned in comments. Unreliable comms are the issue, and IMHO that doesn't go well with low cost hardware and easy solutions.
comment on: http://stackoverflow.com/a/49784987
type: Comment
score: 0

http://stackoverflow.com/comment/86623264
has text: So why not flag the post as a duplicate? Not that we have enough information to be sure that it is a Python 2 / 3 issue here.
type: AnswerComment
comment on: http://stackoverflow.com/a/49804131
score: 2
type: Comment

http://stackoverflow.com/q/49764687
has title: replacing and moving values in list of list
has body: I have following list of the list [ ['90 min', 'Drama', 'Horror', 'Thriller', 'User Rating: 8.2/10 (28,588 user ratings)', '82', 'Metascore', 'Rank:', '2', 'Showtimes:', 'Studio Movie Grill - Downey', '11:15 am', '12:05 pm', '1:40', '2:30', '4:15', '6:40', '7:30', '9:05', '10:15'], ['90 min', 'Drama', 'Horror', 'Thriller', 'User Rating: 8.2/10 (28,588 user ratings)', '82', 'Metascore', 'Rank:', '2', 'Showtimes:', 'AMC Norwalk 20', '11:45 am', '12:45 pm', '2:15', '3:15', '4:45', '5:45', '7:15', '8:15', '9:45', '10:45'], ['90 min', 'Drama', 'Horror', 'Thriller', 'User Rating: 8.2/10 (28,588 user ratings)', '82', 'Metascore', 'Rank:', '2', 'Showtimes:', 'Cinemark Downey and XD', '10:00 am', '11:15', '12:30 pm', '1:45', '3:00', '4:15', '5:30', '6:30', '6:45', '8:00', '8:45', '9:15', '10:00', '10:30', '11:15', '11:45'], ['90 min', 'Drama', 'Horror', 'Thriller', 'User Rating: 8.2/10 (28,588 user ratings)', '82', 'Metascore', 'Rank:', '2', 'Showtimes:', 'AMC Stonebriar 24', '11:40 am', '12:30 pm', '2:00', '3:00', '4:40', '5:30', '7:20', '8:00', '10:00', '10:30'], ['90 min', 'Drama', 'Horror', 'Thriller', 'User Rating: 8.2/10 (28,588 user ratings)', '82', 'Metascore', 'Rank:', '2', 'Showtimes:', 'AMC Orange 30 (AMC Block 30)', '11:00 am', '12:15 pm', '1:30', '2:45', '4:00', '5:15', '6:30', '7:45', '9:00', '10:15'] ] I would like to do two things 1) If user rating ('User Rating: 8.2/10 (28,588 user ratings)') is >= 6.5, I would like to make it bold potentially by adding tags around the existing value in list. 2) Secondly, I would like to move value after "Showtimes:" i.e. 10th element in the list of list and bring it to position "0" I don't know how to do this, I am new to python. If somebody can give me the starting point I will appreciate that. Solution With help of solution provided by Ajax1234 below; I was able to write what I was looking for. This might not be the best solution but it works. The only improvement I have added from Ajax1234 solution is the position of "Us…
answer count: 1
score: -3
has answer: http://stackoverflow.com/a/49764797
has comment: http://stackoverflow.com/comment/86544912
favorite count: 0
type: Question
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/86544897
accepted answer: http://stackoverflow.com/a/49764797
has comment: http://stackoverflow.com/comment/86549450
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/a/49780443
has comment: http://stackoverflow.com/comment/86576506
type: AcceptedAnswer
has body: You can use a custom form in the admin, either by using the form option of the get_form method. This is the documentation example for how you'd pass a custom form: from django import forms from django.contrib import admin from myapp.models import Person class PersonForm(forms.ModelForm): class Meta: model = Person exclude = ['name'] class PersonAdmin(admin.ModelAdmin): exclude = ['age'] form = PersonForm You can add extra fields, as in any form. I was wondering why you wanted this. Since you said in a comment it is to submit information to an API, you can also use an action, taking input from the user in an intermediate page. EDIT: As became apparent in comments, the form needs to be dynamic for the user, and not when it is created. Therefore, the solution is using inlines, which once created and linked to the current model, allow the user to add any number of related forms to the current form.
has comment: http://stackoverflow.com/comment/86617470
has comment: http://stackoverflow.com/comment/86617517
type: Answer
answers question: http://stackoverflow.com/q/49780160
score: 0
has comment: http://stackoverflow.com/comment/86576666
accepted answer of: http://stackoverflow.com/q/49780160

http://stackoverflow.com/q/49813434
has title: Generating and running Haskell code from Python
tagged with: ghci
has comment: http://stackoverflow.com/comment/86641471
accepted answer: http://stackoverflow.com/a/49814606
has answer: http://stackoverflow.com/a/49814606
tagged with: python
tagged with: haskell
linked to: http://stackoverflow.com/q/11515944
tagged with: ghc
upvote count: 4
type: AnsweredQuestion
has body: We are writing a python program that attempts to synthesize a (simple) haskell-function given input-output pairs. Throughout the run of the program, we generate haskell code and check its correctness against the user-supplied examples. Suppose we get as input "1 2" and expected output "3". We would (eventually) come up with the plus function. We would then run (\x y -&gt; x + y) 1 2 in haskell and check if it evaluates to 3. The way we currently do things is by running the following python code: from subprocess import Popen, PIPE, STDOUT proccess = Popen(f'ghc -e "{haskell_code}"', shell=True, stdout=PIPE, stderr=STDOUT) haskell_output = proc.stdout.read().decode('utf-8').strip('\n') As neither of us is familiar with ghc, haskell, processes, or really anything to do with any of this, we were hoping someone could help us with preforming this task in a (much) more efficient manner, as this is currently very slow. Additionally, we would like to be able to perform more than a single statement. For example, we would like to import Data.Char so that our function can use “toUpper”. However, the way we are currently doing this is by sending a single lambda function and the inputs appended to it, and we aren't sure how to add an import statement above that (adding "\n" did not seem to work). To summarize, we would like the fastest (runtime) solution that would allow us to test haskell functions from python (where we don’t have the code for all haskell functions in advance or at one point in time, but rather test as we generate the code), while allowing us to use more than a single statement (for example, importing). Apologies if any of this is trivial or stupid, any help would be highly appreciated.
has comment: http://stackoverflow.com/comment/86641329
score: 3
answer count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49846491
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: extract time from timedelta
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49847382
has answer: http://stackoverflow.com/a/49847183
score: 0
answer count: 2
has body: I have a list: [Timedelta('0 days 00:02:39.210526'), Timedelta('0 days 00:03:29.033333'), Timedelta('0 days 00:03:36.333333'), Timedelta('0 days 00:01:04'), Timedelta('0 days 00:04:05.571428'), Timedelta('0 days 00:04:00.500000'), Timedelta('0 days 00:03:54.583333')] How can I extract only the time from this list?
has comment: http://stackoverflow.com/comment/86707962
tagged with: timedelta

apache-beam-io
type: Tag
tag name: apache-beam-io
tags question: http://stackoverflow.com/q/49913108

http://stackoverflow.com/comment/86660078
comment on: http://stackoverflow.com/q/49813009
type: Comment
type: QuestionComment
has text: so you want to use the Clock, do you want to do a periodic task?
score: 0

http://stackoverflow.com/a/49821060
answers question: http://stackoverflow.com/q/49820904
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86657300
downvote count: 0
has comment: http://stackoverflow.com/comment/86657359
has body: It is better idea to parse html using a html parser. Ex: Using BeautifulSoup from bs4 import BeautifulSoup s = """ Size 1.64 GB in 2 file(s) """ soup = BeautifulSoup(s, "html.parser") print(soup.tr.td.findNext('td').text) print(re.findall("\d+.\d+ [A-Z]+", soup.tr.td.findNext('td').text.strip())) #Use regex to get only the required data. Output: 1.64 GB in 2 file(s) [u'1.64 GB']
has comment: http://stackoverflow.com/comment/86657501
type: Answer

http://stackoverflow.com/q/49851046
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86719069
upvote count: 1
favorite count: 0
type: Question
has title: Merge all h5 files using h5py
tagged with: h5py
has answer: http://stackoverflow.com/a/49856991
score: 1
tagged with: python
linked to: http://stackoverflow.com/q/30214531
has body: I am Novice at coding. Can some one help with a script in Python using h5py wherein we can read all the directories and sub-directories to merge multiple h5 files into a single h5 file.
has comment: http://stackoverflow.com/comment/86717053

http://stackoverflow.com/q/49846084
upvote count: 0
answer count: 1
tagged with: django
downvote count: 1
favorite count: 0
type: Question
has body: Am trying to use MySQL with Django 2.0, I have installed it using "pip install mysqlclient" and it installed successfully. What do i need to do next?
type: UnansweredQuestion
tagged with: mysql-python
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49846136
has title: How to configure MySQL with Django

http://stackoverflow.com/a/49870601
has comment: http://stackoverflow.com/comment/86758437
has comment: http://stackoverflow.com/comment/86758691
has comment: http://stackoverflow.com/comment/86773497
type: Answer
has comment: http://stackoverflow.com/comment/86759676
score: -1
has comment: http://stackoverflow.com/comment/86762545
has comment: http://stackoverflow.com/comment/86757190
upvote count: 0
answers question: http://stackoverflow.com/q/49870181
downvote count: 1
has body: There is a very useful python package called Matplotlib you can use to draw box plot or violin plot. Below is a example of box plot vs violin plot. import matplotlib.pyplot as plt import numpy as np fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(9, 4)) # Fixing random state for reproducibility np.random.seed(19680801) # generate some random test data all_data = [np.random.normal(0, std, 100) for std in range(6, 10)] # plot violin plot axes[0].violinplot(all_data, showmeans=False, showmedians=True) axes[0].set_title('Violin plot') # plot box plot axes[1].boxplot(all_data) axes[1].set_title('Box plot') # adding horizontal grid lines for ax in axes: ax.yaxis.grid(True) ax.set_xticks([y + 1 for y in range(len(all_data))]) ax.set_xlabel('Four separate samples') ax.set_ylabel('Observed values') # add x-tick labels plt.setp(axes, xticks=[y + 1 for y in range(len(all_data))], xticklabels=['x1', 'x2', 'x3', 'x4']) plt.show() There are more examples in matplotlib's gallery.I hope you can find a example which can satisfy you.

http://stackoverflow.com/q/49793366
linked to: http://stackoverflow.com/q/23824687
has body: I'm trying to get mathtext to render my figure axes labels correctly (ideally I don't want to use Latex itself to render the text). However, this small minimum working example produces the error shown below. It seems to me that it should work, is maybe a necessary package not installed? I'm running matplotlib 2.2.2 and Python 3.5 import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(0,0) ax.set_ylabel(r'$\mathrm A$') the error produced: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/matplotlib/mathtext.py", line 2516, in parse result = self._expression.parseString(s) File "/usr/local/lib/python3.5/dist-packages/pyparsing.py", line 1632, in parseString raise exc File "/usr/local/lib/python3.5/dist-packages/pyparsing.py", line 1622, in parseString loc, tokens = self._parse( instring, 0 ) File "/usr/local/lib/python3.5/dist-packages/pyparsing.py", line 1529, in _parseCache value = self._parseNoCache(instring, loc, doActions, callPreParse) File "/usr/local/lib/python3.5/dist-packages/pyparsing.py", line 1379, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/usr/local/lib/python3.5/dist-packages/pyparsing.py", line 3717, in parseImpl return self.expr._parse( instring, loc, doActions, callPreParse=False ) File "/usr/local/lib/python3.5/dist-packages/pyparsing.py", line 1529, in _parseCache value = self._parseNoCache(instring, loc, doActions, callPreParse) File "/usr/local/lib/python3.5/dist-packages/pyparsing.py", line 1379, in _parseNoCache loc,tokens = self.parseImpl( instring, preloc, doActions ) File "/usr/local/lib/python3.5/dist-packages/pyparsing.py", line 3395, in parseImpl loc, exprtokens = e._parse( instring, loc, doActions ) File "/usr/local/lib/python3.5/dist-packages/pyparsing.py", line 1529, in _parseCache value = self._parseNoCache(instring, loc, doActions, callPreParse) File "/usr/local/lib/python3.5/dist-packages/pyparsing.py", line 1379, in _parseNoCache l…
has comment: http://stackoverflow.com/comment/86602780
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49843916
tagged with: latex
has comment: http://stackoverflow.com/comment/86602447
score: 1
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/86601738
has comment: http://stackoverflow.com/comment/86602371
tagged with: python-3.x
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has title: Unknown symbol matplotlib mathtext
answer count: 1

http://stackoverflow.com/comment/86624351
score: 0
comment on: http://stackoverflow.com/q/49784872
has text: The status is optimal. Any suggestion about how to impose an elementwise constraint? What is wrong with the way I defined the elementwise constraints in the code?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/124536862
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49762347
has text: @IlyaLasy did you find any solution?

http://stackoverflow.com/q/49783496
accepted answer: http://stackoverflow.com/a/49784155
has answer: http://stackoverflow.com/a/49784155
has body: I'm trying to pass in a tuple of tests to have each one run on a series: deltas = [getattr(test_df.diff().cumsum()[col], test)(0).cumsum() for col, test in zip(test_df.columns, tests)] I can pass in something like tests = ('lt', 'lt', 'gt'), but can I pass in a condition along with it? Something like tests = ('lt(5)', 'lt(2)', 'gt(9)') (Which doesn't work)?
type: Question
has title: Series getattr with condition
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86582764
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/86748371
type: Comment
has text: Can you not pass the `parallel` context into func2?
type: QuestionComment
comment on: http://stackoverflow.com/q/49866450
score: 1

http://stackoverflow.com/comment/86608404
comment on: http://stackoverflow.com/q/49784816
has text: @IljaEverilä yeah that worked! for some reason if I manually execute the last select, it returns the correct value, but when used as a filter is returning empty.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49801638
type: Question
tagged with: reinforcement-learning
score: 10
upvote count: 10
tagged with: python
has title: Normalizing Rewards to Generate Returns in reinforcement learning
has body: The question is about vanilla, non-batched reinforcement learning. Basically what is defined here in Sutton's book. My model trains, (woohoo!) though there is an element that confuses me. Background: In an environment where duration is rewarded (like pole-balancing), we have rewards of (say) 1 per step. After an episode, before sending this array of 1's to the train step, we do the standard discounting and normalization to get returns: returns = self.discount_rewards(rewards) returns = (returns - np.mean(returns)) / (np.std(returns) + 1e-10) // usual normalization The discount_rewards is the usual method, but here is gist if curious. So an array of rewards [1,1,1,1,1,1,1,1,1] becomes an array of returns [1.539, 1.160, 0.777, 0.392, 0.006, -0.382, -0.773, -1.164, -1.556]. Given that basic background I can ask my question: If positive returns are enforced, and negative returns are discouraged (in the optimize step), then no matter the length of the episode, roughly the first half of the actions will be encouraged, and the latter half will be discouraged. Is that true, or am I misunderstanding something? If its NOT true, would love to understand what I got wrong. If it IS true, then I don't understand why the model trains, since even a good-performing episode will have the latter half of its actions discouraged. To reiterate, this is non-batched learning (so the returns are not relative to returns in another episode in the training step). After each episode, the model trains, and again, it trains well :) Hoping this makes sense, and is short enough to feel like a proper clear question.
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/50574354
accepted answer: http://stackoverflow.com/a/50574354
has answer: http://stackoverflow.com/a/69777567
possible better answer: http://stackoverflow.com/a/69777567
downvote count: 0
tagged with: machine-learning
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/49841365
has title: Python mysql.connector AttributeError
has comment: http://stackoverflow.com/comment/86697543
has comment: http://stackoverflow.com/comment/86697583
score: 1
answer count: 1
downvote count: 0
tagged with: mysql
upvote count: 1
favorite count: 0
type: Question
has body: I am using Python 3.6 and mysql-connector 2.1.6 on macOS High Sierra. Following the instructions in the example on this documentation page 'https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnectionpool-constructor.html', when I attempt to create a connection pool as follows: cnxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name = "mypool",pool_size = 3,**dbconfig) I get the following error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2869, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-4-b07112a83246&gt;", line 1, in &lt;module&gt; cnxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name = "mypool",pool_size = 3,\**dbconfig) AttributeError: module 'mysql.connector' has no attribute 'pooling'** I have provided a valid **dbconfig argument. May someone please help explain why it's not working?
has comment: http://stackoverflow.com/comment/86697460
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/62379409

http://stackoverflow.com/comment/86724428
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49845752
has text: you are right, for now i just want button from 1 to 9, plus, minus and equals buttons. the gui working fine and when i press a number is display it in the entry but the equals button isnt working. for example if i want to do 1+2, it will show 1 and ill press the plus button then 2 and in the entry ill still see 2 instead of 3.

http://stackoverflow.com/a/49850924
has comment: http://stackoverflow.com/comment/86717005
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86716994
accepted answer of: http://stackoverflow.com/q/49850895
has body: I believe you need map by dictionary if only 2 possible values exist: labels['bee_type'] = labels['bee_type'].map({'bumble_bee': 1, 'honey_bee': 2}) Another solution is to use numpy.where - set values by condition: labels['bee_type'] = np.where(labels['bee_type'] == 'bumble_bee', 1, 2) Your code works, but for improved performance, modify it a bit - remove loops and add loc: labels.loc[labels['bee_type'] == 'bumble_bee'] = 1 print (labels) ID bee_type 0 1 1 1 1 honey_bee 2 1 1 3 3 honey_bee 4 1 1 Sample: labels = pd.DataFrame({ 'bee_type': ['bumble_bee','honey_bee','bumble_bee','honey_bee','bumble_bee'], 'ID': list(range(5)) }) print (labels) ID bee_type 0 0 bumble_bee 1 1 honey_bee 2 2 bumble_bee 3 3 honey_bee 4 4 bumble_bee labels['bee_type'] = labels['bee_type'].map({'bumble_bee': 1, 'honey_bee': 2}) print (labels) ID bee_type 0 0 1 1 1 2 2 2 1 3 3 2 4 4 1
type: Answer
answers question: http://stackoverflow.com/q/49850895
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49799566
has comment: http://stackoverflow.com/comment/86614112
favorite count: 0
type: Question
has body: I have following html: Please enter domain to add to EDL. Domain: And Python code: #!/usr/bin/python # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields domain2 = form.getvalue('domain') with open('/tmp/pa-allowed-credentials.txt', 'a') as f: f.write(domain2) print "Content-type:text/html\r\n\r\n" print " " print " " print " Hello - Second CGI Program " print " " print " " print " %s added to the list " % (domain2) print " " print " " The problem I'm having is the python script is not writing the value of "domain2" into the file. If i execute the script via "python domain.py" it works correctly.
has comment: http://stackoverflow.com/comment/86614001
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86613899
has comment: http://stackoverflow.com/comment/86614361
tagged with: python
has comment: http://stackoverflow.com/comment/86614391
has comment: http://stackoverflow.com/comment/86613992
has comment: http://stackoverflow.com/comment/86614329
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/86614061
score: 1
upvote count: 1
has title: Python not writing value to a file
has comment: http://stackoverflow.com/comment/86614051
has comment: http://stackoverflow.com/comment/86614344

http://stackoverflow.com/comment/86780522
has text: Fair enough. What version of matplotlib are you using? No legend appears for me when `loop_cols=False` using `matplotlib 2.1.2`
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49881668

http://stackoverflow.com/comment/86823762
type: Comment
comment on: http://stackoverflow.com/a/49887004
type: AnswerComment
score: 0
has text: `a` is `Sequence[Any]` because it was output by a function which return this type. This function can return anything that is of this type, like a `string`, `List` or `Tuples`. Mypy can't be sure you'll end up with a `string`, useless you state it with a `cast(str, a)`. Remember that the type is infered from the typing. Also, `cast` have almost no runtime cost, so use it if you need to. If your function always return a `string` and not a `Sequence[Any]`, change your typing annotation accordingly.

http://stackoverflow.com/q/49907682
tagged with: chatbot
answer count: 0
has title: The kakao autoresponder API has problems accessing the keyboard
score: 1
downvote count: 0
tagged with: django
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I want to make chatbot using kakaotalk. but have problems accessing the keyboard. I use python,pycharm and django. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'globalHaksik', ] urlpatterns = [ path('admin/', admin.site.urls), path('globalHaksik/', include('globalHaksik.urls')), ] urlpatterns = [ path('keyboard/', views.keyboard), ] from django.http import JsonResponse def keyboard(request): return JsonResponse({ 'type': 'buttons', 'buttons': ['오늘', '내일'] }) KakaoTalk shows this error. Required* keyboard Fail 415 wrong keyboard initialization When I use view.py like this, it works fine on the internet. def keyboard(request): return HttpResponse("Hello, world. You're at the polls index.") why is this errer?
tagged with: python

http://stackoverflow.com/q/49841674
has answer: http://stackoverflow.com/a/49841951
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49841984
has comment: http://stackoverflow.com/comment/86698365
has title: Pandas - Sorting MultIndex by the Sum of Sizes
tagged with: python
tagged with: sorting
tagged with: multi-index
has body: I have a Pandas DataFrame that represent requests from users to different websites and each entity in the DataFrame is a request. To simplify the question let it have only 2 columns - website and ip. The data looks like: website.com 1.1.1.1 website.com 1.1.1.1 website.com 1.1.1.1 website.com 1.1.1.1 website.com 1.1.1.2 website1.com 1.1.1.1 website1.com 1.1.1.1 website1.com 1.1.1.3 website1.com 1.1.1.3 website2.com 1.1.1.4 I want to group this DataFrame so that I can see the websites which got most hits sorted in descending order and inside each of these website see the IPs that visited it, also in descending orded. My current solution is: grouped_df = df.groupby(['website', 'IP']) grouped_df.size() which will give me: website IP Size website.com 1.1.1.1 4 1.1.1.2 1 website1.com 1.1.1.1 2 1.1.1.3 2 website2.com 1.1.1.4 1 I can sort this grouped DataFrame by size like grouped_df.size().sort_values(ascending=False) but this will perform sorting based on the number of requests each user made: website IP Size website.com 1.1.1.1 4 &lt;---- sorted by size (N of requests from IP) website1.com 1.1.1.1 2 1.1.1.3 2 website.com 1.1.1.2 1 website2.com 1.1.1.4 1 and not by the sum of requests to a specific website: website IP Size Sum website.com 1.1.1.1 4 5 &lt;---- sorted by sum and sorted by size inside 1.1.1.2 1 website1.com 1.1.1.1 2 4 1.1.1.3 2 website2.com 1.1.1.4 1 1 How can I achieve this?
type: AnsweredQuestion
answer count: 2
tagged with: pandas
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49841951
has answer: http://stackoverflow.com/a/49841984
downvote count: 0

http://stackoverflow.com/a/49817997
has comment: http://stackoverflow.com/comment/86726170
accepted answer of: http://stackoverflow.com/q/49778740
type: Answer
has comment: http://stackoverflow.com/comment/86776238
has comment: http://stackoverflow.com/comment/86727317
has comment: http://stackoverflow.com/comment/92924984
score: 2
has comment: http://stackoverflow.com/comment/86981715
has comment: http://stackoverflow.com/comment/86775806
has comment: http://stackoverflow.com/comment/86985716
upvote count: 2
has comment: http://stackoverflow.com/comment/86726228
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/92923934
has comment: http://stackoverflow.com/comment/86984657
has comment: http://stackoverflow.com/comment/86775690
has comment: http://stackoverflow.com/comment/86985447
has comment: http://stackoverflow.com/comment/86980721
has body: Note: [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions doesn't have an official doc (or at least I couldn't find any), so I'll be using the 2nd best thing available: ActiveState (I could only find references for the ancient Python2.4, but generally they are OK) [ActiveState.Docs]: PyCDC.TextOut wraps [MS.Docs]: TextOutW function. The function doesn't handle \r\n (and definitely other special chars) like print does (the doc doesn't say anything about this), but instead it just ignores them (it doesn't have the concept of line). That means that in order to achieve print - like functionality, the user is responsible for outputting each line individually (of course at a different Y coordinate - to avoid outputting on top of the previous one). To better illustrate the behavior, I created an example (based on your code). code.py: #!/usr/bin/env python3 import sys import time import win32ui import win32con import win32print def get_data_strings(): rows = (("PETER PAUL", "MALE", "100000"), ("MARGARET ", "FEMALE", "1000"), ("MICHAEL JORDAN", "MALE", "1"),("AGNES", "FEMALE", "200")) return ["{:20} {:8} {}".format(*row) for row in rows] def text(): return "\r\n".join(get_data_strings()) def paint_dc(dc, printer_dc, paint_each_string=True): scale_factor = 20 if printer_dc: x_y = 100, 0 # TopLeft of the page. In order to move away from the point, X increases to positives, while Y to negatives font_scale = 10 y_direction_scale = -1 # For printers, the Y axis is "reversed" y_ellipsis = -100 else: x_y = 100, 150 # TopLeft from wnd's client area font_scale = 1 y_direction_scale = 1 y_ellipsis = 100 font0 = win32ui.CreateFont( { "name": "Lucida Console", "height": scale_factor * font_scale, "weight": 400, }) font1 = win32ui.CreateFont( { "name": "algerian", "height": scale_factor * font_scale, "weight": 400, }) fonts = [font0, font1] dc.SelectObject(font0) dc.SetTextColor(0x0000FF00) # 0BGR #dc.SetBkColor(0x000000FF) dc.SetBkMode(win32con.TRANSPARENT) if paint_eac…
answers question: http://stackoverflow.com/q/49778740
has comment: http://stackoverflow.com/comment/86985200

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/49827504
tags question: http://stackoverflow.com/q/49902146
tags question: http://stackoverflow.com/q/49865132
tags question: http://stackoverflow.com/q/49832708
tags question: http://stackoverflow.com/q/49859127
type: Tag

http://stackoverflow.com/comment/86743398
score: 0
has text: @BhushanBabar in default code it was working now I will check .. thank you
type: Comment
comment on: http://stackoverflow.com/a/49863024
type: AnswerComment

http://stackoverflow.com/q/49887715
has comment: http://stackoverflow.com/comment/86792027
has comment: http://stackoverflow.com/comment/86792266
score: 1
tagged with: python-unicode
tagged with: python
tagged with: python-2.x
has comment: http://stackoverflow.com/comment/86834908
has comment: http://stackoverflow.com/comment/86792220
has comment: http://stackoverflow.com/comment/86792761
has comment: http://stackoverflow.com/comment/86791828
has comment: http://stackoverflow.com/comment/86791822
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86829980
has comment: http://stackoverflow.com/comment/86791797
type: UnansweredQuestion
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/49746807
upvote count: 1
has comment: http://stackoverflow.com/comment/86791600
has title: Error decoding byte string in Python3 [TypeError: must be str, not bytes]
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86796464
has answer: http://stackoverflow.com/a/60964939
has body: I'm trying to use in Python 3.6 a piece of code written for Python 2.7, and I'm having trouble managing differences in how byte strings are handled. The code is meant to read a .dat file that existed before I wrote my code. Running the untouched P2.7 script returns the following error: import numpy as np buff = '' dt = np.dtype([('var1', np.uint32, 1), ('var2', np.uint8, 1)]) with open(filename, 'rb') as f: for line in f: dat = line ---&gt; buff += dat data = np.frombuffer(buffer=buff, dtype=dt) TypeError: must be str, not bytes If I get it right, while Python2 will concatenate the read bytes into the string buff without complaining, Python3 cares about the difference between bytes and strings. Typecasting line to str(line) returns the following error: for line in f: dat = str(line) buff += dat -&gt; data = np.frombuffer(buffer=buff, dtype=dt) AttributeError: 'str' object has no attribute '__buffer__' How should I go about it? What type should buff be? Any solutions that would work for P2.7 and P3.6? EDIT It turns out the data in filename.dat is not made of unicode strings at all. I've edited the question to remove mention to my mistaken assumption, and I've added lines of code I'd omitted in trying to show a minimal example that I now realize are relevant. Sorry for the confusion.

http://stackoverflow.com/comment/86660975
comment on: http://stackoverflow.com/q/49822424
has text: does it mean that you move forward of 250ms, right? how are you selecting a DF portion of 1 second?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49761056
has answer: http://stackoverflow.com/a/49761534
has title: Save output of a command execution with subprocess
has body: I am trying to get output of subprocess.Popen in variable. It is working fine for pwd command, but not working for pwdx $(pgrep -U $USER -f SimpleHTTPServer) command. This works: (Pdb++) p = subprocess.Popen("pwd", stdout=subprocess.PIPE) (Pdb++) result = p.communicate()[0] (Pdb++) result 'xyz' This is not working: (Pdb++) subprocess.Popen("pwdx $(pgrep -U $USER -f SimpleHTTPServer)", stdout=subprocess.PIPE) *** OSError: [Errno 2] No such file or directory Can someone please let me know how can I save the output of it to a variable?
type: Question
possible better answer: http://stackoverflow.com/a/49761534
tagged with: python
tagged with: python-2.7
tagged with: subprocess
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49761160
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49761160

http://stackoverflow.com/q/49816503
tagged with: python
has title: How to get weights for custom loss function in pytorch?
score: 3
tagged with: pytorch
upvote count: 3
answer count: 1
downvote count: 0
tagged with: loss-function
favorite count: 0
type: Question
has body: I have a model in pytorch and would like to add L1 regularization insde the loss_function. But I don't want to pass the weights to the loss_function() - is there a better way of doing this? For details see the loss_function() below. class AutoEncoder(nn.Module): def __init__(self, inp_size, hid_size): super(AutoEncoder, self).__init__( self.lambd = 1. # Encoder self.e1 = nn.Linear(inp_size, hid_size) # Decoder self.d1 = nn.Linear(hid_size, inp_size) self.sigmoid = nn.Sigmoid() pass def forward(self,x): encode = self.e1(x) decode = self.sigmoid(self.d1(encode)) return decode def loss_function(self, recon_x, x): l2_loss = nn.MSELoss() # Here I would like to compute the L1 regularization of the weight parameters loss = l2_loss(recon_x, x) + self.lambd(l1_loss(self.e1) + l1_loss(self.e2)) return loss
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49853098

http://stackoverflow.com/a/67383100
type: Answer
has body: I was faced with the same error when running on Google Colab. here's what fixed for me: %pip install mlxtend --upgrade
downvote count: 0
upvote count: 7
answers question: http://stackoverflow.com/q/49889524
score: 7

http://stackoverflow.com/comment/88113466
score: 1
comment on: http://stackoverflow.com/a/50196309
has text: sorry for being so late, I got busy during my exams and by mistake overlooked your answer. Thanks for helping me out :)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86804964
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49894665
has text: Instead of having Chinese words for example I have these characters which prevents my tokenization. I also have these characters for line breaks which are then considered as words during tokenization

http://stackoverflow.com/comment/86744836
comment on: http://stackoverflow.com/a/49861759
type: Comment
score: 0
type: AnswerComment
has text: @Basj After flattening, you have a single query with two AND-connected conditions (i.e., what you started with).

http://stackoverflow.com/comment/86628843
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49806945
has text: @ Prune, Python 2.7 and it works so I believe it's legal.

http://stackoverflow.com/comment/86595756
type: Comment
comment on: http://stackoverflow.com/a/49790081
type: AnswerComment
score: 1
has text: Thanks for the answer, it's really helpful! May I ask another question? What is the faster way to iterate 2d array in python? Thanks!

http://stackoverflow.com/comment/86624938
type: QuestionComment
comment on: http://stackoverflow.com/q/49804102
score: 0
has text: do you have any idea where the shape (8,) came from?
type: Comment

http://stackoverflow.com/q/49801197
answer count: 1
downvote count: 0
has title: How to deploy python and node js at same time at same domain in google app engine?
upvote count: 1
has body: I have a web application that I want to deploy it in Google cloud. It built with python and node js which node js communicates with python. How can I deploy the app with two different runtime ? The node js .yaml: runtime: nodejs api_version: 1 env: flex python .yaml runtime: python env: flex threadsafe: true runtime_config: python_version: 3 health_check: enable_health_check: True check_interval_sec: 5 timeout_sec: 4 unhealthy_threshold: 2 healthy_threshold: 2
favorite count: 0
linked to: http://stackoverflow.com/q/45332283
tagged with: express
has answer: http://stackoverflow.com/a/49802027
tagged with: google-app-engine
score: 1
tagged with: python
tagged with: google-cloud-storage
tagged with: node.js
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/43218971

http://stackoverflow.com/a/49823968
upvote count: 1
type: AcceptedAnswer
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49823117
has body: You're probably writing to the wrong serial port, which can change depending on the device, or even just when disconnecting and reconnecting a device.
answers question: http://stackoverflow.com/q/49823117
downvote count: 0

http://stackoverflow.com/q/49909773
has comment: http://stackoverflow.com/comment/86835687
tagged with: python
tagged with: numeric
tagged with: numpy
has comment: http://stackoverflow.com/comment/87784128
answer count: 0
upvote count: 2
tagged with: matrix
score: 1
has comment: http://stackoverflow.com/comment/86835523
has body: To calculate the eigenvalues of a Laplacian matrix, I used the function numpy.linalg.eig. The least positive eigenvalue I obtained was 2.6645352591003757e-15. What is wrong in the calculation? Is it related to floating point arithmetic?
downvote count: 1
tagged with: eigenvalue
favorite count: 0
has comment: http://stackoverflow.com/comment/86835595
type: Question
has comment: http://stackoverflow.com/comment/86835769
type: UnansweredQuestion
has title: Least positive eigenvalue of a Laplacian matrix

http://stackoverflow.com/comment/86582242
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49783418
type: Comment
has text: @MrYouMath: aarrghh.. the functions are not returning, but printing? Why? Usually you only want a very small subset to `print`. It is still possible, but very "unelegant". Anyway, I've made an edit such that it works now.

http://stackoverflow.com/comment/86578062
has text: Thank you for the response... a few questions: Do you need robot for singleton classes? Which py file would I implement the singleton class? Or does it get it's own?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49769915

http://stackoverflow.com/a/49783240
answers question: http://stackoverflow.com/q/49783178
has comment: http://stackoverflow.com/comment/133228892
has comment: http://stackoverflow.com/comment/139022461
type: Answer
downvote count: 1
upvote count: 75
has comment: http://stackoverflow.com/comment/86581900
has comment: http://stackoverflow.com/comment/107828159
score: 74
has comment: http://stackoverflow.com/comment/86583599
has body: You should specify what pandas must do with the other columns. In your case, I think you want to keep one row, regardless of its position within the group. This could be done with agg on a group. agg accepts a parameter that specifies what operation should be performed for each column. df.groupby(['name'], as_index=False).agg({'value1': 'sum', 'value2': 'sum', 'otherstuff1': 'first', 'otherstuff2': 'first'})
has comment: http://stackoverflow.com/comment/107871769

http://stackoverflow.com/q/49881114
type: Question
has answer: http://stackoverflow.com/a/49881235
tagged with: pyqt4
downvote count: 0
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/86778039
tagged with: if-statement
upvote count: 3
answer count: 1
linked to: http://stackoverflow.com/q/60208
has body: I have a function that pops-up a message box after you click on a button using PyQt4 in python. I use 'sender()' to determine which button was clicked and then set the text of pop-up window accordingly. This function works perfectly with 'if statements'. However I was wondering how do I write a function with same functionality using a dictionary (since there is no switch statement in python and there are too many if statements in my code)? def pop_up(self): msg = QtGui.QMessageBox() msg.setIcon(QtGui.QMessageBox.Information) sender = self.MainWindow.sender() if sender is self.button1: msg.setText("show message 1") elif sender is self.button2: msg.setText("show message 2") elif sender is self.button3: msg.setText("show message 3") elif sender is self.button4: msg.setText("show message 4") elif sender is self.button5: msg.setText("show message 5") elif sender is self.button6: msg.setText("show message 6") . . . . . elif sender is self.button36: msg.setText("show message 36") msg.exec()
accepted answer: http://stackoverflow.com/a/49881235
tagged with: switch-statement
favorite count: 0
has title: How to use dictionary instead of if statement in python?

http://stackoverflow.com/comment/86569541
has text: There isn't in the example, but I see what you are saying. You could check the length list created, and if it's correct you are good to go. If not try something like splitting on: ),( I'd try it before I over engineer a solution. Working with regexes is often trial and error.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49776579
type: Comment

http://stackoverflow.com/q/49910393
tagged with: python
linked to: http://stackoverflow.com/q/16288497
score: 0
has title: count word occurrences with sklearn
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86859688
tagged with: scikit-learn
has body: I'm trying to get the most frequent words, and in a future, bigrams, trigrams, etc, in my corpus. I found this quiestion but it didn't work for me, and I want to avoid using zip since I want it in a more efficient way. Up to now I have this code: vectorizer_words = CountVectorizer(input=u'content', analyzer=u'word', lowercase=True, stop_words=cached_stopwords, strip_accents=u'unicode', ngram_range=(1, 1), binary=False) vectors = vectorizer_words.fit_transform(X, y) N, V = vectors.shape count_words = np.array(np.sum(vectors, axis=0)) count_words = np.squeeze(count_words) assert count_words.shape == (V,), "count_words.shape = {}".format(count_words.shape) words = np.array(vectorizer_words.get_feature_names()) assert words.shape[0] == V a = count_words.argsort()[::-1] print(words[a][:10]) print(count_words[a][:10]) plt.bar(words[a][:10], count_words[a][:10]) plt.title('title') plt.show() I was expecting my graph to be descending but it does not, and I can't understand why. I'm doing something wrong (what?) or I'm misunderstanding the output? EDIT The problem seem to be in the plt.bar: looking more carefully at the output of the following lines: print(words[a][:10]) print(count_words[a][:10]) # Output: ['atencion' 'bien' 'mas' 'banco' 'buena' 'siempre' 'problemas' 'problema' 'tarjeta' 'rapido'] [10442 7594 6322 6121 5382 4953 4316 4202 4041 3097] So count_words[a] is sorted as expected, but the plot is in alphabetical order (as suggested in comments, thanks!), so the problem probably is in the plot
type: Question
tagged with: numpy
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86842031

http://stackoverflow.com/comment/86859674
comment on: http://stackoverflow.com/a/49907046
type: AnswerComment
has text: A better answer would have been: `from resources import image1` That answers the question and is correct code.
score: 0
type: Comment

http://stackoverflow.com/q/49902438
type: Question
tagged with: beautifulsoup
has title: Python loop not reading through Beautifulsoup contents
tagged with: for-loop
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49904673
tagged with: python
score: 0
answer count: 1
has body: I wrote a for-loop that I thought was extracting the text from the html elements that I had indicated using the Beautifulsoup library. It looks like this: url = "https://www.researchgate.net/profile/David_Severson" r = requests.get(url) data = r.text soup = bsoup(data, "lxml") item = soup.find("div", {"class": "section section-research"}) papers = [paper for paper in item.find_all("div", {"class": "nova-o-stack__item"})] for p in papers: title = p.find("div", {"class": "nova-e-text nova-e-text--size-l nova-e-text--family-sans-serif nova-e-text--spacing-none nova-e-text--color-inherit nova-v-publication-item__title nova-v-publication-item__title--clamp-3"}) abstract = p.find("div", {"class": "nova-e-text nova-e-text--size-m nova-e-text--family-sans-serif nova-e-text--spacing-none nova-e-text--color-inherit nova-v-publication-item__description nova-v-publication-item__description--clamp-3"}) views = p.find("ul", {"class": "nova-e-list nova-e-list--size-m nova-e-list--type-inline nova-e-list--spacing-none nova-v-publication-item__metrics"}) date = p.find("li", {"class": "nova-e-list__item publication-item-meta-items__meta-data-item"}) authors = p.find("ul", {"class": "nova-e-list nova-e-list--size-m nova-e-list--type-inline nova-e-list--spacing-none nova-v-publication-item__person-list"}) link = p.find("a", {"class": "nova-e-badge nova-e-badge--color-green nova-e-badge--display-block nova-e-badge--luminosity-high nova-e-badge--size-l nova-e-badge--theme-solid nova-e-badge--radius-m nova-v-publication-item__type"}, href=True) if link: full_link = urllib.parse.urljoin("https://www.researchgate.net/", link["href"]) print(full_link) print(p.text) I noticed that it was printing out more than what I had indicated in the contents of the loop. After trying to debug each of the individual items (title, abstract etc...), I realized the loop was not even accessing the items therein at all. For example, if I commented them all out, or totally remove them, it still gave the exact s…
tagged with: web-crawler

http://stackoverflow.com/comment/86669921
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49827117
has text: @Prune I edited it.
score: 0

http://stackoverflow.com/q/49865689
downvote count: 0
upvote count: 1
has title: Pulling numbers in text str from pdf after a character with no white space
accepted answer: http://stackoverflow.com/a/49865801
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49865801
tagged with: python
has body: I am new to python / programming in general. I'm trying to pull a six digit number following an alpha character in a string like this: A12345612341234 asdfa we'a aslkfj4353 alsdfasA345678asA858585943 So in the above I would want to pull A123456 and loop to pull A345678 and A858585. How can I do that? I'm using PyPDF2 to pull the text from a pdf and set it to a variable, but I've tried splicing and lists, but I can't figure out how to get it to work. I've spent some time searching the internet and find tons of examples, but they don't relate to my situation, most have whitespace. Seems like it should be real simple. This is what I'm working on #import PyPDF2 and set extracted text as the page_content variable import PyPDF2 pdf_file = open('5302.pdf','rb') read_pdf = PyPDF2.PdfFileReader(pdf_file) number_of_pages = read_pdf.getNumPages() page = read_pdf.getPage(0) page_content = page.extractText() #initialize the user_input variable user_input = "" #function to get the AFE numbers from the pdf document def get_afenumbers(Y): #initialize the afe and afelist variables afe = "A" afelist = "" x = "" #Make a while loop of this after figuring out how to get only 6 digits #after the "A" use .isdigit() somehow? while True: if user_input.upper().startswith("Y") == True: #Find the letter A and extract it and its following 6 digits if "A" in page_content: #right now only getting everything after first A afe = page_content[page_content.find("A")+1:] #Add AFEs to afelist afelist += afe #Build a string of AFEs seperated by a new line character x = x + '\n' + afe print(afe) break else: afe = "No AFE numbers found..." if user_input.upper().startswith("N") == True: print("HAVE A GREAT DAY - GOODBYE!!!") break #Build a while loop for initial question prompt (when Y or N is not True): while user_input != "Y" and user_input != "N": user_input = input('List AFE numbers? Y or N: ').upper() if user_input not in ["Y","N"]: print('"',user_input,'"','is an invalid input') get_afenumbers(user_i…
type: AnsweredQuestion
score: 1
answer count: 1

http://stackoverflow.com/q/49799535
tagged with: differential-equations
answer count: 1
tagged with: python
tagged with: scipy
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86621397
linked to: http://stackoverflow.com/q/40866387
score: 9
upvote count: 9
tagged with: numerical-methods
downvote count: 0
accepted answer: http://stackoverflow.com/a/49802019
has answer: http://stackoverflow.com/a/49802019
tagged with: runge-kutta
has body: I am a physics student interested in solving ODEs numerically. I usually write my own solvers in C using Runge–Kutta methods. I recently learned Python, and I used SciPy’s odeint function to solve ODEs. But I am worried about how the function algorithm works, because it not take a step size argument. So, how can I learn how it works? How can I know what is the precision of their results? I consulted this documentation, but it does not offer very much information, and I don’t really understand the optional arguments that they describe.
type: AnsweredQuestion
has title: How does odeint() from scypy python module work?

http://stackoverflow.com/comment/86785106
has text: You never use your `v` variable. You can use `v` instead of `d[k]`. But more importantly, why not invert the dict and swap keys with values? You'd change `res_dict[(k, k2)] = v2` to `res_dict[v2] = (k, k2)` and then `minval = min(res_dict)` and `res = res_dict[minval]`.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49884426

http://stackoverflow.com/comment/86679383
score: 1
comment on: http://stackoverflow.com/q/49831995
type: QuestionComment
has text: You're going to have to post a dataframe showing your desired outcome, I'm unsure of what you mean.
type: Comment

http://stackoverflow.com/comment/86741298
has text: Maybe you need to specify `\\ ` due to escaping by Python?
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49858395

http://stackoverflow.com/comment/86748967
type: Comment
comment on: http://stackoverflow.com/a/49866584
score: 0
type: AnswerComment
has text: thank you for explaining where the bug comes from. Do I feel silly for not thinking of the solution. Thanks!

http://stackoverflow.com/a/49839874
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49839680
type: Answer
has body: Ok so previous answers are not totally complete. The main difference between the 1 and 1. is in their type and type of the result of any equation that include float number in python will be float. That include addition subtraction multiplication exponents and even the integer division as if one operand is float answer will be of type float. Also as others mentioned it is there mainly for the compatibility with python2 but be aware that in that expression if the one num is float then result will always be float. ..# 1. / 4 0.25 ..# 1 / 4 0.25 ..# type(1.) &lt;class 'float'&gt; ..# type(1) &lt;class 'int'&gt; ..# 1 // 4 0 ..# 1. // 4 0.0 ..# type(1. // 4) &lt;class 'float'&gt; ..# type(1 // 4) &lt;class 'int'&gt; I changed the interpreter &gt;&gt;&gt; to ..# as stack editor shows that in multi line as quote level. So basically if you want to ensure that code snippet will always have a float value you make one of numbers float.

http://stackoverflow.com/comment/86633413
has text: It's hard to give a concrete example without knowing a bit more about your XML data, but you probably want to look into the [`xml.sax`](https://docs.python.org/3.6/library/xml.sax.html) package.
type: QuestionComment
comment on: http://stackoverflow.com/q/49764084
score: 0
type: Comment

http://stackoverflow.com/comment/86599870
comment on: http://stackoverflow.com/q/49791920
has text: Don't do this. Use a dict.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49823075
answer count: 1
accepted answer: http://stackoverflow.com/a/49823167
has comment: http://stackoverflow.com/comment/86663274
favorite count: 0
type: Question
has title: Django pagination: How do 'paginator' and 'page_obj' get injected into a template's context?
tagged with: django
has answer: http://stackoverflow.com/a/49823167
tagged with: python
type: AnsweredQuestion
upvote count: 3
score: 3
has body: I'm trying to understand some source code which is used in a ListView to generate pagination links at the bottom of the page. For example, on a page listing 'experts', it looks like this: It seems to be implemented somewhat differently from the way described in https://docs.djangoproject.com/en/2.0/topics/pagination/. There is an inclusion tag called paginator: from django import template from django.core.paginator import EmptyPage from dashboard.views.utils import query_dict_from_params_or_cookies register = template.Library() def query_params(params): query = params.copy() if query.get('page'): del query['page'] return '&' + query.urlencode() if query.urlencode() else '' @register.inclusion_tag('templatetags/paginator.html', takes_context=True) def paginator(context, adjacent_pages=2): request = context['request'] page_obj = context['page_obj'] page_range = context['paginator'].page_range page_number = page_obj.number last_page_number = len(page_range) left_idx = max(0, page_number - adjacent_pages - 1) right_idx = min(page_number + adjacent_pages, last_page_number) if left_idx == 2: left_idx -= 1 if right_idx == last_page_number - 2: right_idx += 1 window = page_range[left_idx:right_idx] try: previous_page_number = page_obj.previous_page_number() except EmptyPage: previous_page_number = None try: next_page_number = page_obj.next_page_number() except EmptyPage: next_page_number = None params = query_dict_from_params_or_cookies(request) return { 'has_previous': page_obj.has_previous(), 'has_next': page_obj.has_next(), 'previous_page_number': previous_page_number, 'next_page_number': next_page_number, 'last_page_number': last_page_number, 'page_range': window, 'page_number': page_number, 'show_first': page_number > adjacent_pages + 1, 'show_left_gap': page_number > adjacent_pages + 3, 'show_last': page_number < last_page_number - adjacent_pages, 'show_right_gap': page_number < last_page_number - adjacent_pages - 2, 'query_params': query_params(params) } The correspo…
downvote count: 0
tagged with: pagination

http://stackoverflow.com/q/49790723
tagged with: rest
has title: Django REST: serialize url to list of objects of a category
tagged with: django
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/49813021
type: UnansweredQuestion
answer count: 1
has body: Hard facts: I am using Django 2.0 with python 3.6, if it makes any difference. What I am trying to achieve is a link to a list of objects that belong to a summary. I have a ManyToOne relationship in my models.py. class Summary(models.model): type=models.CharField class Object(models.Model): summary= models.ForeignKey(Summary, on_delete=models.CASCADE) in urls.py object_list= views.ObjectListViewSet.as_view({ 'get': 'list' }) urlpatterns = format_suffix_patterns([ url(r'^summary/(?P&lt;pk&gt;[^/.]+)/objects/$', object_list, name='summary-objects') ]) and now the idea was to give a user the possibility to click the an url in the browsable API and getting all objects. So, I tried to write a MethodField in serializers.py. I am not able to get any reasonable URL here, the only solution would be to hardcode it. class SummarySerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name="app:summary-detail") objects= serializers.SerializerMethodField('get_obj_url') def get_obj_url(self, obj): pass class Meta: model = Summary Is this possible? Is it necessary to write a MethodField? If yes, how do I get the url I need?
type: Question
tagged with: serialization
has comment: http://stackoverflow.com/comment/86596587

http://stackoverflow.com/a/49852517
has comment: http://stackoverflow.com/comment/86759654
answers question: http://stackoverflow.com/q/49852390
has comment: http://stackoverflow.com/comment/86761049
has body: Simply remove the timezone tag from datetime import datetime import dateutil.parser as dparser date_str='December 31, 2020 5:59:59 PM' date=dparser.parse(date_str) print 'date =',date,'CST' Output date = 2020-12-31 17:59:59 CST
score: 0
type: Answer

http://stackoverflow.com/comment/86591902
type: Comment
comment on: http://stackoverflow.com/q/49788464
score: 0
has text: Or, if you can't use sets, just use dictionaries: `dict(e: 1 for e in (setA + setB)).keys()`
type: QuestionComment

http://stackoverflow.com/a/51964830
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49810566
type: Answer
has body: Try different config parameters in below line result = pytesseract.image_to_string(Image.open(img_path))#src_path+ "thres.png")) Like as shown below: result = pytesseract.image_to_string(Image.open(img_path))#src_path+ "thres.png"), config='--psm 1 --oem 3') Try to change the psm value and compare the results -- Good Luck --

http://stackoverflow.com/a/49884395
has body: You could do df["tmp"] = df.duplicated(subset = ["date", "amp", "rounds"]) df2 = df.set_index(["date", "emp"]) df2["example"]= df.groupby(["date", "emp"])["tmp"].sum() df2 = df2.drop("tmp", 1).reset_index() date emp amount vendor rounds example 0 1 a 4.9 x 5.0 1.0 1 1 a 4.8 x 5.0 1.0 2 2 a 1.0 y 1.0 0.0 3 3 b 6.0 z 6.0 2.0 4 3 b 5.6 z 6.0 2.0 5 3 b 5.4 z 6.0 2.0 We start with your provided df. The first line df["tmp"] = df.duplicated(subset = ["date", "amp", "rounds"]) creates a temporary column that indicates whether a row is duplicated or not, i.e. amount date emp vendor rounds tmp 0 4.9 1 a x 5.0 False 1 4.8 1 a x 5.0 True 2 1.0 2 a y 1.0 False 3 6.0 3 b z 6.0 False 4 5.6 3 b z 6.0 True 5 5.4 3 b z 6.0 True The second and third lines df2 = df.set_index(["date", "emp"]) df2["example"]= df.groupby(["date", "emp"])["tmp"].sum() Just assign the sum of the groups of date and emp to column example. It does this by setting the indexes to be the same. When two data frames have the same index, you can assign values of one to the other even if the number of rows is different: pandas will infer that values should duplicated as long as indexes are the same. The last column just drops the tmp.
has comment: http://stackoverflow.com/comment/86785357
score: 1
has comment: http://stackoverflow.com/comment/86785292
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86784836
has comment: http://stackoverflow.com/comment/86785411
has comment: http://stackoverflow.com/comment/86785922
has comment: http://stackoverflow.com/comment/86785150
type: Answer
answers question: http://stackoverflow.com/q/49884072

http://stackoverflow.com/q/49782869
downvote count: 0
has body: I got multiple Spiders with different items and i want to export each item into a different csv file. I used the code example from How can scrapy export items to separate csv files per item, but there is a problem. Right now my spider will only write the "page" item. All items is filled in the shell but the files keep being empty. I debugged the pipeline, but I didn't found an error so far. Here is my spider: import csv import scrapy from BeautifulSoup import BeautifulSoup from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor from scrapy.spiders import Rule from DataSpiders import CSV_PATH from ScrapingItems import TrierDeItem from SuperSpider import SuperSpider HTML_PATH = 'pages/trier.de/' class TrierDeSpider(scrapy.Spider, SuperSpider): name = 'trierDeSpider' allowed_domains = ['trier.de'] denied_domains = [] start_urls = [ 'https://www.trier.de/rathaus-buerger-in/trier-in-zahlen/', 'https://trier.de/startseite/', 'https://www.trier.de/leben-in-trier/', 'https://www.trier.de/kultur-freizeit/', 'https://www.trier.de/wirtschaft-arbeit/', 'https://www.trier.de/bildung-wissenschaft/', 'https://www.trier.de/bauen-wohnen/', 'https://www.trier.de/umwelt-verkehr/', ] # Set starting point for the spider and starts crawling from start_urls rules = (Rule(LxmlLinkExtractor(allow=()), callback='parse', follow=True),) def parse(self, response): """ Parse for Links Page Body. Follow allowed Domains by adding them to the request. Parse the current page with callback and the method parse_page. :param response: :return: """ for link in LxmlLinkExtractor(allow=self.allowed_domains, deny=self.denied_domains).extract_links(response): yield scrapy.Request(response.urljoin(link.url), callback=self.parse_page) def parse_page(self, response): """ Parse the current page for information. :param response: :return: """ trier_de_item = TrierDeItem() yield self.parse_general_page_info(response, HTML_PATH) # extract the page url trier_de_item["url"] = response.url # extract the crawling …
tagged with: scrapy
favorite count: 0
type: Question
has title: Scrapy MultiCSVItemPipeline exports some empty items
linked to: http://stackoverflow.com/q/12230332
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: 2
tagged with: export-to-csv
tagged with: python-2.7
upvote count: 2
has answer: http://stackoverflow.com/a/49828820
answer count: 1

http://stackoverflow.com/q/49811955
type: Question
answer count: 9
tagged with: postgresql
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49813679
score: 49
has answer: http://stackoverflow.com/a/68374830
tagged with: python
has answer: http://stackoverflow.com/a/49812755
tagged with: psycopg2
has answer: http://stackoverflow.com/a/63640659
has body: I'm using MAC and python version 2.7.14 Collecting psycopg2 Could not fetch URL https://pypi.python.org/simple/psycopg2/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:661) - skipping Could not find a version that satisfies the requirement psycopg2 (from versions: ) No matching distribution found for psycopg2
has answer: http://stackoverflow.com/a/68792766
has comment: http://stackoverflow.com/comment/86651369
has title: Unable to install psycopg2 (pip install psycopg2)
upvote count: 50
tagged with: pip
has answer: http://stackoverflow.com/a/49812230
has answer: http://stackoverflow.com/a/72482470
downvote count: 1
linked to: http://stackoverflow.com/q/40001881
linked to: http://stackoverflow.com/q/49748063
has answer: http://stackoverflow.com/a/73106835
has answer: http://stackoverflow.com/a/71561100
favorite count: 0

http://stackoverflow.com/a/49859054
answers question: http://stackoverflow.com/q/49858937
score: 0
has comment: http://stackoverflow.com/comment/86910171
has body: This may be an installation problem. Check in your python installation folder whether there is a file multipart.py in Lib/email/mime folder. Hope this helps!
type: Answer

http://stackoverflow.com/q/49880156
accepted answer: http://stackoverflow.com/a/49880488
has body: Why am I getting bad request for this post calls? It has to do with json formatting. How do I reformat the json object passed as param? I'm running a load test using LocustIO and Python. from locust import HttpLocust, TaskSet, task from slumber import API import json, requests nameInquiry = """ [{ "data": { "Account Number": "1234567898", "Bank Code": "EBN", "AppId": "com.appzonegroup.zone", "deviceId": "a4a7427032c286e3", "Sender Phone Number": "+2348094399450", "Sender Conversation ID": "161503479186618e8726fc4-70c0-4768-a2ea-5217c3a3c26d", "FileId": "" }, "instruction": { "FunctionId": "", "FlowId": "813dac4f-7e44-4873-b45f-f6f3b5dbe436", "InstitutionCode": "", "TimeOutSeconds": 30 } }] """ myheaders = {'Content-Type': 'application/json', 'Accept': 'application/json'} class NameInquiries(TaskSet): @task(1) def send(self): response = self.client.post("/zoneflowsapi/api/Goto/goto/", data=json.dumps(nameInquiry), headers= myheaders ) print("Response status code:", response.status_code) print("Response content:", response.text)
has answer: http://stackoverflow.com/a/49880488
type: AnsweredQuestion
answer count: 2
score: 2
upvote count: 2
downvote count: 0
tagged with: locust
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/58610866
has answer: http://stackoverflow.com/a/58610866
tagged with: http://stackoverflow.com/tag/json
has title: Formatting Json for Python LocustIO
tagged with: python

http://stackoverflow.com/a/50200104
type: Answer
downvote count: 0
upvote count: 1
has body: This should work if you access the prefetched pizzas like this: topping.pizza_set.all() If you do something like topping.pizza_set.filter(...some conditions etc...) then it won't work and this is expected (as only specific query result is prefetched).
score: 1
answers question: http://stackoverflow.com/q/49844181

http://stackoverflow.com/q/49883072
downvote count: 0
has answer: http://stackoverflow.com/a/49911236
possible better answer: http://stackoverflow.com/a/49911236
has body: I have a problem on ONE specific OSX machine used for auto-testing, that os.listdir raises OSError. The funny thing is that: os.path.exists("/Volumes/label_of_mounted_drive") -&gt; True os.path.isdir("/Volumes/label_of_mounted_drive") -&gt; True but os.listdir("/Volumes/label_of_mounted_drive") -&gt; OSError ([Errno 2] No such file or directory) stat for the path is posix.stat_result(st_mode=16877, st_ino=1, st_dev=939524119, st_nlink=2, st_uid=502, st_gid=20, st_size=68, st_atime=1523980718, st_mtime=1523980718, st_ctime=1523980718) The drive is mounted, visible and usable in finder. I can list it via terminal. I can even list it via separate python process (e.g. calling subprocess and 'python', '-c', 'import os; print os.listdir("the_path_here")') The even funnier part is that it was working 2 days ago, and now it stopped*. In addition - running python in terminal - listdir works on this particular path, running tests via nosetests / unittests - listdir is broken. Now this is NOT THE FIRST time this has happen on this particular machine. Last time I just reinstalled the whole system and it fixed it. Now - I'm planning to do the same - but at this point I'm just SUPER curious what is causing this. Any thoughts? *it stopped working after I switched from virtualenv to pyenv-virtualenv. BUT after some time and many other tries, I uninstalled all brew packages and brew itself, created new fresh user, removed the old user, installed brew and python on new user from scratch, and went back to simple virtualenv, all to no success :( Machine setup is: Sierra 10.12.6 brew python@2 xcode 9.2 some of the installed libs are: brew: zlib, libjpeg python: matplotlib, Pillow, lxml, pyobjc
tagged with: macos
favorite count: 0
type: Question
tagged with: listdir
tagged with: matplotlib
tagged with: python
type: AnsweredQuestion
has title: os.listdir raises OSError, but path exists and is corectly passed to python
answer count: 2
tagged with: operating-system
has answer: http://stackoverflow.com/a/50330634
score: 1
accepted answer: http://stackoverflow.com/a/50330634
upvote count: 1

http://stackoverflow.com/q/49821337
has comment: http://stackoverflow.com/comment/86705247
tagged with: python-2.7
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/86683196
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/29218750
has body: { "Food" : { "Abc" : "xyz", "Meat" : { "kind" : "Turkey", "Size" : {}, "Id" : "9747" }, "Fruit" : [{ "Name" : "Orange", "Code" : "Fr", "NewCode" : "Fu1" }, { "Name" : "Apple", "Code" : "App", "Id" : "23" }, { "Name" : "Grape", "Code" : "Grp" } ], "Vegetables" : {} } } I need check if 'Id' is present in Meat, Fruit and Vegetables and if it is present then delete the Id(Key - Value) pair. Sometimes Id is present (ex. Meat and Fruit) or not present for a particular section(Fruit --> Grape) or sometime nothing is present (Vegetables). I've been able to remove Abc(Key-Value) pair but i've not been able to do the same for Meat, Fruit and Vegetables dictionaries. Can someone help me out.
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86661280
type: Question
duplicate of: http://stackoverflow.com/q/29218750
score: 1
has comment: http://stackoverflow.com/comment/86658236
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/86711408
has title: How can delete Key and values in Jsons using python
tagged with: python

http://stackoverflow.com/comment/86780624
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49882253
score: 0
has text: @NikitaPolovinkin use `BeautifulSoup`

http://stackoverflow.com/q/49773582
has answer: http://stackoverflow.com/a/51889351
tagged with: h2o
tagged with: python
has body: I randomly encounter the same error whenever I run XGBoost model (both the normal run and grid search). The error message says this: H2OConnectionError: Local server has died unexpectedly. RIP. I don't know what happens, I tried to change versions but didn't work. I'm currently using the version 3.18.0.5. Does anyone have any idea what is happening? Thanks in advance
tagged with: artificial-intelligence
has title: Error every time running H2OXGBoostEstimator
favorite count: 0
type: Question
upvote count: 4
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86571137
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86590448
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/89930509
score: 4
tagged with: xgboost
has comment: http://stackoverflow.com/comment/86662097

http://stackoverflow.com/q/49830657
score: -1
has comment: http://stackoverflow.com/comment/86676859
has comment: http://stackoverflow.com/comment/86678057
favorite count: 0
type: Question
has title: Python Spell Checker Using Linear Search
upvote count: 0
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/86676735
type: AnsweredQuestion
has body: I am trying to write a spellchecker using a linear search which takes Shakespeares full works and compares it to a 10,000 word dictionary. I want the code to output all words in Shakespeares full works which aren't in the dictionary. I have attached pictures of my current output as well as pictures of the output I am looking for. The code I currently have doesn't produce any errors however as seen from the current output displays all words in Shakespeares full works. Any help here is appreciated. https://i.sstatic.net/Oc7BQ.jpg: Current Output https://i.sstatic.net/Z1tsE.jpg: Output I'm looking for import re import time start_time = time.time() def LinearSearch(Target, Words): #Linear search for target in words. Words need not be sorted. for s in Words: if s==Target: return True return False # Gets the Dictionary. Words = [s.strip("\n").lower() for s in open("10kWords.txt")] # Gets ShakespearesFullWorks and Encodes it. Input_File = open('ShakespeareFullWorks.txt', "r", encoding='utf-8') lines = Input_File.readlines() for x in lines: if not LinearSearch(x, Words): print (re.findall(r"[\w']+", x)) print ("--- %s seconds ---" % (time.time() - start_time))
accepted answer: http://stackoverflow.com/a/49830957
tagged with: linear-search
answer count: 1
has answer: http://stackoverflow.com/a/49830957

http://stackoverflow.com/comment/86754339
type: QuestionComment
comment on: http://stackoverflow.com/q/49869250
type: Comment
score: 0
has text: Alternatively, calling sort with the pandas data structure didn't actually do what you think it did, as in my code I commented out the first sort, the first line of output was `0 1916`, which tells me your code with pandas didn't cause the sorting to happen.

http://stackoverflow.com/q/49840020
type: AnsweredQuestion
score: 0
tagged with: iterator
answer count: 1
tagged with: loops
type: Question
has answer: http://stackoverflow.com/a/49840179
accepted answer: http://stackoverflow.com/a/49840179
has body: I am trying to create a 3d tensor with the dimension (101, 2, 1000). I had to translate the R code I found to python and there is just a problem that r starts to iterate at 1 and python at zero. Is there a way to solve this problem below? Thanks in advance! df1 = pd.DataFrame(np.random.rand(1000, 2), columns=['Col1', 'Col2']) a = np.array(df1) a_stdnorm = stats.norm.ppf(a) n_rows = a.shape[0] n_cols = a.shape[1] samples = 100 if samples % 2 == 0: samples = samples + 1 # force an odd number samples_increment = samples - 1 # to cater for 1 based indices tensor = np.zeros((samples, n_cols, n_rows)) sum_col = a[:,0] + a[:,1] sort = np.argsort(sum_col) block_half = samples // 2 start = 0 end = start + samples_increment for n in range(n_rows): if (n + 1) - block_half &gt; 0 and n + block_half &lt;= n_rows: start = n - block_half end = start + samples_increment dx = sort[start:end] data = a_stdnorm[dx,:] tensor[:,:,sort[n]] = data --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-50-1b371b208d20&gt; in &lt;module&gt;() 22 dx = sort[start:end] 23 all_data = a_stdnorm[dx,:] ---&gt; 24 tensor[:,:,sort[n]] = all_data ValueError: could not broadcast input array from shape (100,2) into shape (101,2)
tagged with: arrays
tagged with: python
tagged with: sorting
has title: ValueError: could not broadcast input array from shape (100,2) into shape (101,2)

http://stackoverflow.com/a/49821524
has comment: http://stackoverflow.com/comment/86660900
has comment: http://stackoverflow.com/comment/86660677
upvote count: 2
has comment: http://stackoverflow.com/comment/86661511
has comment: http://stackoverflow.com/comment/86661480
has comment: http://stackoverflow.com/comment/86659604
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86660176
has comment: http://stackoverflow.com/comment/86658762
has body: Your problem is that for tier in data["predicates"] iterates over the keys of the predicate dictionary, thus the subsequent if "any" in tier actually evaluates "any" in "tier1" which is of cause always false. What you want to test here is "any" in data["predicates"]["tier1"]. When working with dictionaries (i.e. mappings) you have to differentiate between a key and its corresponding value. Interestingly you have gotten it right for the next level down: # ... content = tier['any'] if 'Other' in content: other = "" for s2 in content['Other']: # ... Ways to iterate over a dictionary d = {"key1":"value1", "key2":"value2", "key3":"value3"} for key in d: print(key) # prints key1, key2, key3 for key in d.keys(): print(key) # prints key1, key2, key3 for value in d.values(): print(value) # prints value1, value2, value3 for item in d.items(): print(item) # prints (key1,value1), (key2,value2), (key3,value3) for key, value in d.items(): print(key) print(value) # prints key1, value1, key2, value2, key3, value3 see python documentation here and here As you are new to Python and do not know what is possible, allow me to present you a much more elegant solution with out all the repetitive string operations: import yaml yamldata1 = r""" - ! name: Martial Focus prerequisites: tier1: any: Attribute: - Attribute1:§ 1 - Attribute2:§ 1 Feat: - Feat1 Other: - Other Prerequisites cost: - 3 description: | [...] effect: | [...] """ yamldata2 = r""" - ! name: Martial Focus prerequisites: tier1: Attribute: - Attribute1:§ 1 - Attribute2:§ 1 Feat: - Feat1 Other: - Other Prerequisites cost: - 3 description: | [...] effect: | [...] """ def process(data): output = "" for tier_name, tier in data['prerequisites'].items(): output += f"* {tier_name}" if 'any' in tier: content = tier['any'] prerequisites = content.get('Other', []) + content.get('Attribute', []) + content.get('Feat', []) if prerequisites: output += "\n** " + " or ".join(prerequisites) else: content = tier prerequisites = [content.get('Ot…
score: 2
has comment: http://stackoverflow.com/comment/86660308
accepted answer of: http://stackoverflow.com/q/49821100
has comment: http://stackoverflow.com/comment/86658296
type: Answer
answers question: http://stackoverflow.com/q/49821100
has comment: http://stackoverflow.com/comment/86661409

discord.py
tags question: http://stackoverflow.com/q/49881606
tags question: http://stackoverflow.com/q/49842851
tags question: http://stackoverflow.com/q/49848063
tags question: http://stackoverflow.com/q/49866785
type: Tag
tags question: http://stackoverflow.com/q/49886183
tags question: http://stackoverflow.com/q/49835742
tags question: http://stackoverflow.com/q/49759662
tags question: http://stackoverflow.com/q/49788888
tags question: http://stackoverflow.com/q/49881935
tag name: discord.py
tags question: http://stackoverflow.com/q/49837578
tags question: http://stackoverflow.com/q/49900578

http://stackoverflow.com/a/69229417
upvote count: 12
answers question: http://stackoverflow.com/q/49875588
downvote count: 0
has comment: http://stackoverflow.com/comment/135256209
type: Answer
has comment: http://stackoverflow.com/comment/126558380
score: 12
has body: if you are in a HPC this worked for me I think: module load gcc/9.2.0

http://stackoverflow.com/q/49910606
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86837133
upvote count: 1
has comment: http://stackoverflow.com/comment/86837615
has body: I have a binary array having m characters, I want to divide it into the block of n characters from right side using python.
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86837076
has answer: http://stackoverflow.com/a/49910660
score: 1
has title: How to split a array in n character from right side python?

http://stackoverflow.com/comment/86717993
type: QuestionComment
has text: You use different kind of double quotes. Try using a character class [`[\"”]`.](https://regex101.com/r/8ui9GE/1/)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49851349

http://stackoverflow.com/comment/86741149
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49862977
has text: You test if 3 and 2 belong in two different samples in `b()`, is this really what you mean?
type: Comment

http://stackoverflow.com/a/49806506
downvote count: 0
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/86628182
has body: with pd.DataFrame.filter df.filter(regex='i(o|r)') aio bir index 1 2 3 2 3 4 If you have a list of things to match things = ['io', 'ir'] df.filter(regex='|'.join(things)) aio bir index 1 2 3 2 3 4 Alternatives df.filter(regex='io|ir') df.loc[:, df.columns.str.contains('io|ir')]
has comment: http://stackoverflow.com/comment/86677023
type: Answer
accepted answer of: http://stackoverflow.com/q/49806485
has comment: http://stackoverflow.com/comment/86628126
answers question: http://stackoverflow.com/q/49806485
has comment: http://stackoverflow.com/comment/86630349
type: AcceptedAnswer

http://stackoverflow.com/comment/95632595
type: Comment
type: QuestionComment
has text: Wouldn't a [custom cursor](https://www.pygame.org/docs/ref/cursors.html) do in a situation like this? I really hate pointing to external resources, especially those trying to do what SO is doing but less efficient.. But since I don't want to be a internet thief, here's a good example of what I'm trying to convey: https://www.reddit.com/r/pygame/comments/47e3av/create_a_cursor_from_an_image/d0c9a42
comment on: http://stackoverflow.com/q/49842142
score: 0

http://stackoverflow.com/comment/86833978
has text: You should also mention passing the value(s) from `input` into the function and fixing the loop boundaries.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49909017

http://stackoverflow.com/a/49863324
type: AcceptedAnswer
has body: There are a few problems with your program, most notably, you are calling a within b, which I don't think you want to do. Within b, you are regenerating a list of new random values and then checking the contents of this list. Also, you should not use pass in your else statement because you could imagine the possibility where y is never defined, and therefore you will fail to return something. I would suggest the following: from random import choice, sample def a(): a = sample(range(0,5),2) a.append(1) return a def b(a): if 3 in a: return 1 elif 2 in a: return 2 else: return a_output = a() print a_output print b(a_output) However, this is an odd way to check the contents of a list. Without knowing the purpose of your program, it is difficult to make a recommendation for an alternative way to write a more pythonic function.
accepted answer of: http://stackoverflow.com/q/49862977
answers question: http://stackoverflow.com/q/49862977
type: Answer
score: 0

http://stackoverflow.com/q/49865394
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86746296
has comment: http://stackoverflow.com/comment/86746328
score: -2
tagged with: refactoring
has title: How to get rid of global variables in my code?
downvote count: 3
has comment: http://stackoverflow.com/comment/86746359
tagged with: python
has body: I was sitting all week on this and I don't know how to get rid of these global points. Here I define points. def init(): global points, hidden_password, hidden_password2, country, used, start_time points = 0 hidden_password = [] hidden_password2 = [] country = "" used = [] start_time = datetime.now() welcome() choice() Then it goes to choice() from choice to play_game() than to guessing_capital() and here I use points for the first time, and the program is working until var points reach 5. def guessing_capital(password, used, user_name): global points while points &lt; 5: checking(password, user_name) time.sleep(1) print("\n Letters You failed guessing: ", ", ".join(used), end=".\n") time.sleep(2) print("\n *** You lost! Sorry, but the GAME is OVER! ***\n") time.sleep(3) init() Then it goes to checking() and from checking it goes to the letter() and then to checking_password() where if the user didn't guess right letter it adds 1 to points and returns it. def checking_password(number): global points, hidden_password2, hidden_password if hidden_password2 == hidden_password: points += number time.sleep(1) print("\n Boo! You have +", number, "penalty points!") time.sleep(1) hidden_password2 = hidden_password if points &lt; 4: manage_graphics(points) elif points == 4: manage_graphics(points) print(" Hint: It's a capital of " + country + ".") elif points &gt;= 5: manage_graphics(5) return points Here is a full code if someone wants: https://codeshare.io/aYBAzb
tagged with: global-variables
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86746722
has comment: http://stackoverflow.com/comment/86746373
accepted answer: http://stackoverflow.com/a/49866137
has comment: http://stackoverflow.com/comment/86746471
has comment: http://stackoverflow.com/comment/86746345
answer count: 1
has answer: http://stackoverflow.com/a/49866137

http://stackoverflow.com/comment/86597292
type: AnswerComment
comment on: http://stackoverflow.com/a/49790662
type: Comment
has text: Can you post complete trace? Doesn't look like `Pool` should make something like that happen
score: 0

http://stackoverflow.com/a/76304091
upvote count: 1
has body: @jeffffc's solution is good if you need to edit message inside handler. But if you need to edit message in another handler, you should store message_id somewhere. It's because in other handler you'll don't have access to previous bot message, only to user message/command it receives. For example, if you try to do something like this: def echo(bot, update): update.message.reply_text("Sorry, you're on your own, kiddo.") def echo2(bot, update): bot.edit_message_text(chat_id=update.message.chat_id, message_id=.message_id, text="Seriously, you're on your own, kiddo.") You will receive an error "Message can't be edited". It's because you try to edit user message, not bot message. With latest 13.x version of python-telegram-bot you can use CallbackContext to store data between handlers. Instead of handlers above you can make it this: def echo(update, context): msg = update.message.reply_text("Sorry, you're on your own, kiddo.") context.user_data['bot_last_message_id'] = msg.message_id # remember to edit later def echo2(update, context): context.bot.edit_message_text( text="Seriously, you're on your own, kiddo.", chat_id=update.message.chat_id, message_id=context.user_data['bot_last_message_id'], # get it from context )
answers question: http://stackoverflow.com/q/49836428
type: Answer
score: 1
downvote count: 0

http://stackoverflow.com/a/49790814
score: 0
type: Answer
has body: If you get the string with requests, you may try to use the following method import json import requests data = requests.get(r'https://example.com').json()
answers question: http://stackoverflow.com/q/49771961

http://stackoverflow.com/q/49807052
downvote count: 0
has answer: http://stackoverflow.com/a/50123706
favorite count: 0
type: Question
tagged with: kivy-language
has body: Is there a way to zoom into an image on a desktop kivy app (e.g. zoom with a mouse scroll-wheel)? It appears to be discussed here: https://github.com/kivy/kivy/issues/3563 but I do not see if there was a work around given. I began with a static image in my kivy app. I want to add the ability to zoom / pan into the image. I do not want the actual size of the image frame to change, just add zoom/pan functionality, like you might expect from interacting with google maps for example. Possible Programming Directions From what I've read, I should be using Scatter(?), and I see that I can manually set the Scatter scale to size up/down the image. My initial thoughts are that I will have to add a separate widget with a scrollview to contain the scatter layout and that will keep the image frame a consistent size. Then I will need to add an event that dynamically changes the scale value. The problems I cannot find the appropriate event to use to change the scale value. the on_motion event seemed promising. My app can update values with a slider, but when I try a similar approach using on_motion, I get AttributeError: motion errors I am struggling to create the widget. Most documentation seems to use .add_widget(...) in the python file. Is it possible to do this from the kv file? I imagine this process is similar to screens and the screen manager, but I am struggling to find an approach that works. Is there a more straight forward way to do this? Is there a way I can use on_motion type event in my kv file to adjust this value using the mouse scroll-wheel? I give a watered down example of the structure of my kivy app - along with what I tried to do to add Scatter. I think I will need to put it into it's own widget to keep the image the same size? Toy Example import kivy from kivy.lang import Builder from kivy.core.window import Window kivy.require('1.1.0') from kivy.app import App presentation = Builder.load_file("scatter.kv") class TestApp(App): def build(self): Window.clearcol…
has comment: http://stackoverflow.com/comment/86630905
linked to: http://stackoverflow.com/q/43925919
accepted answer: http://stackoverflow.com/a/50123706
score: 13
tagged with: python
tagged with: kivy
has title: Kivy: scroll to zoom
upvote count: 13
possible better answer: http://stackoverflow.com/a/68308310
linked to: http://stackoverflow.com/q/49896086
has comment: http://stackoverflow.com/comment/86839139
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/68308310

http://stackoverflow.com/comment/86842920
score: 2
type: AnswerComment
has text: @tdelaney I have sympathy. Some people do have legit reasons for still using py2. Unicode support ain't one of them, though
type: Comment
comment on: http://stackoverflow.com/a/49913664

http://stackoverflow.com/comment/86674450
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49829627
has text: In the first iteration of the `for` loop, what do you think the values of `a[0]`, `b[0]` and `c[0]` are?
type: Comment

http://stackoverflow.com/comment/86709253
comment on: http://stackoverflow.com/q/49847143
type: Comment
type: QuestionComment
has text: @smci The `np.array` function returns an ndarray, so your comment reads rather confusingly.
score: 0

http://stackoverflow.com/comment/86699132
comment on: http://stackoverflow.com/a/49842199
score: 0
type: AnswerComment
has text: `concat` not, because it should be slowier.
type: Comment

http://stackoverflow.com/q/49829336
has comment: http://stackoverflow.com/comment/86724461
type: Question
has body: Huffman Code Tree Exercise, Write a program with menu options that: Asks the user for the name of a text file and then read the file, compute the relative frequencies of the 128 ascii characters and write this to a text file, one floating point frequency per line. reads a text file containing 128 lines each with a floating point number that represents the relative frequency of the corresponding ascii symbol in a given text type. Each Line correspond to the ASCII code of that line number, so line 32 is equal to ASCII code 32. Build a Huffman Code tree using the Assigned Frequencies from the file, ignore the ascii codes less than 32, ie only use lines 32-127. Print the tree using the following algorithm: def printTree("Tree", indent = ""): #inorder Traversal if theres a right subtree: printTree("node.right",indent+" ") print(indent, data)#data is equal to a character and if no char, then is equal to a " * " if theres a left subtree: printTree("node.left",indent+" ") Create and Print a Huffman Code table from the data. ( Similar to Below) That is what I'm attempting to do, however I've been able to build a tree (At least I think I have been able to, but I'm having trouble traversing the left or right children of the tree and building the corresponding byte code for the code table. I've made it this far but now I'm at a lost and I need some outside input to help trigger me in the right direction, and to ask questions or someone to report what I've done wrong, and help show me how I'm wrong. def pushDown(H,i,n): #Allows larger values to be at top of tree while i &lt;= n//2: lc = i*2 rc = 2*i+1 if H[lc] &gt; H[i] and (lc == n or H[lc] &gt;= H[rc]): H[i],H[lc] = H[lc],H[i] i = lc elif rc &lt;= n and H[i] &lt; H[rc]: H[i],H[rc] = H[rc],H[i] i = rc else: break def Heapify(H): #Creates a tree n = len(H)-1 for i in range(n//2,0,-1): pushDown(H,i,n) return H def Hsort(H): #Sort into a heap Heapify(H) n = len(H)-1 while n &gt; 1: H[n], H[1] = H[1], H[n] n = n-1 pushDown(H,1,n) r…
type: UnansweredQuestion
tagged with: python
tagged with: heapsort
has comment: http://stackoverflow.com/comment/86674059
has title: Creating Huffman Tree & Table Using a Heapsort
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/86689306
tagged with: huffman-code

http://stackoverflow.com/comment/139957239
score: 0
has text: here the list of [_wm attributes_](https://wiki.tcl-lang.org/page/wm+attributes) for different OSs
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/79166810

http://stackoverflow.com/q/49886528
downvote count: 0
upvote count: 1
tagged with: python
tagged with: pyqtgraph
has title: Does PyQtGraph have an option for placing symbols on only some fraction of points, similar to Matplotlib's markevery keyword?
possible better answer: http://stackoverflow.com/a/76710647
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/76710647
score: 1
accepted answer: http://stackoverflow.com/a/49951105
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49951105
has body: The following code snippet and plot shows how Matplotlib's markevery keyword can be convenient for placing markers on line without cluttering the plot by marking every point in a large dataset. Is there a similar feature in PyQtGraph, or do I just have to call plot twice to put symbols on a subset of the data? from matplotlib import pyplot as plt import pyqtgraph as pg import numpy as np x = np.linspace(0, 10, 151) y = x**2 pg.plot(x, y, symbol='o') plt.plot(x, y, marker='o') plt.plot(x, y+10, marker='o', markevery=10) plt.show()

http://stackoverflow.com/q/49913043
tagged with: supervised-learning
has title: Python supervised ML text classification into different categories with probability
tagged with: python
tagged with: twitter
has body: I am working with a large dataset of tweets from which I have trained a small subset into four manually classified categories. The manual classifications have about twenty tweets each, while the dataset has tens of thousands of tweets. Here is the code I used to train the model. from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import TfidfTransformer tweets = [] labels_list = [] tfidf = TfidfVectorizer(sublinear_tf=True, min_df=5, norm='l2', encoding='latin-1', ngram_range=(1, 2), stop_words='english') features = tfidf.fit_transform(tweets).toarray() labels = labels_list X_train, X_test, y_train, y_test = train_test_split(tweets, labels, random_state = 0) count_vect = CountVectorizer() X_train_counts = count_vect.fit_transform(X_train) tfidf_transformer = TfidfTransformer() X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) clf = MultinomialNB().fit(X_train_tfidf, y_train) Whenever I type print(clf.predict(count_vect.transform(["Some random content"]))) the machine accurately outputs the label that the tweet belongs to if I fill in the content with something that matches the training data. However, if I type in total nonsense, it will also output some random category that I know it doesn't belong to. My goal is to find 100 tweets that are most likely to belong to that category, however, the four categories mentioned above are not representative of the entire dataset, therefore, I need to know if there some sort of probability threshold I could use to eliminate that tweet and not add it to the 100 if it is too low on the threshold? I tried looking into multinomial logistic regression but I could not find any sort of probability output, so maybe if I am just doing something wrong or if there is another way I would like to know!
tagged with: text
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/49914239
type: Question
has answer: http://stackoverflow.com/a/49914239

http://stackoverflow.com/comment/86589401
type: Comment
comment on: http://stackoverflow.com/a/49787051
type: AnswerComment
has text: "As you are in Python3, is preferable to use mechanicalsoup" How do you figure that? bs4 is widely used and I've never even heard of mechanicalsoup.
score: 1

http://stackoverflow.com/comment/121147834
score: 0
type: Comment
type: QuestionComment
has text: what is the definition of `b` in beginning of your cvxpy example? i.e. `b = ?`
comment on: http://stackoverflow.com/q/49787068

http://stackoverflow.com/comment/86693126
comment on: http://stackoverflow.com/q/49838357
type: Comment
type: QuestionComment
has text: Why 3 downvotes?
score: 0

http://stackoverflow.com/comment/86812486
comment on: http://stackoverflow.com/a/49898511
type: Comment
has text: That actually worked, but there are more spans that contain '100%'. This only selects the first one. Sorry, I should've mentioned it.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86603076
type: AnswerComment
has text: No problem, we all started somewhere.
type: Comment
comment on: http://stackoverflow.com/a/49794319
score: 0

http://stackoverflow.com/q/49882680
answer count: 1
downvote count: 0
favorite count: 0
tagged with: console
type: AnsweredQuestion
tagged with: pyinstaller
tagged with: python
has title: Pyinstaller on Linux - How to show a console
accepted answer: http://stackoverflow.com/a/49883003
has comment: http://stackoverflow.com/comment/86782531
type: Question
has answer: http://stackoverflow.com/a/49883003
has body: I'm trying to generate a Python executable file with Pyinstaller on Linux. For this purpose I'm trying this implementation with a simple 'Hello World' file. The issue I'm having is that when the executable file is generated and I execute it (double-click), nothing happens. There is no console popping out and I can see no execution. I have read in the documentation that in MacOS and Windows there are explicit options in order to make this console appear or not, but not in Linux. Any idea?
score: 2
upvote count: 2
linked to: http://stackoverflow.com/q/1418553

http://stackoverflow.com/comment/86719126
type: Comment
comment on: http://stackoverflow.com/q/49852271
type: QuestionComment
has text: @Vinny Which is the best practice ?
score: 0

http://stackoverflow.com/q/49771963
has comment: http://stackoverflow.com/comment/86558875
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49772099
type: Question
linked to: http://stackoverflow.com/q/34443946
has comment: http://stackoverflow.com/comment/86558864
has title: How to count instances of consecutive letters in a string in Python 3?
upvote count: 1
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/86559432
has answer: http://stackoverflow.com/a/49772361
has comment: http://stackoverflow.com/comment/86559267
has body: I want to count the number of instances where consecutive letters are identical in a given string. For example, my string input is: EOOOEOEE I would only like to find the number of occasions where there is more than one consecutive 'O'. The Output should be: 1 Since, there is only one set of O's that come consecutively.
has comment: http://stackoverflow.com/comment/86559025
has comment: http://stackoverflow.com/comment/86558928
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49772121
has answer: http://stackoverflow.com/a/49772099
downvote count: 3
has answer: http://stackoverflow.com/a/49772121
has comment: http://stackoverflow.com/comment/86558870
has comment: http://stackoverflow.com/comment/86559706
tagged with: string
has comment: http://stackoverflow.com/comment/86559481
has answer: http://stackoverflow.com/a/49772266
answer count: 4
favorite count: 0

http://stackoverflow.com/comment/118134600
type: Comment
type: AnswerComment
has text: can you please explain what is f-string doing here..
comment on: http://stackoverflow.com/a/49909726
score: 0

http://stackoverflow.com/q/49782232
has comment: http://stackoverflow.com/comment/86605381
type: UnansweredQuestion
tagged with: python
tagged with: image
has answer: http://stackoverflow.com/a/49800655
tagged with: opencv
score: 0
has body: I'm trying to get the black region from an image using TensorFlow. To this point I was using OpenCV but it fails to get the hole region given that the gray scale is very complicated. The image I'm using is a photo of a electric meter, the whole meter is white(normally) except for the part with the numbers that is black. I would want to isolate this part in order to get the numbers later on. To de the date, I have been using the function findContours from OpenCV, with a defined threshold . I have seen that TensorFlow is very potent so I think this could no be a problem, but I can't find any documentation. Any hints? Thanks!
tagged with: colors
has title: Get black region from image using Tensorflow and Python
answer count: 1
has comment: http://stackoverflow.com/comment/86580860
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/86819864
type: AnswerComment
comment on: http://stackoverflow.com/a/49805500
score: 0
has text: Thank you Adrien.
type: Comment

http://stackoverflow.com/q/49858395
tagged with: command-line
type: Question
tagged with: c#
has comment: http://stackoverflow.com/comment/86741298
has answer: http://stackoverflow.com/a/49946820
has comment: http://stackoverflow.com/comment/86740844
has comment: http://stackoverflow.com/comment/86735925
has body: I've try to taken python version, so i've start a process with cmd and a command "python --version". I've try this for first: using (System.Diagnostics.Process p = new System.Diagnostics.Process()) { p.StartInfo.UseShellExecute = true; p.StartInfo.RedirectStandardOutput = false; p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = "/k C:/Python36/python --version"; p.StartInfo.CreateNoWindow = false; var retorno = p.Start(); } and opened a cmd window and returned this: cmd return instead of this, i need this result returned to my WPF application, so i try this: public static string GetPythonVersion() { string command = "python --version"; string output = null; using (System.Diagnostics.Process p = new System.Diagnostics.Process()) { p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = String.Format(@"/c {0}\{1} ", "C:/Python36/", command); p.StartInfo.CreateNoWindow = true; if (p.Start()) output = p.StandardOutput.ReadToEnd(); } return output; } return empty string to me. however to an example if i using the same code to return "pip list" to my wpf application working well, but in this case to taken the version the string return empty....
upvote count: 1
tagged with: python
tagged with: wpf
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49946820
score: 1
has comment: http://stackoverflow.com/comment/86733806
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86741183
tagged with: cmd
has comment: http://stackoverflow.com/comment/86758639
has comment: http://stackoverflow.com/comment/86740722
has title: WPF C# - get python version by cmd
has comment: http://stackoverflow.com/comment/86731507
favorite count: 0
has comment: http://stackoverflow.com/comment/86770339

http://stackoverflow.com/q/49900375
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86817598
has comment: http://stackoverflow.com/comment/86826834
downvote count: 1
has comment: http://stackoverflow.com/comment/86816490
has comment: http://stackoverflow.com/comment/86818885
has comment: http://stackoverflow.com/comment/86819823
favorite count: 0
has body: I am trying really hard to find contours in this image: here is my code: import numpy as np import cv2 im = cv2.imread('test.jpg') ##imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) cv2.namedWindow('gray',cv2.WINDOW_NORMAL) cv2.imshow('gray',im) cv2.waitKey() ret, thresh = cv2.threshold(imgray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) _, contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) print ("number of countours detected before filtering %d -> "%len(contours)) new = np.zeros(im.shape) new = cv2.drawContours(im,contours,-1,(0,0,255)) cv2.namedWindow('Display',cv2.WINDOW_NORMAL) cv2.imshow('Display',new) cv2.waitKey() Problems: 1. the produced image is always completely black and it never shows anything, just pure black image. by my description you can realize i am new to image processing. i am trying to show the body contour in red color but nothing appears. I am using open cv 3.4.0 and python 3.6 any suggestions / solutions are welcome, thank you.
type: Question
upvote count: 0
tagged with: contour
has answer: http://stackoverflow.com/a/49905500
accepted answer: http://stackoverflow.com/a/49905500
has comment: http://stackoverflow.com/comment/86816810
has title: drawContour doesn't do what I want
answer count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86816618

http://stackoverflow.com/a/49841659
upvote count: 2
downvote count: 0
score: 2
has body: a is a string, and strings are immutable in Python. Example from documentation: &gt;&gt;&gt; s = "Hello, World" &gt;&gt;&gt; c_s = c_wchar_p(s) &gt;&gt;&gt; print(c_s) c_wchar_p(139966785747344) &gt;&gt;&gt; print(c_s.value) Hello World &gt;&gt;&gt; c_s.value = "Hi, there" &gt;&gt;&gt; print(c_s) # the memory location has changed c_wchar_p(139966783348904) &gt;&gt;&gt; print(c_s.value) Hi, there &gt;&gt;&gt; print(s) # first object is unchanged Hello, World &gt;&gt;&gt;
type: Answer
answers question: http://stackoverflow.com/q/49841577

http://stackoverflow.com/a/49844338
score: 0
answers question: http://stackoverflow.com/q/49844277
type: Answer
has body: One way to resolve this issue is to convert to seconds and just compare integers: x, y = pd.to_timedelta('14:00:00').seconds, pd.to_timedelta('14:50:00').seconds df_temp = data3[data1.dt.seconds.between(x, y)].mean()

http://stackoverflow.com/q/49760858
type: Question
has body: I need to get data from this API https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434 (sample node) This is my code (python): import requests f = requests.get('https://api.storj.io/contacts/f52624d8ef76df81c40853c22f93735581071434') print f.text I want to save only protocol, responseTime and reputation in three subsequent lines of the txt file. It's supposed to look something like this:: protocol: 1.2.0 responseTime: 8157.912472694088 reputation: 1377 Unfortunately, I'm stuck at this point and I can not process this data in any way
has answer: http://stackoverflow.com/a/49761052
possible better answer: http://stackoverflow.com/a/49761052
has title: Get data from API and save it to txt with Python
tagged with: python
tagged with: get
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49761083
answer count: 3
tagged with: api
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49761076
accepted answer: http://stackoverflow.com/a/49761076
favorite count: 0

vim
tags question: http://stackoverflow.com/q/49786117
tags question: http://stackoverflow.com/q/49827046
tag name: vim
tags question: http://stackoverflow.com/q/49758489
type: Tag

http://stackoverflow.com/comment/132695487
comment on: http://stackoverflow.com/a/49836698
type: AnswerComment
score: 1
type: Comment
has text: Useful! My issue: I had a decimal in percentage form (call it n), and formatted it as `n.2`. Changing this to `n.2f` rounded it to 2 decimal places, while removing the scientific notation. Thank you!

http://stackoverflow.com/q/49776930
upvote count: 1
has answer: http://stackoverflow.com/a/49900458
has body: For my pi touchscreen project I am working with an -you guessed it- pi and an egalax touchdriver. The thing receives input and the touchscreen actually works, after some minor tweaking like inverting y_axis and stuff. However, at this moment I'm stuck trying to touch a certain button on the edge of the screen which I can't reach. I actually use a pen with the cursor enabled to make sure I know where the screen registers my input. So after searching a bit in the kivy documents I came across this postproc.calibration module which should do the trick. But it doesn't. I tried putting the following 2 code snippets in the .kivy/config.ini file: [input] egalax = hidinput,/dev/input/event0,rotation=90,invert_y=1 [postproc:calibration] egalax = xratio=1.2,yratio=1.2 The [input] bit works, no problems there. the [postproc:calibration] bit is what doesn't work. I've tried putting the line above the [postproc] module, beneath it, even beneath the [modules] module. Also I've tried putting the egalax = xratio=1.2,yratio=1.2 line IN the [postproc] module. Didn't seem to work. I've also tried to increase the floats to 2.0, but no changes. So how would I 'expand' my area of touch input?
favorite count: 0
type: Question
tagged with: python-3.x
has title: Cant calibrate touchscreen on kivy
tagged with: calibration
tagged with: python
possible better answer: http://stackoverflow.com/a/56591421
tagged with: kivy
has answer: http://stackoverflow.com/a/56591421
tagged with: touch
type: AnsweredQuestion
answer count: 2
score: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49900458

pyinstaller
tags question: http://stackoverflow.com/q/49803308
tags question: http://stackoverflow.com/q/49840828
tags question: http://stackoverflow.com/q/49894820
tags question: http://stackoverflow.com/q/49878329
tags question: http://stackoverflow.com/q/49849044
tags question: http://stackoverflow.com/q/49882680
type: Tag
tags question: http://stackoverflow.com/q/49883255
tags question: http://stackoverflow.com/q/49806594
tags question: http://stackoverflow.com/q/49908236
tags question: http://stackoverflow.com/q/49893124
tags question: http://stackoverflow.com/q/49916290
tags question: http://stackoverflow.com/q/49813936
tags question: http://stackoverflow.com/q/49913317
tags question: http://stackoverflow.com/q/49806573
tags question: http://stackoverflow.com/q/49850013
tag name: pyinstaller
tags question: http://stackoverflow.com/q/49861161
tags question: http://stackoverflow.com/q/49791273
tags question: http://stackoverflow.com/q/49913805
tags question: http://stackoverflow.com/q/49763583
tags question: http://stackoverflow.com/q/49869187

http://stackoverflow.com/comment/86754935
score: 0
has text: Well, you can do static type checking, but then it's not Python anymore.
comment on: http://stackoverflow.com/q/49869848
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49872110
has title: Vagrant up fails when installing Theano dependencies, can't fetch index URL
type: UnansweredQuestion
has body: Here is the error which has occured: change from absent to present failed: Execution of '/usr/bin/pip install -q git+git://github.com/Theano/Theano.git' returned 1: Cannot fetch index base URL http://pypi.python.org/simple/ ==&gt; default: Could not find any downloads that satisfy the requirement numpy&gt;=1.9.1 (from Theano==1.0.1-81.gf2a2df1) ==&gt; default: No distributions at all found for numpy&gt;=1.9.1 (from Theano==1.0.1-81.gf2a2df1)
tagged with: pip
tagged with: python
tagged with: conda
has comment: http://stackoverflow.com/comment/86770509
score: 0
tagged with: vagrant
has comment: http://stackoverflow.com/comment/86760240
has comment: http://stackoverflow.com/comment/86770308
has comment: http://stackoverflow.com/comment/86760526
has comment: http://stackoverflow.com/comment/86770140
type: Question
has comment: http://stackoverflow.com/comment/86760143
answer count: 0
has comment: http://stackoverflow.com/comment/86760321
tagged with: theano

http://stackoverflow.com/comment/86535256
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49760010
type: AnswerComment
has text: then simply you can add methods for update and for retrieve also

http://stackoverflow.com/comment/86925044
has text: @Blaszard Checkout my answer update and let me know the status
comment on: http://stackoverflow.com/a/49904176
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49761425
has answer: http://stackoverflow.com/a/49771596
tagged with: pandas
score: 1
tagged with: python
has title: Discrepancy between Seaborn plotted mean and calculated mean. (Python/Pandas)
favorite count: 0
type: Question
has body: Hello there wonderful people of StackOverflow! I have been getting to grips with Python and was starting to feel pretty confident that I knew what I was doing until this doozy came up: I am plotting and comparing two subselections of a dataframe where "Type" = "area" and "". Seaborn plots a boxplot of these and marks the mean, but when I calculate the mean using .mean() it gives a different answer. Here's the code: plotdata = df[df['Type'].isin(['A','B'])] g = sns.violinplot(x="Type", y="value", data=plotdata, inner="quartile") plt.ylim(ymin=-4, ymax=4) # This is to zoom on the plot to make the 0 line clearer This is the resulting plot, note how the means are ~-0.1 and ~1.5 But when I calculate them with: print(df_long[df_long['charttype'].isin(['area'])]['error'].mean()) print(df_long[df_long['charttype'].isin(['angle'])]['error'].mean()) It returns: 0.014542483333332705 -2.024809368191722 So my question is, why don't these numbers match?
has comment: http://stackoverflow.com/comment/86558060
type: UnansweredQuestion
tagged with: seaborn
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/112264395
type: Comment
type: AnswerComment
has text: applying this solution can lead to unwanted results. Every-time an operation is applied on Df1, the values for id will be different.
score: 1
comment on: http://stackoverflow.com/a/50095755

http://stackoverflow.com/a/61243904
has comment: http://stackoverflow.com/comment/138162928
type: Answer
downvote count: 1
has body: I solved, as explained by the message, by adding: import os os.environ['KMP_DUPLICATE_LIB_OK']='True'
score: 3
upvote count: 4
answers question: http://stackoverflow.com/q/49880700

http://stackoverflow.com/q/49835062
upvote count: 1
tagged with: python-requests
downvote count: 1
type: AnsweredQuestion
score: 0
has body: Trying to insert data into database but I keep getting this error: Traceback (most recent call last): File "business.py", line 25, in &lt;module&gt; data = fetch_data(con) File "business.py", line 18, in fetch_data result.append((entry['address'], entry['postalcode'], KeyError: 'address' Still new to python and coding. Appreciate your help, folks! What I have so far: import requests import sqlite3 URL = 'http://url/url/url/{}.json' def fetch_data(con): cur = con.cursor() cur.execute("SELECT identifier FROM restaurant WHERE res_creditnote = 'No' LIMIT 6") result = [] for row in cur: r = requests.get(URL.format(row[0])) entry = r.json() result.append((entry['address'], entry['postalcode'], entry['postal'], entry['statenumber'], entry['state'], entry['countrycode'], entry['country'])) return result con = sqlite3.connect("business.db") data = fetch_data(con) cur = con.cursor() cur.executemany('INSERT INTO hotel (address, postalcode, ' 'postal, statenumber, state, ' 'countrycode, country) VALUES (?, ?, ?, ?, ?, ?, ?);', data) con.commit() con.close() EDIT I try to fetch json data like this: "businessaddress":{"address":"Stockholm road 11","postalcode":"045432","postal":"Stockholm","statenumber":"45141","state":"Stockholm","countrycode":"SW","country":"Sweden"}
has comment: http://stackoverflow.com/comment/86685532
tagged with: python
has answer: http://stackoverflow.com/a/49835098
accepted answer: http://stackoverflow.com/a/49835251
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86685250
has answer: http://stackoverflow.com/a/49835251
answer count: 2
has title: Insert data into SQLite but getting KeyError - Python
possible better answer: http://stackoverflow.com/a/49835098

http://stackoverflow.com/comment/86701203
has text: Can you try `sns.barplot(y = axes['yaxis'], x = axes['xaxis'], orient='v');` changing `orient='v'`? May be explanation in https://stackoverflow.com/a/39937451/5916727 will be helpful.
score: 0
comment on: http://stackoverflow.com/q/49843309
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/95273559
type: QuestionComment
comment on: http://stackoverflow.com/q/49782579
has text: Curiously -- its also slower in numpy.
score: 0
type: Comment

http://stackoverflow.com/q/49786117
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/52274888
tagged with: vim
has comment: http://stackoverflow.com/comment/86617705
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/59902438
has comment: http://stackoverflow.com/comment/86593498
tagged with: macos
has comment: http://stackoverflow.com/comment/86592636
favorite count: 0
type: Question
has body: Now i update my .vimrc in Mac Osx but i have the next errors: Error detected while processing /Users/dmuino/.vimrc: line 59: E319: Sorry, the command is not available in this version: py &lt;&lt; EOF line 60: E492: Not an editor command: import os line 61: E492: Not an editor command: import sys line 62: E15: Invalid expression: 'VIRTUAL_ENV' in os.environ: line 117: E171: Missing :endif But i checked my .vimrc but i don't find any error in it, could you help me? My .vimrc is the next: set nocompatible " required filetype off " required set runtimepath+=~/.vim_runtime source ~/.vim_runtime/vimrcs/basic.vim source ~/.vim_runtime/vimrcs/filetypes.vim source ~/.vim_runtime/vimrcs/plugins_config.vim source ~/.vim_runtime/vimrcs/extended.vim set rtp+=~/.vim/bundle/Vundle.vim set splitbelow set splitright call vundle#begin() "split navigations nnoremap &lt;C-J&gt; &lt;C-W&gt;&lt;C-J&gt; nnoremap &lt;C-K&gt; &lt;C-W&gt;&lt;C-K&gt; nnoremap &lt;C-L&gt; &lt;C-W&gt;&lt;C-L&gt; nnoremap &lt;C-H&gt; &lt;C-W&gt;&lt;C-H&gt; " Enable folding set foldmethod=indent set foldlevel=99 " Enable folding with the spacebar nnoremap &lt;space&gt; za " alternatively, pass a path where Vundle should install plugins "call vundle#begin('~/some/path/here') " let Vundle manage Vundle, required Plugin 'gmarik/Vundle.vim' Plugin 'tmhedberg/SimpylFold' Helptags let g:SimplyFold_docstring_preview=1 " PEP8 indetantion au BufNewFile,BufRead *.py \ set tabstop=4 \ set softtabstop=4 \ set shiftwidth=4 \ set textwidth=79 \ set expandtab \ set autoindent \ set fileformat=unix " HTML, JS, CSS indentation au BufNewfile,BufRead *.js, *.html, *.css \ set tabstop=2 \ set softtabstop=2 \ set shiftwidth=2 "Fix problem indentation PEP8 Plugin 'vim-scripts/indentpython.vim' "Uneccesary whitespace au BufRead,BufNewfile *.py,*.pyw,*.c,*.h match BadWhitespace /\s\+$/ " UTF8 support set encoding=utf-8 "Autocomplete Bundle 'Valloric/YouCompleteMe' let g:ymc_autoclose_preview_window_after_completion=1 map &lt;leader&gt;g…
type: UnansweredQuestion
has title: Vim update plugins with errors
has comment: http://stackoverflow.com/comment/86592672
tagged with: python

http://stackoverflow.com/q/49795198
type: UnansweredQuestion
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/86604700
has comment: http://stackoverflow.com/comment/86609489
upvote count: 0
answer count: 1
has body: for this code i try to find if the word is repeat it will say word is "not unique" and if word does not repeat it will say word is "unique". I run the program but it showing error after i enter the sentence. def isUnique(): words = sentence.split() unique = {} for i in words: if word not in unique: count[i] = true else: unique[i] = false def main(): user_input = input("Enter word sperated by space: ") uniques = isUnique(user_input) print(uniques) main()
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49795589
has comment: http://stackoverflow.com/comment/86604706
downvote count: 2
has title: I am trying to write the python code that can check repeat word in sentance

http://stackoverflow.com/q/49822986
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86743188
type: Question
tagged with: videotexture
has body: I tried to change the texture of an object in the blender game engine. I thought it would be a good idea to use the Texture Replacement from the Video Texture (bge.texture). I tried to run the following script: def createTexture(cont): obj = cont.owner # get the reference pointer (ID) of the internal texture ID = texture.materialID(obj, 'Kraftwerk2.png') # create a texture object object_texture = texture.Texture(obj, ID) # create a new source with an external image url = logic.expandPath(new_file) new_source = texture.ImageFFmpeg(url) # the texture has to be stored in a permanent Python object logic.texture = object_texture # update/replace the texture logic.texture.source = new_source logic.texture.refresh(False) def removeTexture(cont): """Delete the Dynamic Texture, reversing back the final to its original state.""" try: del logic.texture except Exception as e: print(e) but it failed with the following error message: Python script error - object 'Plane', controller 'Python': Traceback (most recent call last): File "F:\Benutzer\Merlin\MW-Industries\Blender Dateien\Cinema\Render-Blend\MoonSpace.ble nd\Test.py", line 19, in createTexture AttributeError: 'VideoTexture.Texture' object has no attribute 'materialID' Is there a way to solve the problem?
has title: BGE Error: 'VideoTexture.Texture' object has no attribute 'materialID'
tagged with: blender
tagged with: attributeerror
has comment: http://stackoverflow.com/comment/86701635
tagged with: python
has comment: http://stackoverflow.com/comment/86662491
score: 0

http://stackoverflow.com/q/49907462
has body: I am trying to plot a twin figure. my code seems to work correctly in jupyter notebooks. the output figure of jupyter notebooks are as follows jupyter notebook inline figure However, when I try to save the figure to file, my output figure is always wrong, no matter how I adjust the figure size by figsize=(*,*) keywords, I can not get the right results. my output to file are something like the below figure save to file my code as follow: import numpy as np import matplotlib.pyplot as plt fig1, (ax1,ax2) = plt.subplots(2,1) box1 = [0.1, 0.1, 0.8, 0.4] box2 = [0.1, 0.5, 0.8, 0.8] ax1.set_position(box1) #lower figure ax2.set_position(box2) #upper figure x=np.arange(10) y1=0*x y2=x+1 ax1.plot(x,y1) ax2.plot(x,y2) ax1.set_xlim(0,9) ax2.set_xlim(0,9) ax2.set_xticklabels('') ax1.set_xlabel('ax1 x') ax1.set_ylabel('ax1 y') ax2.set_ylabel('ax2 x') ax2.set_title('titles') fig1.savefig('./1.png',dpi=200) fig1.show() Thanks very much for any help.
has comment: http://stackoverflow.com/comment/86843930
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: plot
has title: matplotlib: save multiple axis figure wrong
score: 0
has comment: http://stackoverflow.com/comment/86830759
answer count: 0
tagged with: matplotlib
tagged with: axis

http://stackoverflow.com/a/49909897
answers question: http://stackoverflow.com/q/49909538
upvote count: 2
downvote count: 0
type: Answer
has body: IIUC, you can do it like this. df.columns = pd.MultiIndex.from_tuples(cat_df.reset_index()'broader category','current category'.apply(tuple, axis=1).tolist()) print(df) Output: X Y Z A B C D 0 1 2 1 4 1 3 0 2 2 2 1 5 3 1 Sum level: df.sum(level=0, axis=1) Output: X Y Z 0 1 3 4 1 3 2 2 2 1 8 1
score: 2

http://stackoverflow.com/a/49808501
has body: Append a message delimiter character to the arduino output sequence; your choice but ‘\n’ would be good. Make a python generator function that reads input characters from bluetooth stream, assembling them into a buffer. Yield the entire buffer when the message delimiter character has been received, so the function calling the generator blocks until the entire message is available.
answers question: http://stackoverflow.com/q/49801361
score: 0
type: Answer

http://stackoverflow.com/comment/86844833
type: Comment
comment on: http://stackoverflow.com/q/49914613
has text: Argparse can not only parse flags but also positional arguments as you would like. There are many argument parsing libraries (argparse, docopt, click, invoke, optik,...) and all should be able to do what you want.
score: 0
type: QuestionComment

http://stackoverflow.com/q/49904571
tagged with: python
has answer: http://stackoverflow.com/a/49904989
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86825244
has title: Documentation for Python Internals?
downvote count: 0
has comment: http://stackoverflow.com/comment/86825466
has body: Perl provides internal documentation in perlguts. This is a great introduction to the perl source code, and helps you navigate and make sense of it. Does Python have an alternative that supplements the CPython source code? Something like pyguts or pythonguts?
has answer: http://stackoverflow.com/a/49904652
favorite count: 0
accepted answer: http://stackoverflow.com/a/49904652
type: Question
answer count: 2
tagged with: python-internals
tagged with: cpython
possible better answer: http://stackoverflow.com/a/49904989

http://stackoverflow.com/comment/86535707
type: Comment
type: AnswerComment
score: 1
has text: Pro tip: use a context manager (with `with`), or at least `.close()` the file handler.
comment on: http://stackoverflow.com/a/49760321

http://stackoverflow.com/a/49801685
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/49799356
has comment: http://stackoverflow.com/comment/86619352
downvote count: 0
answers question: http://stackoverflow.com/q/49799356
has comment: http://stackoverflow.com/comment/86619397
type: AcceptedAnswer
has body: You might be looking for something like df.procedure_id.groupby(df.patient_id).nunique().hist(); Explanation: df.procedure_id.groupby(df.patient_id).nunique() finds the number of unique procedures per patient. hist() plots a histogram. Example df = pd.DataFrame({'procedure_id': [3, 2, 3, 2, 4, 1, 2, 3], 'patient_id': [1, 2, 3, 2, 1, 2, 3, 2]}) df.procedure_id.groupby(df.patient_id).nunique().hist(); xlabel('num patients'); ylabel('num treatments');
has comment: http://stackoverflow.com/comment/86621547
upvote count: 6

http://stackoverflow.com/q/49838532
tagged with: pycharm
tagged with: installation
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/86692145
has comment: http://stackoverflow.com/comment/86692100
favorite count: 0
type: Question
has body: Python version: 3.6 Pycharm: community edition 2017.3.4 When i am trying to install an interpreter in pycharm but the "+" button is not available When i clicked on the "Install packaging tools" at the bottom it displays an error message So i follow some instructions and download pip and setuptools and try to get them installed,however error messages just keep popping up. no module named setuptools // no module named pip I'm new to python and have no idea what is going on... Please help... Error message when i tried to check pip version on CMD: C:\WINDOWS\system32>pip --version Traceback (most recent call last): File "runpy.py", line 193, in _run_module_as_main File "runpy.py", line 85, in _run_code File "C:\Python\Scripts\pip.exe__main__.py", line 5, in ModuleNotFoundError: No module named 'pip' I have uninstall pycharm and re-installed again, thing is getting worsen. When I clicked add base interpreter, there always an error message pop up: "Error: Standard Python 'venv' module not found" What does it mean??
has answer: http://stackoverflow.com/a/49838589
type: UnansweredQuestion
has title: How to install interpreter on pycharm?
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/49840592
answer count: 2

http://stackoverflow.com/comment/86664466
has text: the error in writer
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49824262

http://stackoverflow.com/q/49785149
downvote count: 1
has comment: http://stackoverflow.com/comment/86585772
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86587420
has comment: http://stackoverflow.com/comment/86616807
duplicate of: http://stackoverflow.com/q/49796314
has comment: http://stackoverflow.com/comment/86616908
has comment: http://stackoverflow.com/comment/86585840
type: UnansweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86588832
has comment: http://stackoverflow.com/comment/86587660
tagged with: python
has comment: http://stackoverflow.com/comment/86585910
has comment: http://stackoverflow.com/comment/86587949
has comment: http://stackoverflow.com/comment/86585890
has title: animated scatterplot by loop
has comment: http://stackoverflow.com/comment/86596595
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86585996
has body: I am trying to animate scatterplot by loop. I don't want to use matplotlib animation module because my time interval is variable and thats why i use time.sleep() in loop. My code is not working perfectly. It is showing only the first point only. However, while debugging, it showing as intended. Here is my code: fig, ax = plt.subplots() ax.set(xlim=(10, 90), ylim=(0, 60)) for i in range(1,6): ax.scatter(x[:i], y[:i]) plt.show() time.sleep(1)
has comment: http://stackoverflow.com/comment/86587236
linked to: http://stackoverflow.com/q/49796314
has comment: http://stackoverflow.com/comment/86585934
upvote count: 1
has comment: http://stackoverflow.com/comment/86585797
has comment: http://stackoverflow.com/comment/86615458

http://stackoverflow.com/a/49830180
answers question: http://stackoverflow.com/q/49828916
has body: If your goal is to regroup them in a template, have a look at https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#regroup Note that you'll have to sort your objects by category first, as regroup relies on that order to produce correct output. If your goal is to regroup them in the code (as opposed to templates), you can rely on itertools.groupby (see https://docs.python.org/3/library/itertools.html#itertools.groupby). Again, you'll need to join and sort your data first.
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/49759060
type: Answer
accepted answer of: http://stackoverflow.com/q/49758858
has body: This can be done using a simple one-liner using np.concatenate: data = np.concatenate([np.repeat(i, j) for i, j in zip(x, n)])
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49758858

http://stackoverflow.com/comment/86567830
has text: The current `insert` we see doesn't take anything, since it's not a valid function definition. If you've fixed it up somehow so it actually compiles, and that version doesn't take 3 arguments, you'll have to show us that version.
score: 0
comment on: http://stackoverflow.com/q/49775610
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49878046
has comment: http://stackoverflow.com/comment/87674833
accepted answer: http://stackoverflow.com/a/50851719
type: Question
has title: NiFi NiPyApi gives me errors
has comment: http://stackoverflow.com/comment/86778776
answer count: 1
has body: I managed to get at Kerberos ticket and perform some task with canvas object, but I still face some issues. I have wrapped the code into a class and have those 2 functions The first function getBulletinBoard retrieves all messages in the bulletin board from NiFi in it works fine: def getBulletinBoard(self): canvas_id = canvas.get_bulletin_board() return canvas_id The second function Stop Processor should stop a processor doesn't work, I have hardcorded my processor id into this for test reason and tried various thing to make it work. def stopProcessor(self): try: canvas.schedule_processor('d73136a7-6b8d-1914-a511-3c5acb2b5515',scheduled=False) except nifi.rest.ApiException as e: print(e.body) return None The output for StopProcessor function is Traceback (most recent call last): File "c:\Temp\nifi-rest\test1.py", line 176, in &lt;module&gt; n.stopProcessor() File "c:\Temp\nifi-rest\test1.py", line 162, in stopProcessor canvas.schedule_processor('d73136a7-6b8d-1914-a511- 3c5acb2b5515',scheduled=False) File "C:\python3.6_32\lib\site-packages\nipyapi\canvas.py", line 528, in schedule_processor assert isinstance(processor, nipyapi.nifi.ProcessorEntity) AssertionError I cannot figure out why this doesn't work.
has comment: http://stackoverflow.com/comment/86789475
has comment: http://stackoverflow.com/comment/86851914
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50851719
tagged with: python
tagged with: apache-nifi

http://stackoverflow.com/comment/86610158
has text: Re-seek to offset 0 immediately before the upload? Or open a new stream on the file?
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49797674

http://stackoverflow.com/q/49882337
type: Question
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49882390
tagged with: python
has answer: http://stackoverflow.com/a/49882416
has title: Class attributes functionally dependent on other class attributes
tagged with: class
has body: I'm trying to use a static class attribute to define another static class attribute, which I thought could be achieve by the following code: f = lambda s: s[::-1] class A: foo = "foo" bar = f(A.foo) However, this results in NameError: name 'A' is not defined. I found an explanation of why here, but this doesn't explain how one is supposed to work around this. So how could one define A.bar == "oof"?
score: 2
answer count: 3
linked to: http://stackoverflow.com/q/22294192
has answer: http://stackoverflow.com/a/49883179
favorite count: 0

http://stackoverflow.com/comment/123702530
score: 9
type: AnswerComment
has text: I think there is a difference in the order perhaps this is better? `x.detach().cpu().numpy()`
comment on: http://stackoverflow.com/a/64566135
type: Comment

http://stackoverflow.com/comment/86821148
type: Comment
has text: @DanMašek Difficult to pin point since OP hasn't mentioned the API version. @Mel Abgrall There could be an issue in this line as well `images[pos, :, :, :] = testimg`
score: 0
comment on: http://stackoverflow.com/q/49902322
type: QuestionComment

http://stackoverflow.com/comment/86844737
comment on: http://stackoverflow.com/q/49914613
has text: https://docs.python.org/3/library/sys.html#sys.argv
type: QuestionComment
score: 3
type: Comment

http://stackoverflow.com/a/49842073
upvote count: 1
has body: In my case python points to 2.7 while py works to 3.6. You can check this by typing py in Terminal, and if so then py -m pip install something
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/86700687
answers question: http://stackoverflow.com/q/49840543
downvote count: 2

http://stackoverflow.com/q/49815091
has answer: http://stackoverflow.com/a/49851323
accepted answer: http://stackoverflow.com/a/49815157
possible better answer: http://stackoverflow.com/a/49816482
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/49816482
tagged with: python
tagged with: string
score: 4
type: Question
tagged with: pandas
type: AnsweredQuestion
has body: I have following data frame I want to find the index for cell which are starts with certain string. Example : Price | Rate p/lot | Total Comm| 947.2 1.25 BAM 1.25 129.3 2.1 NAD 1.25 161.69 0.8 CAD 2.00 If I have search for ['NAD']:- Expected output:- (1,2)
tagged with: dataframe
has answer: http://stackoverflow.com/a/49815157
favorite count: 0
upvote count: 4
tagged with: python-3.x
has title: Pandas how to find position of cell startswith string

http://stackoverflow.com/comment/86839181
type: AnswerComment
comment on: http://stackoverflow.com/a/49911138
type: Comment
has text: Sorry I made a bad question title... I thought all moving rows operation were based on shift()...
score: 0

http://stackoverflow.com/q/49850435
answer count: 1
downvote count: 0
upvote count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/49852111
favorite count: 0
type: Question
has title: custom matrix in NMF in scikit-learn
tagged with: python
accepted answer: http://stackoverflow.com/a/49852111
tagged with: optimization
has body: I've to do NMF with sklearn, I've used the instructions here: http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.NMF.html I want to add my initialized matrix H, there is option to do init='custom' but I don't know how to give him the matrix H. I've tried: model = NMF(n_components=2, init='custom',H=myInitializationH random_state=0); but it doesn't work. In addition, is someone know how to fix my matrix and update only W? edit: Thanks for the answer When I choose the custom option, I get the error: ValueError: input contains nan infinity or a value too large for dtype('float64') However, the matrix don't contains any nan or infinity. Moreover, I did it for very small matrix to see if it is fine and its not: import numpy as np from sklearn.decomposition import NMF x=np.ones((2,3)); #model = NMF(n_components=1, init='custom', solver='mu',beta_loss=1,max_iter=500,random_state=0,alpha=0,verbose=0, shuffle=False); model = NMF(n_components=1, init='custom'); fixed_W = model.fit_transform(x,H=np.ones((1,3))); fixed_H = model.components_; print(np.matmul(fixed_W,fixed_H)); I got the same error unless I do 'random' instead of 'custom'. Is it happen also to you? why is it happen?
has comment: http://stackoverflow.com/comment/86715487
type: AnsweredQuestion
tagged with: nmf
score: 1
has comment: http://stackoverflow.com/comment/86715557

http://stackoverflow.com/comment/86665681
comment on: http://stackoverflow.com/q/49824504
type: Comment
type: QuestionComment
score: 0
has text: @Andersson Positive and there is no helpful explaination on there as to what None means. Funny this is when i step through it using terminal debug command it works because i take a screen shot there after.

http://stackoverflow.com/q/49795585
has answer: http://stackoverflow.com/a/49796809
tagged with: python
has comment: http://stackoverflow.com/comment/86606417
has comment: http://stackoverflow.com/comment/86605713
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/86609922
score: 0
has title: Store user entry from entry field, tkinter
has comment: http://stackoverflow.com/comment/86606597
answer count: 1
has body: So, I've seen other questions on a similar topic to this, I've struggled to make sense of them so I'm asking this one. I have this program, the majority of the code is below, It's a basic GUI. I'm having problems with the entry fields that take the users first name and surname, the block of code associated with this is here: tk.Label(self, text='First Name: ').pack(side=TOP) EntryFieldFN = Entry(self) EntryFieldFN.pack(pady=2, padx=2) tk.Label(self, text='Surname: ').pack() EntryFieldSN = Entry(self) EntryFieldSN.pack(pady=2, padx=2) FirstName = EntryFieldFN.get() Surname = EntryFieldSN.get() I've been unable to work out how to store the user input from these fields into variables that I can then use later. I wish to use the first name and surname of the user in the FinalWindow() function, which I want to act as a receipt of purchase for the order. def FinalWindow(): win = Toplevel() LabelRW = Label(win, text='Receipt of Purchase') ExitProg = Button(win, text='Exit', command=sys.exit) LabelRW.pack() ExitProg.pack() win.title('Virtual Receipt') class Till(tk.Frame): def __init__(self, master=None, **kw): tk.Frame.__init__(self, master=master, **kw) self.price_string = tk.StringVar() tk.Label(self, text='GUI Program - Till System').pack(side=TOP) tk.Label(self, text='First Name: ').pack(side=TOP) EntryFieldFN = Entry(self) EntryFieldFN.pack(pady=2, padx=2) tk.Label(self, text='Surname: ').pack() EntryFieldSN = Entry(self) EntryFieldSN.pack(pady=2, padx=2) FirstName = EntryFieldFN.get() Surname = EntryFieldSN.get() tk.Label(self, textvariable=self.price_string).pack(side=BOTTOM) tk.Label(self, text="Total Price: ").pack(side=BOTTOM) self.items = [] # For each stock item, create an IntVar, a checkbox and keep record of the price/name for idx, item in enumerate(stock_items): new_item = {} new_item['var'] = tk.IntVar() new_item['check'] = tk.Checkbutton(self, text=item['name'], variable=new_item['var'], command=self.recalculate) new_item['check'].pack() new_item['name'] =…
has comment: http://stackoverflow.com/comment/86606700
type: Question
has comment: http://stackoverflow.com/comment/86606070
accepted answer: http://stackoverflow.com/a/49796809

http://stackoverflow.com/comment/86572631
type: QuestionComment
score: 0
has text: The link you provided was for a list of lists. You just have a list. Getting the second element (index 1) is as simple as `l[1]`.
comment on: http://stackoverflow.com/q/49778665
type: Comment

http://stackoverflow.com/q/49833528
accepted answer: http://stackoverflow.com/a/49835215
tagged with: python
has comment: http://stackoverflow.com/comment/86682646
has comment: http://stackoverflow.com/comment/86682634
has answer: http://stackoverflow.com/a/49835215
possible better answer: http://stackoverflow.com/a/49834112
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86682777
tagged with: list
has comment: http://stackoverflow.com/comment/86682534
has body: I'm looking for the best way to find duplicate sequences in a list. A sequence is defined as at least two neighbouring values. Example: In the following list, the repeating sequence should be identified and deleted. a = [45874, 35195, # &lt;- 28965, 05867, 25847, # &lt;- 94937, 64894, 55535, 62899, 00391, 35195, # Duplicate Sequence Start 28965, 05867, 25847, # Duplicate Sequence End 08483, 55801, 33129, 42616] I can't wrap my head around any solution, so any help is much appreciated!
has comment: http://stackoverflow.com/comment/86682519
has answer: http://stackoverflow.com/a/49834112
has comment: http://stackoverflow.com/comment/86682490
has comment: http://stackoverflow.com/comment/86682621
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86682374
tagged with: subsequence
has comment: http://stackoverflow.com/comment/86682536
has title: Python: Identifying and deleting duplicate sequences in list
favorite count: 0
type: Question
tagged with: sequences
answer count: 2
has comment: http://stackoverflow.com/comment/86682754
downvote count: 0

http://stackoverflow.com/a/49856243
has comment: http://stackoverflow.com/comment/86726933
answers question: http://stackoverflow.com/q/49856172
upvote count: 3
has body: Use re.split: import re s = 'abc1235abc53abcXX' re.split('abc', s) # ['', '1235', '53', 'XX'] Note that you get an empty string, representing the match before the first 'abc'.
downvote count: 0
score: 3
type: Answer

http://stackoverflow.com/comment/86609448
type: AnswerComment
has text: @Victor - Thank you.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49796021

http://stackoverflow.com/comment/86681082
comment on: http://stackoverflow.com/q/49832898
score: 1
type: Comment
type: QuestionComment
has text: Can you add that content "data"that you have received?

hadoop-streaming
tags question: http://stackoverflow.com/q/49788047
tag name: hadoop-streaming
type: Tag

http://stackoverflow.com/a/54760333
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49839857
has body: I have read this on sungjin han' blog but it's golang maybe helpful, You could see this part, He has used ffmpeg convertor, but it's on golang language... His github. func speechToText(w *witai.Client, fileUrl string) (text string, err error) { var oggFilepath, mp3Filepath string // download .ogg, if oggFilepath, err = downloadFile(fileUrl); err == nil { // .ogg =&gt; .mp3, if mp3Filepath, err = oggToMp3(oggFilepath); err == nil { // .mp3 =&gt; text if result, err := w.QuerySpeechMp3(mp3Filepath, nil, "", "", 1); err == nil { log.Printf("&gt; analyzed speech result: %+v\n", result) if result.Text != nil { text = fmt.Sprintf("\"%s\"", *result.Text) /* // traverse for more info sessionId := "01234567890abcdef" if results, err := w.ConverseAll(sessionId, *result.Text, nil); err == nil { for i, r := range results { log.Printf("&gt; converse[%d] result: %v\n", i, r) } } else { log.Printf("failed to converse: %s\n", err) } */ } } // delete converted file if err = os.Remove(mp3Filepath); err != nil { log.Printf("*** failed to delete converted file: %s\n", mp3Filepath) } } else { log.Printf("*** failed to convert .ogg to .mp3: %s\n", err) } // delete downloaded file if err = os.Remove(oggFilepath); err != nil { log.Printf("*** failed to delete downloaded file: %s\n", oggFilepath) } } return text, err }

http://stackoverflow.com/a/49829843
score: 1
has body: In principle your version works too. Only the default draw mode of plot is to draw lines without markers for the sample points. As one point does not make a line, nothing can be drawn. Change the plot commands to plt.plot(t, theta,'.b') plt.plot(t, omega,'.r') to switch the markers on, then there will be something drawn. You will still have to remove or adapt the axis settings. This method is rather slow as there are rather many, and also many redundant, calls to the plotting library.
downvote count: 0
answers question: http://stackoverflow.com/q/49823699
upvote count: 1
type: Answer

http://stackoverflow.com/q/49875722
has answer: http://stackoverflow.com/a/49880173
accepted answer: http://stackoverflow.com/a/49880173
linked to: http://stackoverflow.com/q/44641669
linked to: http://stackoverflow.com/q/13784201
tagged with: pandas
has comment: http://stackoverflow.com/comment/86766892
tagged with: matplotlib
answer count: 1
downvote count: 0
has title: Seaborn FacetGrid - Place single colorbar after last subplot
favorite count: 0
type: Question
tagged with: facet-grid
tagged with: seaborn
has body: I'm trying to add a colorbar to a grid of 3 seaborn plots. I am able to add the colorbar to the 3 individual plots, or squeeze a colour bar next to the 3rd plot. I would like to have a single colorbar after the 3rd plot, without changing the size of the last plot. I got lots of good ideas from this answer, but couldn't solve my exact problem: SO Question/Answer Here is my current code: import seaborn as sns def masked_vs_unmasked_facets(output_dir, merged_df, target_col, thresholds): # defining the maximal values, to make the plot square z_min = merged_df'z_full', 'z_masked'.min(axis=0, skipna=True).min(skipna=True) z_max = merged_df'z_full', 'z_masked'.max(axis=0, skipna=True).max(skipna=True) z_range_value = max(abs(z_min), abs(z_max)) # Setting the column values to create the facet grid for i, val in enumerate(thresholds): merged_df.loc[merged_df.info_score_masked &gt; val, 'PlotSet'] = i # Start the actual plots g = sns.FacetGrid(merged_df, col='PlotSet', size=8) def facet_scatter(x, y, c, **kwargs): kwargs.pop("color") plt.scatter(x, y, c=c, **kwargs) # plt.colorbar() for multiple colourbars vmin, vmax = 0, 1 norm=plt.Normalize(vmin=vmin, vmax=vmax) g = (g.map(facet_scatter, 'z_full', 'z_masked', 'info_score_masked', norm=norm, cmap='viridis')) ax = g.axes[0] for ax in ax: ax.set_xlim([-z_range_value * 1.1, z_range_value * 1.1]) ax.set_ylim([-z_range_value * 1.1, z_range_value * 1.1]) ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c=".3") plt.colorbar() # Single squashed colorbar plt.show() masked_vs_unmasked_facets(output_dir, masking_results, 'info_score_masked', [0, 0.7, 0.9]) Single colorbar, but 3rd plot squashed Multiple colorbars, but crowded
has comment: http://stackoverflow.com/comment/86773596
tagged with: python
upvote count: 4
score: 4
type: AnsweredQuestion

http://stackoverflow.com/q/49895863
has comment: http://stackoverflow.com/comment/86807333
has title: Tkinter create notebook page with if loop
tagged with: python
has comment: http://stackoverflow.com/comment/86807600
type: Question
score: 0
tagged with: tkinter
has body: I got a program that read an HTML template and search for variables and create for each variable a text entry field. But I want this entry fields in Notebook pages but atm it just create one Notebook page from the last variable. How do I do this? class writer(): def __init__(self): self.root = Tk() self.root.filename = filedialog self.start_folder = filedialog.askopenfilename(initialdir="/", title="Open HTML Template", filetypes=(("HTML", "*.HTML"), ("all files", "*.*"))) self.solved = {} self.progress_var = [] self.page = [] self.variables = [] self.load_template(self.start_folder) self.start_gui() self.writer() def save(self): for var, eing in self.progress_var: self.solved[var] = eing.get('1.0', END) print('Var:', self.solved) def load_template(self, start_folder): with open(start_folder, mode="r") as htmlfile: for line in htmlfile.readlines(): if '{{' in line and '}}' in line: found_var = line[line.find('{{')+2:line.find('}}')] if found_var[:6].lower() == 'header': if self.page: self.variables.append(self.page) self.page = [] self.page.append(found_var) else: self.page.append(found_var) self.variables.append(self.page) def start_gui(self): notebook = ttk.Notebook(padding='10 10 10 10', width=600, height=200) notebook.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S)) gui = ttk.Frame(notebook) for page in self.variables: self.page = page for i, needed_var in enumerate(page): print('needed var:', needed_var) # ttk.Button(gui, text=needed_var, width=15, command=self.save).grid(row=2, column=1) # ttk.Button(gui, text=needed_var, width=15, command=self.save).grid(row=4, column=1) notebook.add(gui, padding=5, text=needed_var) field = LabelFrame(gui, text=needed_var[1], padx=100, pady=50) field.grid(row=i*2, column=1, sticky=NW) eing = scrolledtext.ScrolledText(gui, width=40) eing.insert(INSERT, needed_var) eing.grid(row=(i * 2)+1, column=1, sticky=NW) self.progress_var.append([needed_var, eing]) ttk.Button(gui, text="SAVE", width=15, command=self.save).grid(row=2,…
tagged with: tkentry
answer count: 1
accepted answer: http://stackoverflow.com/a/49916449
has answer: http://stackoverflow.com/a/49916449
type: AnsweredQuestion

http://stackoverflow.com/comment/86581747
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49783082
has text: Note that if you want to include all the numbers up to and including 34, you should use `range(1, 35)`. https://docs.python.org/2/library/functions.html#range

http://stackoverflow.com/comment/86703248
score: 0
has text: I didnt know how to give data. Thats why I have added the image. How to give the data? @cmaher
comment on: http://stackoverflow.com/q/49843461
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49891327
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49889593
has body: This can be achieved in a single line using list comprehensions. &gt;&gt;&gt;from collections import Counter &gt;&gt;&gt;name_list = ["Davy Jones", "Davy Crockett", "George Washington"] &gt;&gt;&gt;Counter([name.split()[0] for name in name_list]) #result --&gt; Counter({'Davy': 2, 'George': 1})

http://stackoverflow.com/comment/86685705
type: QuestionComment
score: 0
has text: is there any problem ?
comment on: http://stackoverflow.com/q/49835272
type: Comment

http://stackoverflow.com/comment/86858145
comment on: http://stackoverflow.com/q/49891013
type: Comment
type: QuestionComment
score: 0
has text: What version of Python are you using? And which version of pycrfsuite?

http://stackoverflow.com/q/49843334
linked to: http://stackoverflow.com/q/11792629
has answer: http://stackoverflow.com/a/49843363
answer count: 1
type: Question
tagged with: multiprocessing
duplicate of: http://stackoverflow.com/q/11792629
has body: I use multiprocessing to set up 2 process. Here is my code: import multiprocessing def aaa(): while True: print('aaa') def bbb(): while True: print('bbb') if __name__=='__main__': p1=multiprocessing.Process(target=aaa()) p2=multiprocessing.Process(target=bbb()) p1.start p2.start p1.join p2.join I expect it will print: 'aaa','bbb','aaa','bbb','aaa','bbb','aaa','bbb','aaa','bbb','aaa','bbb', Why does it only print aaa, but not bbb ? thank you!
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86701299
score: 0
has title: about multiprocessing in python3

http://stackoverflow.com/a/49905817
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49901840
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86832284
has body: Both snippets are equal and do the same job. The second looks a little more elegant from my perspective.

http://stackoverflow.com/q/49863071
has comment: http://stackoverflow.com/comment/86745930
has comment: http://stackoverflow.com/comment/86748125
tagged with: http://stackoverflow.com/tag/csv
tagged with: size
tagged with: dataframe
tagged with: python
answer count: 0
upvote count: 2
score: 2
type: UnansweredQuestion
downvote count: 0
has title: CSV file changes size when modified a little bit using panda data frames
favorite count: 0
type: Question
has body: I'm reading a CSV file and saving it as a panda data frame, changing it, and later saving it as another CSV file. The problem is the number of rows and columns and each element data size remains constant in this process, yet the size of the input and output CSV files differ significantly( input = 132 kB, output = 139 KB). I'm having a hard time understanding what's going on. I suspected encodings, and enforced them to be the same type both when reading and writing, but the issue remained. What's more, if I open the output file manually and change a single element(say change only a 1 to 2 ), the size of the file goes back to 132 KB, which I expect. For your reference here is the code I'm using: user_df = pd.read_csv("input.csv") answer = pd.DataFrame(columns=['question','worker','answer']) After copying some fields of user data frame to answer data frame: answer.to_csv("output.csv") Thanks a ton

http://stackoverflow.com/q/49904228
tagged with: pip
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/86824853
has comment: http://stackoverflow.com/comment/86825985
type: Question
score: 0
has body: All I want to do is install pyodbc. I am using python 3.4.4 and I can verify the installation is not correct since running import pyodbc causes the error ImportError: No module named 'pyodbc'. In my /Python/Scripts directory I have tried multiple times running pip install pyodbc which gives Requirement already satisfied (use --upgrade to upgrade): pyodbc in c:\python34\ lib\site-packages and after searching I believe that means it has already been installed. Additionally I tried downloading the .whl file and installing it as pip install pyodbc-4.0.17-cp34-cp34m-win_amd64.whl which gives pyodbc-4.0.17-cp34-cp34m-win_amd64.whl is not a supported wheel on this platform. What am I not doing that I need to do in order to get it installed properly?
has comment: http://stackoverflow.com/comment/86830327
tagged with: python
linked to: http://stackoverflow.com/q/1405913
has title: Properly install pyodbc
answer count: 0
has comment: http://stackoverflow.com/comment/86840739
type: UnansweredQuestion

http://stackoverflow.com/q/49837627
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/49837646
has comment: http://stackoverflow.com/comment/86690552
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49837646
favorite count: 0
has comment: http://stackoverflow.com/comment/86690586
type: Question
accepted answer: http://stackoverflow.com/a/49837644
has answer: http://stackoverflow.com/a/49837644
has body: I have the following two lists states = ('ab',['rose','cose']) flowers = {'rose':0,'cose:0','mose:0'} Now need the flowers dictionary to be changed to flowers = {'rose':1,'cose:1','mose:0'} after I loop th states I tried this but some syntax seems to be a problem! [flowers[i] = 1 for i in states[1] if i in flowers.keys()] Help is really appreciated! I am not able to understand, I kept the expression first and the conditional in the last! :/
tagged with: python
tagged with: list-comprehension
has title: Looping through dictionary and updating in python List Comprehension
type: AnsweredQuestion

http://stackoverflow.com/a/49881281
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49876794
answers question: http://stackoverflow.com/q/49876794
score: 1
type: Answer
has body: PolyDrawTool is a very recent feature, it is much newer then version 0.12. You will need to update your Bokeh version to be able to use it. The latest current release is 0.12.15.
type: AcceptedAnswer

http://stackoverflow.com/comment/86533775
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49759309
has text: Why have you tagged this both `python-3.x` and `python-2.7`? Do you need your code to work with both versions? Are you translating code from one version to the other?
score: 2

http://stackoverflow.com/q/49806961
tagged with: numpy
tagged with: python-3.x
tagged with: matplotlib
tagged with: python
score: -1
upvote count: 0
has title: Matplotlib 2.02 plotting within a for loop
type: UnansweredQuestion
answer count: 1
downvote count: 1
tagged with: scipy
has body: I am having trouble with two things on a plot I am generating within a for loop, my code loads some data in, fits it to a function using curve_fit and then plots measured data and the fit on the same plot for 5 different sets of measured y value (the measured data is represent by empty circle markers and fit by a solid line as the same color as the marker) Firstly I am struggling to reduce the linewidth of the fit (solid line) however much I reduce the float value of linewidth, I can increase the size just not decrease it by the value displayed in the output below. Secondly I would like the legend to display only circle markers not circles with lines through - I cannot seem to get this to work, any ideas? Here is my code and attached is the output plot and data file on google drive share link (for some reason it's cutting off long lines of text on this post): import scipy import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit #define vogel-fulcher-tamman (VFT) function def vft(x,sigma_0,temp_vf,D): return np.log(sigma_0)-((D*temp_vf)/(x-temp_vf)) #load and sort data data=np.genfromtxt('data file',skip_header=3) temp=data[:,0] inverse_temp=data[:,1] dc_conduct=np.log10(data[:,2:11]) only_adam=dc_conduct[:,4:9] colors = ['b','g','r','c','m'] labels = ['50mg 2-adam','300mg 2-adam','100 mg 2-adam','150 mg 2-adam','250mg 2-adam'] for i in range(0,len(only_adam)): #fit VTF function y=only_adam[:,i] popt, pcov = curve_fit(vft,temp,y) #plotting plt.plot(inverse_temp,y,color=colors[i],marker='o',markerfacecolor='none', label=labels[i]) plt.plot(inverse_temp,vft(temp, *popt),linewidth=0.00001,linestyle='- ',color=colors[i]) plt.ylabel("Ionic Conductivity [Scm**2/mol]") plt.xlabel("1000 / [T(K)]") plt.axis('tight') plt.legend(loc='lower left')
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49807191

http://stackoverflow.com/q/49857395
has answer: http://stackoverflow.com/a/49858173
has comment: http://stackoverflow.com/comment/86730709
has title: Python: Store indices of non-zero unique rows after comparing each rows with every other row in a matrix
has comment: http://stackoverflow.com/comment/86808384
possible better answer: http://stackoverflow.com/a/49861530
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49861530
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86808405
answer count: 2
accepted answer: http://stackoverflow.com/a/49858173
tagged with: arrays
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86805456
has comment: http://stackoverflow.com/comment/86731300
favorite count: 0
has body: For this matrix K= [[-1. 1. 0.] [ 0. 0. 0.] [ 0. -1. 1.] [ 0. 0. 0.] [ 0. -1. 1.] [ 0. 0. 0.]] task is to store indices of non-zero unique rows in an array (here answer would be {0,2}), so that K([0,2],:) is accessible for linear algebra operations. My attempt is: myList = [] for i in range(len(K)): #generate pairs for j in range(i+1,len(K)): #travel down each other rows if np.array_equal(K[i],K[j]) and np.any(K[i] != 0, axis=1) and np.any(K[j] != 0, axis=1): myList.append(K[i]) print ('indices of similar-non-zeros rows are\n',(i, j)), elif not np.array_equal(K[i],K[j]) and np.any(K[i] != 0,axis=1) and np.any(K[j] != 0, axis=1): myList.append(K[i]) print ('indices of non-similar-non-zeros rows are\n',(i, j)), else: continue new_K = np.asmatrix(np.asarray(myList)) new_new_K = np.unique(new_K,axis=0) print('Now K is \n',new_new_K) The answer is: new_new_K = [[-1. 1. 0.] [ 0. -1. 1.]] Question-1: How to do it in pythonic way. The above is an alternative solution with matrix storage limitation, but storing indices in array is more preferable.
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/86808226
tagged with: matrix
upvote count: 3
has comment: http://stackoverflow.com/comment/86764148

http://stackoverflow.com/comment/86805400
type: QuestionComment
has text: can i save my tweet directly like that :https://image.noelshack.com/fichiers/2018/16/3/1524040862-capture-d-ecran-2018-04-18-a-11-40-14.png In my json file
comment on: http://stackoverflow.com/q/49894665
score: 0
type: Comment

http://stackoverflow.com/a/49786712
score: 5
upvote count: 5
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49786441
has body: Python is a "garbage collection" language. One such consequence of this is that memory is automatically allocated and freed as needed. This creates memory fragmentation which can break apart transfers to the CPU caches. It's also not possible to change the layout of a data structure directly in memory which means that one transfer on the bus might not contain all the relevant information for a computation — even though it might all fit within the bus width. It essentially hurts any prospects for keeping L1/L2 caches filled with the relevant data for the next computation. Another problem comes from Python’s dynamic types and not being compiled. Many C developers generally realize at some point the compiler is usually smarter than they are. The compiler can perform many tricks to affect how things are laid out, how the CPU will run certain instructions, in what order, and the best way to optimize them. Python, however, is not compiled and, to make matters worse, has dynamic types which means that inferring any possible opportunities for optimizations with an algorithm is exponentially more difficult since code functionality can be changed during runtime. As mentioned in the comments, there ways to mitigate such problems, foremost being CPython or the Cython extensions for Python — it allows Python code to be compiled.

http://stackoverflow.com/comment/86781316
comment on: http://stackoverflow.com/a/49860925
type: Comment
score: 0
type: AnswerComment
has text: Yeah, thats actually correct, I pulled a part of it out from a project of mine and filled in the blanks. Ill edit

http://stackoverflow.com/comment/86671498
type: Comment
comment on: http://stackoverflow.com/q/49828029
score: 0
has text: @chrisz Thanks, that helped.
type: QuestionComment

http://stackoverflow.com/comment/86794440
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49871182
type: AnswerComment
has text: My input is the following: each time step I have a length 64 mfcc vector, so the embedding length is 64, not some other values. The spectrogram has indefinite length, but I will feed 1 time step (=64 numbers) to the network at a time. 100 is the truncated back propagation length of LSTM, so that's what I mean by saying "100 time steps". Now, what I want is that, the CNN should convolve within the same time step, meaning that it should take the 64 numbers as its input, and apply filters on this signal which consists of 64 numbers. So I think your code doesn't quite do the same thing. Thanks!

http://stackoverflow.com/comment/86839567
type: Comment
has text: What version of pip and python are you using? Edit your question to include the output of `sudo pip --version` and `python --version`.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49911823

http://stackoverflow.com/comment/86542750
score: 0
type: Comment
type: QuestionComment
has text: These are called lists and dicts.
comment on: http://stackoverflow.com/q/49763476

http://stackoverflow.com/q/49878953
tagged with: python
score: 15
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35529754
has title: Issues listening incoming messages in websocket client on Python 3.6
answer count: 1
downvote count: 0
tagged with: websocket
favorite count: 0
type: Question
upvote count: 15
has body: I'm trying to build a websocket client on Python using websockets package from here: Websockets 4.0 API I'm using this way instead of example code because I want to create a websocket client class object, and use it as gateway. I'm having issues with my listener method (receiveMessage) on client side, which raises a ConnectionClose exception at execution. I think maybe there is any problem with the loop. This is the simple webSocket client I've tried to build: import websockets class WebSocketClient(): def __init__(self): pass async def connect(self): ''' Connecting to webSocket server websockets.client.connect returns a WebSocketClientProtocol, which is used to send and receive messages ''' self.connection = await websockets.client.connect('ws://127.0.0.1:8765') if self.connection.open: print('Connection stablished. Client correcly connected') # Send greeting await self.sendMessage('Hey server, this is webSocket client') # Enable listener await self.receiveMessage() async def sendMessage(self, message): ''' Sending message to webSocket server ''' await self.connection.send(message) async def receiveMessage(self): ''' Receiving all server messages and handling them ''' while True: message = await self.connection.recv() print('Received message from server: ' + str(message)) And this is the main: ''' Main file ''' import asyncio from webSocketClient import WebSocketClient if __name__ == '__main__': # Creating client object client = WebSocketClient() loop = asyncio.get_event_loop() loop.run_until_complete(client.connect()) loop.run_forever() loop.close() To test incoming messages listener, server sends two messages to client when it stablishes the connection. Client connects correctly to server, and sends the greeting. However, when client receives both messages, it raises a ConnectionClosed exception with code 1000 (no reason). If I remove the loop in the receiveMessage client method, client does not raise any exception, but it only receives one message, so I suppose …
has answer: http://stackoverflow.com/a/49918082
accepted answer: http://stackoverflow.com/a/49918082

http://stackoverflow.com/comment/86829153
score: 0
type: Comment
type: QuestionComment
has text: If your function returns a Series instead of a tuple then you can call `s.apply(f)` and it will return a DataFrame. Constructing a Series for each row might be more expensive though.
comment on: http://stackoverflow.com/q/49906526

http://stackoverflow.com/comment/86621085
type: QuestionComment
comment on: http://stackoverflow.com/q/49793141
has text: The generated `help` displays the positionals after all the optionals, regardless of how they defined. But parsing is intended to be order independent - except for glitches like this.
score: 0
type: Comment

http://stackoverflow.com/comment/86744421
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49864385
has text: @Guillaume I edited the question to reflect your input. Thanks!

http://stackoverflow.com/comment/86553896
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49769335
type: QuestionComment
has text: could you explain what research have you completed so far before you posted the question?

http://stackoverflow.com/comment/86589688
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49786423
has text: Perhaps you meant to sort by the norm of the implied vectors?

http://stackoverflow.com/q/49826909
tagged with: jupyter
has title: how to print out dataframe in python
score: 4
accepted answer: http://stackoverflow.com/a/49866439
answer count: 4
has answer: http://stackoverflow.com/a/63840386
upvote count: 4
has answer: http://stackoverflow.com/a/49866439
has answer: http://stackoverflow.com/a/49827148
downvote count: 0
has answer: http://stackoverflow.com/a/51759028
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86669443
possible better answer: http://stackoverflow.com/a/49827148
tagged with: pandas
has body: normally using jupyternotes I can import pandas make my dataframe and export to csv. I'm trying to automate this reoccurring query with a python script. I can't figure out how to test my script because I cant print out the df to screen. In jupyternotes I just need to type out the df name in any cell and it will display. here what I'm doing import pandas as pd def run_agg_query(db): df1 = pd.read_sql( "select some query",conn) display(df1) but I cant get the df to display.
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/49760096
has title: How do I import selenium webdriver tests from one Python file to another?
has answer: http://stackoverflow.com/a/49769915
has body: I'm incredibly new to separating modules. I have this long Python script that I want to separate into different files by class and run them collectively in the same browser instance/window. The reason for this is all the tests are reliant on being logged into the same session. I'd like to do a universal setUp, then login, and then pull the different tests in one after another. Folder structure is: ContentCreator - main.py - _init_.py - Features - login.py - pytest.py - _init_.py Here is my code: login.py import unittest from selenium import webdriver from selenium.common.exceptions import NoSuchElementException import time import json driver = webdriver.Chrome() class logIn(unittest.TestCase): @classmethod def test_login(self): """Login""" driver.get("sign_in_url") # load username and pw through a json file with open('path/to/file.json', 'r') as f: config = json.load(f) # login driver.find_element_by_id("email").click() driver.find_element_by_id("email").clear() driver.find_element_by_id("email").send_keys(config['user']['name']) driver.find_element_by_id("password").click() driver.find_element_by_id("password").clear() driver.find_element_by_id("password").send_keys(config['user']['password']) driver.find_element_by_id("submit").click() time.sleep(3) print("You are Logged In!") pytest.py import time import unittest from datetime import datetime from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from displays import DISPLAY_TYPES, DISPLAY_NAMES driver = webdriver.Chrome() #driver.get("url") class createContent(unittest.TestCase): @classmethod def test_add_required(self): """Test adding all the required fields across all sites:""" for i in range(1): """This is the number of each type of article that will be created.""" for i in range(1): """This is how many different article types that will be created.""" print("create new content") time.sleep(1) driver.find_element_by_link_tex…
tagged with: python
has answer: http://stackoverflow.com/a/73323569
tagged with: selenium-webdriver
score: 0
answer count: 3
tagged with: pytest
type: UnansweredQuestion
tagged with: selenium
has answer: http://stackoverflow.com/a/49785206
tagged with: webdriver
type: Question

http://stackoverflow.com/q/49793368
tagged with: python
has answer: http://stackoverflow.com/a/49793586
has title: Specify time period in domain computed field (odoo 10)
type: AnsweredQuestion
score: 0
tagged with: odoo
answer count: 1
has body: How can I specify a date in the domain of a computed field: for record in self: last_confirmed_order = self.env['sale.order'].search( [('partner_id', '=', record.name),('date_order','&amp;gt;=',time.strftime('%Y-%m-%d'))], order='date_order desc', limit=1000 ) sum = 0 for x in last_confirmed_order: sum = sum + x.amount_total record['x_last_order_sum'] = sum Gives an error Thx for the advice I adjusted my code to for record in self: today=time.strftime('%Y-%m-%d') last_confirmed_order = self.env['sale.order'].search( [('partner_id', '=', record.name),('date_order','=',today)], order='date_order desc', limit=1000 ) record['x_last_order'] = last_confirmed_order.date_order for x in last_confirmed_order: sum = sum + x.amount_total record['x_last_order_sum'] = sum I get no error but the value stays zero. While I do have orders for that customer today. Do I have to convert date_order to same format as Y M D ?
tagged with: computed-field
type: Question
accepted answer: http://stackoverflow.com/a/49793586

http://stackoverflow.com/comment/86754374
has text: Ok updated with error
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49869562
score: 0

http://stackoverflow.com/comment/86920231
score: 2
has text: The question **still** doesn't show what `% change` is supposed to mean. From deleted contents, it started with *total **count** of fruits*; comments recently mentioned `total basket value` - please specify *in the question proper*.
comment on: http://stackoverflow.com/q/49890536
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49873926
has answer: http://stackoverflow.com/a/49875273
has comment: http://stackoverflow.com/comment/86827003
type: Question
tagged with: python-itertools
upvote count: 0
type: UnansweredQuestion
has title: How to aggregate after fetching result using groupby using itertools
answer count: 1
tagged with: python
tagged with: dictionary
downvote count: 1
favorite count: 0
tagged with: list
has comment: http://stackoverflow.com/comment/86765153
has body: I am having a list as a=[{'name': 'xyz','inv_name':'asd','quant':300,'amt':20000, 'current':30000},{'name': 'xyz','inv_name':'asd','quant':200,'amt':2000,'current':3000}] This list i have fetched using itertools groupby. I want to form a list after adding up the quant, amt and current filed for same name and inv_name and create a list something like : [{'name':'xyz','inv_name':'asd','quant':500,'amt':22000,'current':33000} Any suggestions on how to achieve this?
has comment: http://stackoverflow.com/comment/86765658
score: -1
has comment: http://stackoverflow.com/comment/86765074

http://stackoverflow.com/comment/86626315
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49805631
type: Comment
has text: Thanks for the response,it's perfect :D

http://stackoverflow.com/q/49799635
tagged with: flask
has body: I am trying to change the default formatter in Flask 0.12. Here is my code from pomegranate.routes import app import os from flask import request from flask.logging import Formatter, StreamHandler, DEBUG class RequestFormatter(Formatter): def format(self, record): record.url = request.url record.remote_addr = request.remote_addr record.request_id = request.headers.get('X-Request-Id', '') return super().format(record) formatter = RequestFormatter( '[%(asctime)s] %(request_id)s %(remote_addr)s %(url)s\n' '%(levelname)s %(module)s: %(message)s' ) stream_handler = StreamHandler() stream_handler.setLevel(DEBUG) app.logger.addHandler(stream_handler) for handler in app.logger.handlers: handler.setFormatter(formatter) dev = int(os.getenv('FLASK_DEBUG', 0)) if __name__ == '__main__': host = '0.0.0.0' if dev == 1 else '127.0.0.1' app.run(host=host, port=8081, debug=True) But the new formatter does not seem to take effect. It still uses the default formatter. What is going wrong?
favorite count: 0
has title: Changing default formatter in Flask 0.12
upvote count: 3
score: 3
tagged with: python
type: Question
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/49847508
answers question: http://stackoverflow.com/q/49846783
downvote count: 0
upvote count: 2
type: Answer
has body: In case you want to change the reverse relation name class Room(Base): ''' fields above ''' users = models.ManyToManyField(User,related_name='get_rooms') Now you use the reverse relation with the related_name: the_user.get_rooms.all()
score: 2

http://stackoverflow.com/q/49776624
has title: Passing value from slave window tkinter and python
has body: I'm trying to pass a value from a slave window in tkinter running on python, and I just can't figure it out. Here is the code I have so far: #!/usr/bin/env python3 import time import pigpio from tkinter import * GPIO=21 GPIO2=16 GPIO3=20 pi = pigpio.pi() if not pi.connected: exit() pi.set_mode(GPIO,pigpio.OUTPUT) pi.set_mode(GPIO2,pigpio.OUTPUT) gv=int() def tx_pulses(pi, GPIO, hertz, num, pulse_len=1): motSpeed = int((1/(dscale.get()))*2000) print(motSpeed) pulse_len = motSpeed assert num &lt; 65536 num_low = num % 256 num_high = num // 256 wf = [] wf.append(pigpio.pulse(1&lt;&lt;GPIO, 0, pulse_len)) wf.append(pigpio.pulse(0, 1&lt;&lt;GPIO, pulse_len)) pi.wave_add_generic(wf) wid = pi.wave_create() if wid &gt;= 0: pi.wave_chain([255, 0, wid, 255, 1, num_low, num_high]) while pi.wave_tx_busy(): time.sleep(0.1) pi.wave_delete(wid) def runMotor(): motRevs = int(((scale.get())*400)*5.08) print(motRevs) pi.write(GPIO2,0) pi.write(GPIO3,1) tx_pulses(pi, GPIO, 1000, motRevs) # 250 pulses @ 1000 Hz pi.write(GPIO3,0) tx_pulses(pi, GPIO, 1000, motRevs) # 2391 pulses @ 5000 Hz pi.write(GPIO2,1) def setUp(): speedWin = Toplevel() speedWin.geometry('800x600') speedWin.title('Stepper Control') label = Label(speedWin, text='Inches of Travel') label.place(x=350, y=100) scale = Scale(speedWin, from_=0.0, to=15.0 ,orient=HORIZONTAL,length=600, resolution=0.1, tickinterval=1) scale.place(x=100, y=125) dlabel = Label(speedWin, text='Speed') dlabel.place(x=370, y=200) dscale = Scale(speedWin, from_=1, to=10 ,orient = HORIZONTAL,length = 600, tickinterval=1) dscale.place(x=100, y=225) button = Button(speedWin, text='Apply Values', command=runMotor, padx = 20, pady = 20) button.place(x=350, y=350) button3 = Button(speedWin, text='Back To Main Window', command=speedWin.destroy, padx=20, pady=20) button3.place(x=500, y=350) speedWin.mainloop() mainWin = Tk() mainWin.geometry('800x600') mainWin.title('Main Window') button2 = Button(mainWin, text='Go To Setup', command=setUp, padx=20, pady=2…
answer count: 1
tagged with: raspberry-pi3
score: 0
has comment: http://stackoverflow.com/comment/86570758
tagged with: python
type: Question
tagged with: tkinter
has answer: http://stackoverflow.com/a/49777568
type: UnansweredQuestion

http://stackoverflow.com/comment/115840906
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49802753
type: Comment
has text: why people mark question as duplicate just by seeing the title. this question is quite different from the question that has mentioned duplicate of.

http://stackoverflow.com/q/49868630
has body: I am trying to download youtube video using PyTube package but I am unable to do so. I am using Python 3.5 and pytube 9.2.2. Urllib doesn't give me an error in other programs but it is giving me errors here. The code I am using is: #importing the module from pytube import YouTube #where to save SAVE_PATH = "E:/" #to_do #link of the video to be downloaded link="https://www.youtube.com/watch?v=xWOoBJUqlbI" yt = YouTube(link) #filters out all the files with "mp4" extension mp4files = yt.filter('mp4') yt.set_filename('GeeksforGeeks Video') #to set the name of the file #get the video with the extension and resolution passed in the get() function d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution) try: #downloading the video d_video.download(SAVE_PATH) except: print("Some Error!") print('Task Completed!') The errors that I am getting are: Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\urllib\request.py", line 1240, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 1083, in request self._send_request(method, url, body, headers) File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 1128, in _send_request self.endheaders(body) File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 1079, in endheaders self._send_output(message_body) File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 911, in _send_output self.send(msg) File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 854, in send self.connect() File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\http\client.py", line 1237, in connect server_hostname=server_hostname) File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\ssl.py", line 376, in wrap_socket _context=self) File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib…
downvote count: 0
tagged with: error-handling
favorite count: 0
tagged with: python-3.x
tagged with: pytube
has comment: http://stackoverflow.com/comment/86819036
has title: PyTube, URLlib, Http packages giving error while trying to download youtube video
has comment: http://stackoverflow.com/comment/86811566
tagged with: python
has comment: http://stackoverflow.com/comment/86812261
tagged with: urllib
type: Question
score: 2
answer count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/49871571
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86758447
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49871031
has body: The problem is that you are setting the size of the video frame that matches the first image and then you save images with a size that may not match the size of the first image. The following solution should work: import os import cv2 dir_path = os.getcwd() ext = '.jpg' output = 'video.avi' shape = 960, 720 fps = 1 images = [f for f in os.listdir(dir_path) if f.endswith(ext)] fourcc = cv2.VideoWriter_fourcc(*'DIVX') video = cv2.VideoWriter(output, fourcc, fps, shape) for image in images: image_path = os.path.join(dir_path, image) image = cv2.imread(image_path) resized=cv2.resize(image,shape) video.write(resized) video.release()
type: Answer
answers question: http://stackoverflow.com/q/49871031
has comment: http://stackoverflow.com/comment/86758733

http://stackoverflow.com/comment/114263432
comment on: http://stackoverflow.com/a/49786016
type: AnswerComment
score: 0
type: Comment
has text: We can't do this for `csv.reader`, the only thing we can do is `next(reader)` or iteration, any suggestions?

http://stackoverflow.com/comment/86773423
score: 4
comment on: http://stackoverflow.com/q/49878918
has text: Sort the tuples first?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49797977
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86612186
possible better answer: http://stackoverflow.com/a/49798882
answer count: 2
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/49798882
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49799012
favorite count: 0
type: Question
tagged with: transform
has body: Can you help me to reshape a Pandas DataFrame from this: df = pd.DataFrame({ 'Clasif1': [np.NaN, np.NaN, 'PRE', 'POST'], 'Currency': [np.NaN, np.NaN, 'LC', 'USD'], 'Unnamed: 1': ['A','01/01/2018',1,7], 'Unnamed: 2': ['A','02/01/2018',2,8], 'Unnamed: 3': ['A','03/01/2018',3,9], 'Unnamed: 4': ['B','01/01/2018',4,10], 'Unnamed: 5': ['B','02/01/2018',5,11], 'Unnamed: 6': ['B','03/01/2018',6,12] }) Source To this: df_result = pd.DataFrame({ 'Clasif1': ['PRE', 'POST','PRE', 'POST','PRE', 'POST','PRE', 'POST','PRE', 'POST','PRE', 'POST'], 'Currency': ['LC', 'USD','LC', 'USD','LC', 'USD','LC', 'USD','LC', 'USD','LC', 'USD'], 'A/B': ['A','A','A','A','A','A','B','B','B','B','B','B'], 'Date': ['01/01/2018','01/01/2018','02/01/2018','02/01/2018','03/01/2018','03/01/2018','01/01/2018','01/01/2018','02/01/2018','02/01/2018','03/01/2018','03/01/2018'], 'Value': [1,7,2,8,3,9,4,10,5,11,6,12] }) Output The result DataFrame rows order not needs necesary to match with the expected. Thanks for your help,
has title: Pandas - Reshape
accepted answer: http://stackoverflow.com/a/49799012
tagged with: reshape

http://stackoverflow.com/a/49865085
score: 0
has comment: http://stackoverflow.com/comment/86750941
has comment: http://stackoverflow.com/comment/86764583
has body: Try this xpath - "//div[normalize-space(.)='Room 34']/ancestor::tbody/tr/td//input[@type='submit']" The 'Room 34' can be substituted by a python variable. normalize-space is required as the text has a lot of white space.
has comment: http://stackoverflow.com/comment/86748761
type: Answer
answers question: http://stackoverflow.com/q/49863598

http://stackoverflow.com/a/49762223
has comment: http://stackoverflow.com/comment/97504480
accepted answer of: http://stackoverflow.com/q/49762199
type: Answer
type: AcceptedAnswer
downvote count: 0
score: 34
answers question: http://stackoverflow.com/q/49762199
upvote count: 34
has body: Get a boolean mask and just count the "True"s: (arr1 &gt; 0.6).sum()

http://stackoverflow.com/comment/86584604
type: AnswerComment
has text: Wow, its working Perfectly! Awesome! Thanks you very much!
type: Comment
comment on: http://stackoverflow.com/a/49762445
score: 0

http://stackoverflow.com/q/49888520
type: Question
tagged with: g-code
has title: Python code to convert a plt file into gcode with a specific format
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49888770
has body: I'd like to convert a set of coordinates from one file format to another. It's for a drawing machine, like a plotter. The first file is a plt file that looks like this: PU-3410,7784;PD-3373,-2281;PU16705,7978;PD16435,5325; (continues for thousands of coordinates) and I'd like to convert it to another text file which would have this format: G01 X-3410 Y7784 Z1000 G01 X-3373 Y-2281 Z0 G01 X16705 Y7978 Z1000 G01 X-16435 Y5325 Z0 PU means Pen Up (=Z1000 in Gcode) and PD is pen down (Z0). I'm very new to python, all I know is how to code for Arduino. This piece of code would be so helpful. I've tried to understand how to open and write files but I'd too novice for this project so I thought I'd ask for help rather than give up. Really appreciate any help! Cheers, Pierre
score: 2
tagged with: python-2.7
tagged with: python
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/86621683
has text: Can you add what the expected numpy array for x and y would look like, also why would y be 3d given the current structure of your lstm
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49803503
type: QuestionComment

http://stackoverflow.com/q/49786769
tagged with: python-3.x
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49786822
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49786822
has body: This works: import pandas as pd raw_data = { 'type_1': [1, 1], 'id_1': ['2', '3'], 'name_1': ['Alex', 'Amy']} df_a = pd.DataFrame(raw_data, columns = ['type_1', 'id_1', 'name_1']) raw_datab = { 'type_2': [1, 1], 'id_2': ['4', '5'], 'name_2': ['Billy', 'Brian']} df_b = pd.DataFrame(raw_datab, columns = ['type_2', 'id_2', 'name_2']) dfs = [df_a.set_index(['type_1','id_1']), df_b.set_index(['type_2','id_2'])] df = pd.concat(dfs, axis=1) print (df) prints: name_1 name_2 1 2 Amy NaN 3 Alex NaN 4 NaN Billy 5 NaN Brian If I change the following, it doesn't work as the multi-index key in raw_data is a duplicate: raw_data = { 'type_1': [1, 1], 'id_1': ['2', '2'], # &lt;-- changed from 3 to 2 'name_1': ['Alex', 'Amy']} and the following: raw_datab = { 'type_2': [1, 1], 'id_2': ['2', '5'], # &lt;-- changed from 4 to 2 'name_2': ['Billy', 'Brian']} As a result, both Alex, Amy and Billy have the same multi-index key [1,2], so the concat fails with: cannot handle a non-unique multi-index! But the duplicate data is valid, and I need to concatenate it anyway. This is the result I need to achieve (note that this should be an outer join, the default): name_1 name_2 1 2 Amy Billy 2 Alex Billy 5 NaN Brian How's this possible with Pandas?
tagged with: pandas
score: 2
type: AnsweredQuestion
answer count: 1
downvote count: 0
has title: Need to handle a concatenated dataframe with non-unique multi-index
favorite count: 0

http://stackoverflow.com/comment/86833754
type: AnswerComment
has text: I am just assigning friends = pd.Series({k: list(v) for k, v in json.loads(j).items()}).to_frame().rename(columns={0: 'listOfFriends'}) and then use the pd.merge and for json data I am reading from the file like : json_data = json.load(open(input.json)) data = pd.read_json(json_data) j=data.to_json()
comment on: http://stackoverflow.com/a/49870370
score: 0
type: Comment

http://stackoverflow.com/q/49764456
type: Question
has answer: http://stackoverflow.com/a/49764653
type: UnansweredQuestion
tagged with: python
has title: Changing passwords via Python for SSL certificate
has body: I am looking for a method of doing the equivalent of the command below using Python: openssl rsa -aes256 -in serverKey.pem -out newkey.pem I am trying to find out if this is possible in Python since Python meets my cross platform requirements and find a Python built in! Thanks!!
tagged with: openssl
score: 0
answer count: 1

pythonanywhere
tags question: http://stackoverflow.com/q/49808799
tags question: http://stackoverflow.com/q/49879996
tag name: pythonanywhere
type: Tag

http://stackoverflow.com/q/49832425
tagged with: python
tagged with: flask
score: -1
type: AnsweredQuestion
upvote count: 0
has body: I'm trying to set up integer field validation on a form in Flask, but I keep getting 'Method Not Allowed'. I can't see what is wrong with my routes? My main file is: from flask import Flask, render_template from flask_wtf import FlaskForm from wtforms import IntegerField # from perfect_numbers import classify app = Flask(__name__) app.config['SECRET_KEY'] = 'MySecretKey' # num = 12 # Classify = classify(num) class PerfectForm(FlaskForm): number = IntegerField(4) @app.route('/', methods=['POST']) def form(): form = PerfectForm() return render_template('index.html', form = form) if __name__ == '__main__': app.run(debug=True) Then I have a standard layout.html file: PERFECT App {% block body %}{% endblock %} And my index.html is: {% extends 'layout.html' %} {% block body %} PERFECT NUMBERS This is a basic Flask App to illustrate Aliquot Sums and Perfect Numbers Input a number to check if it is abundant, perfect, or deficient {{ form.csrf_token }} {{ form.number }} {% endblock %}
answer count: 1
downvote count: 1
favorite count: 0
has title: Method Not Allowed in Flask for IntegerField form
type: Question
accepted answer: http://stackoverflow.com/a/49841617
has answer: http://stackoverflow.com/a/49841617

http://stackoverflow.com/comment/86782055
comment on: http://stackoverflow.com/q/49882642
type: Comment
type: QuestionComment
score: 0
has text: What's the classification that you want to perform? Is it a 41-class classification where each class is exclusive? I.e. each object should be classified as one and only one class?

http://stackoverflow.com/a/49846136
has body: In settings.py you'll need: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'user_name', 'PASSWORD': 'user_password', 'HOST': 'localhost', 'PORT': '3306', } You'll need to create the db and user and grant permissions within MySQL. You'll also need to ensure you have MySQL setup and running.
answers question: http://stackoverflow.com/q/49846084
has comment: http://stackoverflow.com/comment/86844591
has comment: http://stackoverflow.com/comment/86836330
type: Answer
upvote count: 2
score: 2
downvote count: 0

deserialization
type: Tag
tags question: http://stackoverflow.com/q/49905287
tags question: http://stackoverflow.com/q/49902115
tag name: deserialization

http://stackoverflow.com/a/49823284
answers question: http://stackoverflow.com/q/49822609
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86662492
type: Answer
accepted answer of: http://stackoverflow.com/q/49822609
has comment: http://stackoverflow.com/comment/86662403
has body: if you could build a string with all the words to search from list_of_words like (Turin|Milan) , you could do a regex match on: ^.*\b(Turin|Milan)\b.*$ Also, we could avoid both the for loops, as mentioned in this answer.

http://stackoverflow.com/comment/86706418
comment on: http://stackoverflow.com/q/49843335
type: Comment
type: QuestionComment
score: 0
has text: What is the full error stack, showing the line of code affected, you're seeing?

http://stackoverflow.com/comment/87061795
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49888600
has text: You're welcome :) . I no longer need the `result` contents, since I was able to reproduce the problem on my side.

http://stackoverflow.com/a/49884211
score: 0
answers question: http://stackoverflow.com/q/49868931
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86880818
type: Answer
accepted answer of: http://stackoverflow.com/q/49868931
has body: The following code works for me on Linux, using the psutil package. When the file can't be opened a search is made to find all other processes that have the file open, and these are sent a terminate signal. NB this works only if the calling process has the correct permissions. import psutil import sys import os import signal def terminate_others(pattern): pids = psutil.pids(); for pid in pids: p = psutil.Process(pid) try: flist = p.open_files() if flist: for f in flist: if pattern in f.path: print "Terminating " + repr(pid) os.kill(pid, signal.SIGTERM) except: pass fname = "Entry_Log.csv" try: with open(fname, "a") as log: log.write("Some log text") except: print "error:", sys.exc_info()[0] # close other processes that have this file open terminate_others(fname) Hope this may help.

http://stackoverflow.com/q/49820583
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49820698
possible better answer: http://stackoverflow.com/a/49820698
tagged with: python
linked to: http://stackoverflow.com/q/154443
type: AnsweredQuestion
answer count: 2
tagged with: pycharm
has title: Where does PyCharm store compiled files?
linked to: http://stackoverflow.com/q/5149832
score: 7
upvote count: 7
has answer: http://stackoverflow.com/a/49820675
accepted answer: http://stackoverflow.com/a/49820675
downvote count: 0
has body: I'm new to PyCharm/Python, and can't figure out where the IDE stores compiled python *.pyc files. Coming from the IntelliJ world, it is strange that I don't see any menu options to re-build the project, or build individual files. I'm also unable to find any pyc files while searching the project directory, so basically, I've no idea whether successful compilation has happened at all, although the GitHub imported project is error free. What can I do here?

http://stackoverflow.com/comment/86611499
score: 0
type: Comment
has text: Thanks a ton!! This has been a great help.
type: AnswerComment
comment on: http://stackoverflow.com/a/49797319

http://stackoverflow.com/q/49868937
has answer: http://stackoverflow.com/a/49869004
has title: I see the text, but cannot .text return it SOUP
type: Question
has body: Running: from bs4 import BeautifulSoup import requests source = requests.get('https://www.yellowpages.com/search? search_terms=bestbuy+10956&amp;geo_location_terms=10956').text soup = BeautifulSoup(source, 'lxml') for article in soup.find_all("div", {"class": "result"}): info_primary = article.find("div", {"class": "info-section info- primary"}).text print(info_primary) ` Yields some noisy (number) characters when yellowpages has a rating for the store. The ratings are stored in "a" tags if they exist, else there is no "a" tag and it goes straight to "p" tags. I wanted to just grab the text from the "p" tags. Running: info_primary = article.find("div", {"class": "info-section info-primary"}).p.text Gives: AttributeError: 'NoneType' object has no attribute 'text' Running: info_primary = article.find("div", {"class": "info-section info-primary"}).p Runs and I can see the text nested, but cannot return it. Upon looking further, the phone number for the store, which I want, is outside of the "p" tag. Maybe correctly accessing the "span" tags via different class descriptions would help? Ideas? Thanks! I am new to Python as a forewarning.
answer count: 1
tagged with: web-scraping
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/49869004
tagged with: beautifulsoup
type: AnsweredQuestion
score: 0
tagged with: python

http://stackoverflow.com/comment/86770983
comment on: http://stackoverflow.com/a/49877674
has text: @jpp Does HDF5 increase the loading speed further?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49777368
type: Answer
score: 0
has body: I was using a Windows compiled version of psycopg2 and needed Linux. Swapped it out for the one here: https://github.com/jkehler/awslambda-psycopg2
answers question: http://stackoverflow.com/q/49761497

http://stackoverflow.com/a/49910631
accepted answer of: http://stackoverflow.com/q/49910608
score: 2
downvote count: 0
type: Answer
has body: To change anything, you have to save the object. In classes you need to give it a name starting with "self.". from tkinter import * class MyFirstGUI: def __init__(self, master): self.master = master master.title("Login") Label(master, text="E-Mail Address:").grid(row=0) Label(master, text="Password:").grid(row=1) Label(master, text="UserID:").grid(row=2) e1 = Entry(master) e2 = Entry(master) e3 = Entry(master) e1.grid(row=0, column=1) e2.grid(row=1, column=1) e3.grid(row=2, column=1) b1 = Button(text ="Login!", command=self.test) b1.grid(row=3, column=1) Label(master, text="Status: ").grid(row=4, column=0) self.mylbl = Label(master, text="Boop!") self.mylbl.grid(row=5, column=0) def test(self): self.mylbl.config(text="Beep!") root = Tk() my_gui = MyFirstGUI(root) root.mainloop() Note that I made the initialization 2 lines instead of one. This is very important if you want to access the object later.
upvote count: 2
answers question: http://stackoverflow.com/q/49910608
has comment: http://stackoverflow.com/comment/86837331
type: AcceptedAnswer

http://stackoverflow.com/q/49883568
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86783207
tagged with: python
has body: How do I pass class variables into class methods? I wrote a program to recursively swap every second character of a string. Since I could not pass self.inputstring as arguments I decided to use a nested function. Is there a better solution? Is it possible to use class variables as arguments? class Swap(object): def __init__(self, astring): self.acc = "" self.count = 1 self.inputstring = astring self.checkstring = astring def swap2(self): string = self.inputstring def swaphelper(string): if len(string) == 2: self.acc = self.acc + string[1] + string[0] self.count = self.count + 2 if len(self.checkstring) == len(self.acc): return self.acc if len(self.checkstring) != len(self.acc): return swaphelper(self.inputstring[self.count-1:self.count+1]) return swaphelper(string) c = Swap("I'm a string") d = c.swap2()
favorite count: 0
tagged with: class
score: 2
has answer: http://stackoverflow.com/a/49883625
answer count: 1
has comment: http://stackoverflow.com/comment/86783279
has title: Passing class variables into class methods
type: Question
has comment: http://stackoverflow.com/comment/86783225
has comment: http://stackoverflow.com/comment/86783387
upvote count: 2
tagged with: class-method

http://stackoverflow.com/comment/86671128
type: Comment
comment on: http://stackoverflow.com/a/49827866
type: AnswerComment
has text: thanks for the answer, testing the solutions one by one :)
score: 1

http://stackoverflow.com/comment/86584786
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49784499
has text: @ducminh I have added some additional information into the questions description above. Thanks!
type: QuestionComment

http://stackoverflow.com/q/49869767
has comment: http://stackoverflow.com/comment/86754898
has comment: http://stackoverflow.com/comment/86754998
score: 0
has comment: http://stackoverflow.com/comment/86755047
has comment: http://stackoverflow.com/comment/86754929
tagged with: python
has comment: http://stackoverflow.com/comment/86754847
has comment: http://stackoverflow.com/comment/86754977
has comment: http://stackoverflow.com/comment/86754999
has comment: http://stackoverflow.com/comment/86754969
has body: How do I scale the drawn pixmap of QGraphicsItem? Can't find any setScaled(), size or height property there. After the picture becomes big, the scrollbars of MyGraphicsView class should be able to scroll the big scaled picture. #!/usr/bin/env python from PyQt5.QtCore import (QRectF, Qt) from PyQt5.QtGui import (QPainter, QPixmap) from PyQt5.QtWidgets import (QMainWindow, QApplication, QGraphicsView, QGraphicsScene, QGraphicsItem) class TicTacToe(QGraphicsItem): def __init__(self, helper): super(TicTacToe, self).__init__() self.mypixmap = QPixmap("exit.png") def paint(self, painter, option, widget): painter.setOpacity(1) painter.drawPixmap(0,0, 300, 300, self.mypixmap) def boundingRect(self): return QRectF(0,0,300,300) class MyGraphicsView(QGraphicsView): def __init__(self): super(MyGraphicsView, self).__init__() scene = QGraphicsScene(self) self.tic_tac_toe = TicTacToe(self) scene.addItem(self.tic_tac_toe) self.setScene(scene) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) class Example(QMainWindow): def __init__(self): super(Example, self).__init__() self.y = MyGraphicsView() self.setCentralWidget(self.y) if __name__ == '__main__': import sys app = QApplication(sys.argv) w = Example() w.show() sys.exit(app.exec_())
has comment: http://stackoverflow.com/comment/86755087
type: Question
has comment: http://stackoverflow.com/comment/86754946
has title: How to make the picture zoom (QGraphicsItem), and make scrollbars change their size accordingly (QGraphicsScene)?
answer count: 0
tagged with: pyqt
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86754980
linked to: http://stackoverflow.com/q/35508711
has comment: http://stackoverflow.com/comment/86754803
has comment: http://stackoverflow.com/comment/86754857
has comment: http://stackoverflow.com/comment/86754832
duplicate of: http://stackoverflow.com/q/35508711
has comment: http://stackoverflow.com/comment/86755151
tagged with: qt

http://stackoverflow.com/comment/92804057
score: 0
type: AnswerComment
has text: According to Davis King, as mentioned here https://peshmerge.io/how-to-build-dlib-on-linux-ubuntu-18-04-using-cmake-with-avx-support-and-install-its-python-api/#comment-44 you only need to run `python setup.py install` assuming python is an alias for python3 !
type: Comment
comment on: http://stackoverflow.com/a/52947436

http://stackoverflow.com/a/49882879
has body: Don't hit corenlp.run with API calls! This is a server set up for demos, and is not provisioned for a large number of requests. It's giving you a 401 Unauthorized because you are unauthorized to make API requests against the public demo server. You should instead run your own instance of the CoreNLP Server and make API requests against that instead.
has comment: http://stackoverflow.com/comment/86782231
has comment: http://stackoverflow.com/comment/86782392
answers question: http://stackoverflow.com/q/49879996
type: Answer
has comment: http://stackoverflow.com/comment/86782070
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/86605003
type: Comment
has text: You add the shebang line at the top of your script `#!/usr/bin/python` and then invoke `./myprogram.py`. If you're on windows, good luck.
comment on: http://stackoverflow.com/q/49795352
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86545965
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49765150
has text: In `hand_stats` function, it is not finding `card` defined. I think it is the issue, if detail error with line number is provided may be it will be helpful.

http://stackoverflow.com/comment/86739873
comment on: http://stackoverflow.com/a/49861890
type: Comment
score: 0
type: AnswerComment
has text: Thanks so much for the reply! If I wanted to generalize and take the n largest every m indices, I would just change each of those 2's respectively? I'll give this a try either way and see how it goes!

http://stackoverflow.com/comment/86626558
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49805647
has text: Can you post the plot or other output of your code?
type: Comment

http://stackoverflow.com/comment/86675462
type: Comment
comment on: http://stackoverflow.com/q/49830040
score: 0
type: QuestionComment
has text: I did not initialize specific error message. I only send 'oops lanjut' when there is an error . 'cause the tanggald, the query is not executed @Sean

http://stackoverflow.com/q/49902930
tagged with: converters
tagged with: python
tagged with: valueerror
tagged with: traceback
type: AnsweredQuestion
score: 0
tagged with: pandas
has body: I'm using the following to ensure a dataframe column has the correct data type before I proceed with operations: &gt;&gt;&gt; cfun = lambda x: float(x) &gt;&gt;&gt; df = pd.read_excel(xl, converters={'column1': cfun}) Using converters instead of dtype so that the traceback will tell me explicitly what value caused the issue: ValueError: could not convert string to float: '100%' What I would like to do is take that information (that the string "100%" was the problem) and tell the user where it occurred in the dataframe/file. How can I get that information from the exception in order to get a row index and, say, print the entire row? Note: Adding the percent sign isn't the only mistake my users make, otherwise I'd just replace any '%' with ''.
answer count: 1
accepted answer: http://stackoverflow.com/a/49903166
has answer: http://stackoverflow.com/a/49903166
type: Question
has title: Access specifics of ValueError in pandas.read_excel() converters

http://stackoverflow.com/comment/86749658
has text: Ah I see, but for some reason it is still not displaying the image in the div. I'll update the original post again. @Ajax1234
comment on: http://stackoverflow.com/a/49864558
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86612260
has text: I thought you said it was working, sorry! Is it not working still?
type: AnswerComment
comment on: http://stackoverflow.com/a/49786912
score: 0
type: Comment

system
tag name: system
tags question: http://stackoverflow.com/q/49798450
type: Tag

http://stackoverflow.com/comment/86753699
type: Comment
type: AnswerComment
has text: @DanieleCappuccio there, I think that's more in line with what OP may have meant.
score: 0
comment on: http://stackoverflow.com/a/49869079

http://stackoverflow.com/q/49873801
has comment: http://stackoverflow.com/comment/86794986
has comment: http://stackoverflow.com/comment/86860313
has comment: http://stackoverflow.com/comment/87038227
score: 0
has comment: http://stackoverflow.com/comment/86888275
tagged with: python
tagged with: google-cloud-dataflow
tagged with: dataflow
type: Question
has title: DATAFLOW CalledProcessError returned non-zero exit status 2
answer count: 0
has comment: http://stackoverflow.com/comment/86871501
tagged with: google-cloud-platform
type: UnansweredQuestion
has body: I'm trying to use Dataflow in the GCP. The contextualization is the following one. -I have created a pipeline that works correctly in local. This is test.py document script: (I do a subprocess fonction which takes the script "script2.py" to be executed, script located in local and stored in a bucket in the cloud as well) import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import GoogleCloudOptions from apache_beam.options.pipeline_options import StandardOptions from apache_beam.options.pipeline_options import SetupOptions project ="titanium-index-200721" bucket ="pipeline-operation-test" class catchOutput(beam.DoFn): def process(self,element): import subprocess import sys s2_out = subprocess.check_output([sys.executable, "script2.py", "34"]) return [s2_out] def run(): project = "titanium-index-200721" job_name = "test-setup-subprocess-newerr" staging_location = 'gs://pipeline-operation-test/staging' temp_location = 'gs://pipeline-operation-test/temp' setup = './setup.py' options = PipelineOptions() google_cloud_options = options.view_as(GoogleCloudOptions) options.view_as(SetupOptions).setup_file = "./setup.py" google_cloud_options.project = project google_cloud_options.job_name = job_name google_cloud_options.staging_location = staging_location google_cloud_options.temp_location = temp_location options.view_as(StandardOptions).runner = 'DataflowRunner' p = beam.Pipeline(options=options) input = 'gs://pipeline-operation-test/input2.txt' output = 'gs://pipeline-operation-test/OUTPUTsetup.csv' results =( p| 'ReadMyFile'&gt;&gt;beam.io.ReadFromText(input)| 'Split'&gt;&gt;beam.ParDo(catchOutput())| 'CreateOutput'&gt;&gt;beam.io.WriteToText(output) ) p.run() if __name__ == '__main__': run() I have done a "setup.py" script for being able to include all the pakcages needed in future scripts to be also run in the dataflow of gcp. Nevertheless when I try to run all that in the cloud, I'm having…

http://stackoverflow.com/comment/91703463
comment on: http://stackoverflow.com/q/49909957
score: 0
has text: Could you solve this? I am currently facing the issue.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86737523
has text: What's `trainX` and `testX` shape? At a first glance, it seems your `input_shape` is wrong. The first dimension represents the sequence length (`look_back`, in your case) and the following ones represent the actual data shape.
comment on: http://stackoverflow.com/q/49861009
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86667293
comment on: http://stackoverflow.com/a/49825104
has text: Use Stock.objects.create(**validate_data)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/102342555
comment on: http://stackoverflow.com/q/49908705
type: Comment
type: QuestionComment
score: 0
has text: This [paper](https://arxiv.org/pdf/1901.02514.pdf) might be discussing part of the solution to your problem.

regex
tags question: http://stackoverflow.com/q/49767309
tags question: http://stackoverflow.com/q/49787739
tags question: http://stackoverflow.com/q/49786931
tags question: http://stackoverflow.com/q/49847622
tags question: http://stackoverflow.com/q/49906269
tags question: http://stackoverflow.com/q/49843095
tags question: http://stackoverflow.com/q/49906179
tags question: http://stackoverflow.com/q/49897375
tags question: http://stackoverflow.com/q/49873707
tags question: http://stackoverflow.com/q/49770095
tags question: http://stackoverflow.com/q/49763597
tags question: http://stackoverflow.com/q/49885266
tags question: http://stackoverflow.com/q/49783425
tags question: http://stackoverflow.com/q/49771199
tags question: http://stackoverflow.com/q/49787417
tags question: http://stackoverflow.com/q/49778697
tags question: http://stackoverflow.com/q/49794501
tags question: http://stackoverflow.com/q/49864945
tag name: regex
tags question: http://stackoverflow.com/q/49761794
tags question: http://stackoverflow.com/q/49808835
tags question: http://stackoverflow.com/q/49861405
tags question: http://stackoverflow.com/q/49799931
tags question: http://stackoverflow.com/q/49795346
tags question: http://stackoverflow.com/q/49882253
tags question: http://stackoverflow.com/q/49857566
tags question: http://stackoverflow.com/q/49888234
tags question: http://stackoverflow.com/q/49816143
tags question: http://stackoverflow.com/q/49828707
tags question: http://stackoverflow.com/q/49762904
tags question: http://stackoverflow.com/q/49861315
tags question: http://stackoverflow.com/q/49820185
tags question: http://stackoverflow.com/q/49857457
tags question: http://stackoverflow.com/q/49869041
tags question: http://stackoverflow.com/q/49766186
tags question: http://stackoverflow.com/q/49829318
tags question: http://stackoverflow.com/q/49814983
tags question: http://stackoverflow.com/q/49902729
tags question: http://stackoverflow.com/q/49840499
tags question: http://stackoverflow.com/q/49815749
tags question: http://stackoverflow.com/q/49905056
tags question: http://stackoverflow.com/q/49769297
tags question: http://stackoverflow.com/q/49841241
tags question: http://stackoverflow.com/q/49772415
tags question: http://stackoverflow.com/q/49764402
tags question: http://stackoverflow.com/q/49814422
tags question: http://stackoverflow.com/q/49862143
tags question: http://stackoverflow.com/q/49890337
tags question: http://stackoverflow.com/q/49785391
tags question: http://stackoverflow.com/q/49809512
tags question: http://stackoverflow.com/q/49908284
tags question: http://stackoverflow.com/q/49825049
tags question: http://stackoverflow.com/q/49843438
tags question: http://stackoverflow.com/q/49900312
tags question: http://stackoverflow.com/q/49892621
tags question: http://stackoverflow.com/q/49851349
tags question: http://stackoverflow.com/q/49780935
tags question: http://stackoverflow.com/q/49772915
tags question: http://stackoverflow.com/q/49849921
tags question: http://stackoverflow.com/q/49900145
tags question: http://stackoverflow.com/q/49820904
tags question: http://stackoverflow.com/q/49813447
tags question: http://stackoverflow.com/q/49877295
tags question: http://stackoverflow.com/q/49827808
tags question: http://stackoverflow.com/q/49784795
tags question: http://stackoverflow.com/q/49909846
tags question: http://stackoverflow.com/q/49809057
tags question: http://stackoverflow.com/q/49779932
tags question: http://stackoverflow.com/q/49833484
tags question: http://stackoverflow.com/q/49804996
tags question: http://stackoverflow.com/q/49849936
tags question: http://stackoverflow.com/q/49856172
tags question: http://stackoverflow.com/q/49866905
tags question: http://stackoverflow.com/q/49910419
tags question: http://stackoverflow.com/q/49798491
tags question: http://stackoverflow.com/q/49915974
tags question: http://stackoverflow.com/q/49887702
tags question: http://stackoverflow.com/q/49783387
tags question: http://stackoverflow.com/q/49866458
tags question: http://stackoverflow.com/q/49808801

http://stackoverflow.com/q/49819399
has title: Running bash script within python and wait for shell command to complete
upvote count: 1
has comment: http://stackoverflow.com/comment/86653841
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86653884
has comment: http://stackoverflow.com/comment/86654935
has answer: http://stackoverflow.com/a/49819599
type: Question
has comment: http://stackoverflow.com/comment/86654141
tagged with: windows
has comment: http://stackoverflow.com/comment/86653751
has comment: http://stackoverflow.com/comment/86654119
has comment: http://stackoverflow.com/comment/86654827
has comment: http://stackoverflow.com/comment/86654203
tagged with: cygwin
tagged with: wait
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86654417
has body: I have the same question as here with python 3.x. I tried the solution provided but it does not work for me. Python does not wait bash script to finish and prints "end" before bash script to be terminated. I am on windows and have cygwin isntalled. callBash.py: import subprocess print("start") subprocess.call("sleep.sh",shell=True) print("end") sleep.sh: #!/bin/bash sleep 10
has comment: http://stackoverflow.com/comment/86653849
tagged with: bash
score: 0
linked to: http://stackoverflow.com/q/13745648
has comment: http://stackoverflow.com/comment/86654169

http://stackoverflow.com/q/49909438
has comment: http://stackoverflow.com/comment/86834879
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86835040
has body: I'm trying to write a loop that pulls people's Twitter followers. Because Twitter only returns 5K followers at a time, this loop should repeat for each user until it gets all the followers. And because sometimes Twitter returns errors randomly, it should also re-try a few times in case of failure. Here's my current attempt, which produces an infinite loop, and I don't know how to fix it. I'm pretty sure there's a simpler way to write it, I just don't know what it is. from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream t = Twitter(auth=OAuth(access_token_key, access_token_secret, consumer_key, consumer_secret)) next_cursor=-1 while next_cursor!=0: for _ in range(5): count=1 try: twitter_pull=t.followers.ids(user_id=some_id,cursor=next_cursor) followers_list=twitter_pull['ids'] next_cursor=twitter_pull['next_cursor'] if next_cursor!=0: time.sleep(60) break except Exception: print("Something went wrong: ", Exception) count=count+1 if count&gt;=5: break time.sleep(120) I know there are a bunch of questions on nested loops, but after reading the answers to them, I could not figure out how to solve my problem.
type: UnansweredQuestion
has title: Writing nested loops in Python correctly
has answer: http://stackoverflow.com/a/49909557
score: 0
has comment: http://stackoverflow.com/comment/86834906
answer count: 1
tagged with: python

http://stackoverflow.com/q/49873433
has body: How does post call work with LOcustIO? I was suspecting Locust not doing what it is suppose to do because it was returning success for all load testing I was running so I decided to post, write to the DB via a web application using LocustIO, to my surprise nothing was written to the db. Though I know some have successfully done this, so I want to know how to write to the Db using LocustIO as part of my load testing. This is the code used: from locust import HttpLocust, TaskSet, task import logging, sys from credentials import * class LoginWithUniqueUsersSteps(TaskSet): institutionCode = "NOT_FOUND" username = "NOT_FOUND" password = "NOT_FOUND" def on_start(self): if len(USER_CREDENTIALS) &gt; 0: self.institutionCode, self.username, self.password = USER_CREDENTIALS.pop() @task def login(self): self.client.post("/dejavuweb/", { 'institutionCode': self.institutionCode, 'email': self.username, 'password': self.password }) logging.info('Login with %s institutionCode %s username and %s password', self.institutionCode, self.username, self.password) @task def createTerminal(self): response = self.client.request(method="POST", url="/dejavuweb/Home#Function/7", data= {"TerminalName": "RealterminalName"}) print("Create; Response status code:", response.status_code) print("Create; Response content:", response.content) class LoginWithUniqueUsersTest(HttpLocust): task_set = LoginWithUniqueUsersSteps host = "http://dev.trublend.cloud" sock = None def __init__(self): super(LoginWithUniqueUsersTest, self).__init__() Mind you, I copied, edited the code snippet above to achieve what I want. Screenshot of LocustIO result:
tagged with: locust
has comment: http://stackoverflow.com/comment/87448880
has comment: http://stackoverflow.com/comment/91773596
type: Question
score: 0
has title: LocustIO test result for post calls
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86927891
tagged with: http-post

http://stackoverflow.com/a/49830212
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49811482
accepted answer of: http://stackoverflow.com/q/49811482
has comment: http://stackoverflow.com/comment/87071141
type: Answer
has comment: http://stackoverflow.com/comment/86815847
has body: You need to be a tenant administrator in order to consent application only access (where you only use client id and secret). However, you can use alternative flows such as Resource Owner Credentials Grant and On-Behalf-Of Grant which requires you to have the credentials of a user with relevant permissions. You can also read about those flows in my post: Getting Access Token for Microsoft Graph Using OAuth REST API. Regarding the message with "version 2.0" - it may be caused by a mixup between version 1 and version 2 of the Microsoft OAuth API. Version 1 is only meant for organization users (users which sit inside azure active directory) and version 2 support Microsoft accounts as well. You can read more about the difference between the two versions in here. Make sure you use one of those versions for the entire process (creating the app, assigning and consenting permissions, and requesting an access token). Mixing between the two versions may not work.
has comment: http://stackoverflow.com/comment/86746899

http://stackoverflow.com/comment/86735700
type: Comment
has text: For each day exist `12:00:00` values?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49860184

http://stackoverflow.com/q/49828806
has answer: http://stackoverflow.com/a/49829155
score: 8
upvote count: 8
tagged with: python
tagged with: boto3
has body: Pretty basic but I am not able to download files given s3 path. for eg, I have this s3://name1/name2/file_name.txt import boto3 locations = ['s3://name1/name2/file_name.txt'] s3_client = boto3.client('s3') bucket = 'name1' prefix = 'name2' for file in locations: s3_client.download_file(bucket, 'file_name.txt', 'my_local_folder') I am getting error as botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found This file exists as when I download. using aws cli as s3 path: s3://name1/name2/file_name.txt .
has title: How to download files from s3 given the file path using boto3 in python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/59304348
answer count: 3
has answer: http://stackoverflow.com/a/76388659
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/59304348
downvote count: 0
accepted answer: http://stackoverflow.com/a/49829155
favorite count: 0
type: Question

http://stackoverflow.com/comment/86653584
score: 0
has text: Possible duplicate of [Select rows from a DataFrame based on values in a column in pandas](https://stackoverflow.com/questions/17071871/select-rows-from-a-dataframe-based-on-values-in-a-column-in-pandas). The accepted answer has an `isin()` solution/example which is relevant to this question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49809354

http://stackoverflow.com/a/49812919
answers question: http://stackoverflow.com/q/49809032
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86744817
has comment: http://stackoverflow.com/comment/86744217
score: 2
accepted answer of: http://stackoverflow.com/q/49809032
has comment: http://stackoverflow.com/comment/86663277
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86663420
has body: If your batch size is too large, with your code the values of (max_indices == labels).sum() (max_indices != labels).sum() do not add up to the batch size. This is due to the fact, that you use a torch.ByteTensor which will overflow for values > 255 when summing. using (max_indices != labels).int().sum() will resolve the issue by casting the Tensor to int before summing.
has comment: http://stackoverflow.com/comment/86744239
upvote count: 2
has comment: http://stackoverflow.com/comment/86744768

http://stackoverflow.com/comment/86764719
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49874228
has text: read my answer again. Does it say "top of function" or "top of script"?

http://stackoverflow.com/a/49894542
accepted answer of: http://stackoverflow.com/q/49893793
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49893793
score: 1
type: Answer
has body: Yes, this is possible, but never ever do that. This is bad practice and if you start thinking about doing something like that, you are doing it wrong. Anyway, this line would do it: import inspect inspect.getouterframes(inspect.currentframe())[1].frame.f_locals["self"].value

http://stackoverflow.com/a/72543893
type: Answer
answers question: http://stackoverflow.com/q/49862318
score: 3
upvote count: 3
has body: In case you want to check all files, including not annotated functions, you have to specify --check-untyped-defs option. Normally, mypy only checks type-annotated functions (functions which arguments or return type are type-annotated). So if you have functions like those, mypy . only shows errors in foo(). # main.py def foo() -> None: print(1 + "a") # show error def bar(): print(1 + "a") # **DON'T** show error $ mypy . main.py:6: error: Unsupported operand types for + ("int" and "str") Found 1 error in 1 file (checked 1 source file) But if you specify --check-untyped-defs, mypy shows all errors even if the functions are not annotated. $ mypy --check-untyped-defs . main.py:2: error: Unsupported operand types for + ("int" and "str") main.py:6: error: Unsupported operand types for + ("int" and "str") Found 2 errors in 1 file (checked 1 source file) Official documentation: https://mypy.readthedocs.io/en/stable/common_issues.html#no-errors-reported-for-obviously-wrong-code
downvote count: 0

http://stackoverflow.com/q/49874349
tagged with: operating-system
tagged with: python
score: -1
has body: I'm trying to delete the contents of a text file till I find a specific string. This was one of the ways I thought was possible. My doubt is, when you move the pointer to the specific position, what happens to the rest of the data before the pointer? Is it deleted or does it still remain in the memory?
tagged with: python-3.x
has title: Using seek() in Python to delete contents of a text file
tagged with: seek
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/11696472
downvote count: 2
answer count: 1
tagged with: systems-programming
upvote count: 1
has comment: http://stackoverflow.com/comment/86764181
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49874445

http://stackoverflow.com/comment/86663111
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49823531
has text: where to extract and how to import after downloading?
type: Comment

http://stackoverflow.com/q/49848573
duplicate of: http://stackoverflow.com/q/17394882
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86711934
has comment: http://stackoverflow.com/comment/86711917
has comment: http://stackoverflow.com/comment/86711896
has comment: http://stackoverflow.com/comment/86711924
type: Question
has body: I have an array correctClassifierLabels with [ 1. 1. -1. -1.] and I need to turn it into [[ 1.] [ 1.][ 1.][ 1.]] I have tried correctClassifierLabels = correctClassifierLabels[:,0:1] and zip(*correctClassifierLabels) and transpose(correctClassifierLabels) and none of them worked for me
linked to: http://stackoverflow.com/q/38604805
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17394882
tagged with: transpose
tagged with: python
has title: Transpose 1 dimensional array in python?
duplicate of: http://stackoverflow.com/q/38604805

http://stackoverflow.com/q/49775621
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has title: How to add a rows to an empty matrix using a loop in python?
favorite count: 0
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49775665
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49775665
has body: My try : matrix=[[]] if my conidtion is filled: matrix+=([[val1],[val2],[val3]]) print matrix where val1, val2, and val3 change with each iteration of my if loop.

http://stackoverflow.com/q/49784513
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: corpus
has comment: http://stackoverflow.com/comment/86615983
favorite count: 0
score: 2
tagged with: tokenize
linked to: http://stackoverflow.com/q/33229360
has comment: http://stackoverflow.com/comment/86585189
has comment: http://stackoverflow.com/comment/86605135
tagged with: python
has comment: http://stackoverflow.com/comment/86598676
tagged with: gensim
has body: I looked for all suggestion, where everyone says to break the string into tokens by split function. All that has been done already, but still it seems to have same error again and again. for r in words: if not r in stop_words: processed_txt+=str(str(ps.stem(r) + " ")) tokenizer = RegexpTokenizer(r'\w+') tokens = tokenizer.tokenize(processed_txt) #print(tokens) dictionary = corpora.Dictionary(tokens) #corpus = [dictionary.doc2bow(text) for text in tokens] print(dictionary) So now it gives below error. raise TypeError("doc2bow expects an array of unicode tokens on input, not a single string") TypeError: doc2bow expects an array of unicode tokens on input, not a single string and the output under "tokens" variable seems like this as below. ['becom', 'effect', 'willingli', 'without', 'need', 'obtain', 'knowledg', 'other', 'obtain', 'acquir', 'must', 'testamentari','claim', 'ownership', 'task', 'establish', 'endow', 'recept', 'willing', 'willsend', 'anoth', 'given', 'efficaci', 'presuppos'] Please help.
has title: TypeError: doc2bow expects an array of unicode tokens on input, not a single string
duplicate of: http://stackoverflow.com/q/33229360
type: Question

http://stackoverflow.com/q/49841971
has title: Can’t get darkflow to process screenshots in realtime
has comment: http://stackoverflow.com/comment/86802556
answer count: 1
has answer: http://stackoverflow.com/a/49893001
upvote count: 1
downvote count: 1
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/86757178
type: Question
has body: I tried to create a simple program which captures screenshots (using mss) and gets tensorflow to predict/detect elements in the images, but it's not working. Here's part of the code: import cv2 import mss import numpy as np from PIL import Image #Import TFNet from darkflow.net.build import TFNet import matplotlib.pyplot as plt #Specify the dictonary. options = { 'model':'cfg/yolo.cfg', 'load':'bin/yolov2.weights', 'threshold': 0.3 } tfnet = TFNet(options) #Creates an endless loop for high-speed image acquisition... while (True): with mss.mss() as sct: #Get raw pixels from the screen sct_img = sct.grab(sct.monitors[1]) #Convert image to a numpy array img = np.array(sct_img) result = tfnet.return_predict(img) print(result) Could someone tell me where I'm going wrong? It returns the following error every time: ValueError: Cannot feed value of shape (1, 608, 608, 4) for Tensor 'input:0', which has shape '(?, 608, 608, 3)' Please give code examples. Thanks in advance.
accepted answer: http://stackoverflow.com/a/49893001
tagged with: python
has comment: http://stackoverflow.com/comment/86714420
tagged with: python-mss
has comment: http://stackoverflow.com/comment/86714848
tagged with: opencv
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49775405
has comment: http://stackoverflow.com/comment/86565775
answer count: 1
tagged with: set
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
has title: Replacement in a list with assigning a weight
tagged with: python-3.x
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49775845
has answer: http://stackoverflow.com/a/49775845
has comment: http://stackoverflow.com/comment/86565976
tagged with: python
has body: My question has two parts: First, suppose we have a list of elements: l=['x1','x2','x3','x4'] How do you assign a weight to each element? for example, in the beginning, all elements have weight one. My second part of the question is to take two elements in random mix them and make a new element. So the new list would be: l=['x1','x2','x3','x4','x5'] where 'x5' now has weight two as: 'x5'= 'x1'+'x3' for example. What I have so far is def randMerge(l:list, count:int) -&gt; list: return l + [random.sample(l,k=count)] def flatten(d): return [i for b in [[c] if not isinstance(c, list) else flatten(c) for c in d] for i in b] num = 2 aList = ['x1','x2','x3','x4'] res = [] newList = aList[:] for _ in range(3): newList = randMerge(newList,num) print(newList) which has a output as: #['x1', 'x2', 'x3', 'x4', ['x2', 'x3']] #['x1', 'x2', 'x3', 'x4', ['x2', 'x3'], ['x2', 'x4']] #['x1', 'x2', 'x3', 'x4', ['x2', 'x3'], ['x2', 'x4'], ['x3', 'x1']] As you can see a new sublist is added at each step, how can I replace them with a new name and new appropriate weight?
type: Question
tagged with: numpy
tagged with: list
has comment: http://stackoverflow.com/comment/86565774

http://stackoverflow.com/a/49798145
upvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49797743
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49797743
has body: PhotoImage reads the image data from file and stores it in memory as a pixel buffer. The reference of this buffer has to be persistent as long as the application runs (or at least, as long the Label widget showing the image exists). If you put the result of PhotoImage in a local variable (e.g. img, as in the second code), the garbage collector is likely to destroy the data referenced by this local variable. On the other hand, if you store the reference of your pixel buffer in an attribute (e.g. self.img, as in the first code) the garbage collector will not destroy your data as long as self exists, which means as long as the application runs... If your GUI uses many images, a usual practice is to create an attribute self.images that puts all required images either in a tuple or a dictionary (whether you prefer indexing them by numbers or by strings), that ensures that all images will be kept in memory.
downvote count: 0

http://stackoverflow.com/comment/86768955
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49876640
has text: Updated the ans. use `'\r'`

http://stackoverflow.com/q/49912743
upvote count: 1
score: -1
tagged with: loops
has title: Python access and sum dictionary values in list
type: Question
has answer: http://stackoverflow.com/a/49912765
has comment: http://stackoverflow.com/comment/86841111
has body: I would like to know how can I access list values in a dictionary to sum them: {'key1': [3, 1], 'key2': [0, 4], 'key3': [57492, 204652], 'key4': [1,3]} I would like to sum the first element of each list sum(3,0,57492,1). Is it possible to do so without any loop ? Thank you in advance
answer count: 1
tagged with: python
tagged with: dictionary
favorite count: 0
linked to: http://stackoverflow.com/q/20639180
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49912765
has comment: http://stackoverflow.com/comment/86841287
tagged with: list
downvote count: 2
has comment: http://stackoverflow.com/comment/86841269
linked to: http://stackoverflow.com/q/3294889

http://stackoverflow.com/q/49787551
tagged with: pybluez
answer count: 1
upvote count: 1
has title: Pycharm is not showing installed packages : PyBluez
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: package
has answer: http://stackoverflow.com/a/49787596
tagged with: pip
tagged with: python
downvote count: 1
score: 0
tagged with: pycharm
has body: I have installed pybluez (a python package) using pip install pybluez, but pybluez is not listed in my package list. My python version is python2.7 and I installed pycharm-2018.1.1 on my PC running Ubuntu 16.04. I can see pybluez is installed using pip list I have also installed pybluez in pycharm and it shows that pybluez is successfully installed. However pybluez is still not listed in the pycharm packages list. This is the error I see when running the program from pycharm.

http://stackoverflow.com/a/49868308
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86752202
answers question: http://stackoverflow.com/q/49868283
accepted answer of: http://stackoverflow.com/q/49868283
has comment: http://stackoverflow.com/comment/86752299
has body: itertools.zip_longest does the trick! result = itertools.zip_longest(*Final_List, fillvalue='\t') # result is a generator result = ['\t'.join(r) for r in result]
type: AcceptedAnswer
score: 10
upvote count: 10

http://stackoverflow.com/comment/86783124
has text: you can try: `hash(df1[:-1].values.tostring())` to remove the last column.
type: QuestionComment
comment on: http://stackoverflow.com/q/49883236
type: Comment
score: 1

http://stackoverflow.com/a/49787307
answers question: http://stackoverflow.com/q/49787177
downvote count: 0
score: 1
upvote count: 1
has body: you should try checking tkinter's documentation on pack: check if this is what you are looking for: root = Tk() root.geometry("250x50") w = Label(root, text="Label UNO", bg="red", fg="white") w.pack(side=LEFT, fill=BOTH, expand=True) w = Label(root, text="Label2", bg="green", fg="black") w.pack(side=LEFT, fill=BOTH, expand=True) w = Label(root, text="Label DREI", bg="blue", fg="white") w.pack(side=LEFT, fill=BOTH, expand=True) root.mainloop() Fill argument basically fills the parent container. Expand argument will use to additional remaining space. Also be sure to take a look at tkinter weight, here is an example.
type: Answer

http://stackoverflow.com/comment/86574999
comment on: http://stackoverflow.com/q/49779738
score: 1
type: Comment
type: QuestionComment
has text: You might find `django-debug-toolbar` useful for debugging problems like this. It makes it easy to see the template context.

http://stackoverflow.com/comment/86738235
score: 0
type: Comment
has text: Yes, its working with that solution. But i have to add "paragraph.alignment = 0 " after adding every single paragraph. So i was trying to find a better solution to reduce line of codes.
type: QuestionComment
comment on: http://stackoverflow.com/q/49861312

http://stackoverflow.com/q/49765956
has comment: http://stackoverflow.com/comment/86619132
has body: As title said, I am working on downloading file in Thai government website. I tried to go back to the old page, delete the old code (hscode) which I had already downloaded and refilled with another one. However, I stuck with sending a `.send_keys(Keys.BACKSPACE)'. I already tried both implicit and explicit wait, but it did not work in my case. Also, I have tried to research on this with the conclusion that "the element is no longer in the DOM or it changed" but no solution was attached. Any ideas or solutions to send that Backsplace key would be very appreciated. Thanks. What I have tried so far is per below code: from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.common.keys import Keys kobs =["8507", "6910"] for kob in kobs: ChromeOptions = webdriver.ChromeOptions() prefs = {"download.default_directory":"C:/Users/Kob/Desktop/Testnaja"} ChromeOptions.add_experimental_option("prefs", prefs) ChromePath = "C:/Users/Kob/Desktop/Python projects/Chrome webdriver/Chromedriver.exe" driver = webdriver.Chrome(executable_path=ChromePath, chrome_options=ChromeOptions) driver.get("http://www2.ops3.moc.go.th/") main_window = driver.window_handles[0] new_window1 = driver.window_handles[1] new_window2 = driver.window_handles[2] Export = driver.find_element_by_link_text("EXPORT") Export.click() driver.switch_to.window(new_window1) driver.close() driver.switch_to.window(new_window2) driver.close() driver.switch_to.window(main_window) driver.switch_to.frame("data") driver.implicitly_wait(5) Commodity = driver.find_element_by_link_text("Commodity") Commodity.click() Year = Select(driver.find_element_by_name("q_Year")); Month = Select(driver.find_element_by_name("q_Month")); Currency = Select(driver.find_element_by_name("q_currency")); Year.select_by_index("0") Month.select_by_index("1") Currency.select_by_index("1") hscode = driver.find_element_by_name("q_hsList") hscode.send_keys(kob) driver.execute_script("doReport()") new_window3…
has title: Python could not send Backspace keys (EDIT)
type: AnsweredQuestion
tagged with: sendkeys
score: 0
has comment: http://stackoverflow.com/comment/86558747
answer count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/49789428
linked to: http://stackoverflow.com/q/44838538
has comment: http://stackoverflow.com/comment/86621872
type: Question
has comment: http://stackoverflow.com/comment/86549121
accepted answer: http://stackoverflow.com/a/49789428
has comment: http://stackoverflow.com/comment/86554395
has comment: http://stackoverflow.com/comment/86621907
tagged with: python
tagged with: chrome-web-driver
has comment: http://stackoverflow.com/comment/86550423

http://stackoverflow.com/q/49767904
tagged with: python-3.x
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/86551010
has comment: http://stackoverflow.com/comment/86551089
tagged with: python
has title: How to calculate summation of different columns value with python
has comment: http://stackoverflow.com/comment/86551382
answer count: 3
has comment: http://stackoverflow.com/comment/86551031
has answer: http://stackoverflow.com/a/49769059
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/49768284
has answer: http://stackoverflow.com/a/49768130
has body: I am working with a dataset with thousands of records. I need to calculate the sum of values for each day and save it to a separate column based on two conditional statement of col3 and col4. The loop count for each day has been stored in col2. condition 1: if col3&lt; col4 take col4 value for summation. condition 2: if col3 &gt;= col4 take col3 value for summation. Test Dataset: id col2 col3 col4 timestamp 0 3 0 50 1-12-2018 1 3 40 35 1-12-2018 2 3 30 30 1-12-2018 3 2 23 14 2-12-2018 4 2 33 33 2-12-2018 5 1 25 50 3-12-2018 Now I need to find the summation as per the above conditions and calculate probability from it. The Desired output is : id col2 col3 col4 timestamp sum P 0 3 0 50 1-12-2018 120 50/120 1 3 40 35 1-12-2018 120 40/120 2 3 30 30 1-12-2018 120 30/120 3 2 23 44 2-12-2018 77 23/77 4 2 33 33 2-12-2018 77 33/77 5 1 25 50 3-12-2018 50 50/50 So far with python I have done this, which only takes summation of either col3 or col4. But, I am confused how to calculate the summation based on the conditions I mentioned above and also calculate the probability to produce desired output: import csv fin = open("tx.in.txt","r") list_id = {} for line in fin: line = line.rstrip() f = line.split() if('value' not in f): try: list_id[f[4]]+=int(f[2]) except: list_id[f[4]]=int(f[2]) fin.close() for k,v in list_txid.items(): print("{0}\t{1:d}".format(k, v)) P.S : I can't install/use pandas library for limited access to the server. Thanks in advance.
favorite count: 0
has comment: http://stackoverflow.com/comment/86551166
type: Question

directed-graph
tags question: http://stackoverflow.com/q/49821907
type: Tag
tag name: directed-graph

waveform
tag name: waveform
type: Tag
tags question: http://stackoverflow.com/q/49778904

http://stackoverflow.com/q/49887874
score: 52
has answer: http://stackoverflow.com/a/75344033
tagged with: python
has comment: http://stackoverflow.com/comment/122748231
has comment: http://stackoverflow.com/comment/86798013
has title: Pygame Xbox One Controller
has comment: http://stackoverflow.com/comment/119074583
has answer: http://stackoverflow.com/a/73988419
linked to: http://stackoverflow.com/q/28132156
has comment: http://stackoverflow.com/comment/119324056
has body: I am trying to run some code that will allow the user to control with an Xbox Controller. I have it working with the Xbox 360 controller using Pygame. Then when I try to use the Xbox one controller and it is able to read the as "connected" but it doesn't read the actual button presses. I tried running the joystick analyzer found on the Pygame website and it shows it connected again but no button input is taken. The code for this can be found at the bottom of this documentation page: https://www.pygame.org/docs/ref/joystick.html import pygame # Define some colors. BLACK = pygame.Color('black') WHITE = pygame.Color('white') # This is a simple class that will help us print to the screen. # It has nothing to do with the joysticks, just outputting the # information. class TextPrint(object): def __init__(self): self.reset() self.font = pygame.font.Font(None, 20) def tprint(self, screen, textString): textBitmap = self.font.render(textString, True, BLACK) screen.blit(textBitmap, (self.x, self.y)) self.y += self.line_height def reset(self): self.x = 10 self.y = 10 self.line_height = 15 def indent(self): self.x += 10 def unindent(self): self.x -= 10 pygame.init() # Set the width and height of the screen (width, height). screen = pygame.display.set_mode((500, 700)) pygame.display.set_caption("My Game") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates. clock = pygame.time.Clock() # Initialize the joysticks. pygame.joystick.init() # Get ready to print. textPrint = TextPrint() # -------- Main Program Loop ----------- while not done: # # EVENT PROCESSING STEP # # Possible joystick actions: JOYAXISMOTION, JOYBALLMOTION, JOYBUTTONDOWN, # JOYBUTTONUP, JOYHATMOTION for event in pygame.event.get(): # User did something. if event.type == pygame.QUIT: # If user clicked close. done = True # Flag that we are done so we exit this loop. elif event.type == pygame.JOYBUTTONDOWN: print("Joystick button pressed.") elif event.type == pygame.…
has comment: http://stackoverflow.com/comment/129772147
has comment: http://stackoverflow.com/comment/86825229
answer count: 3
has answer: http://stackoverflow.com/a/73980330
has comment: http://stackoverflow.com/comment/129770921
tagged with: pygame
has comment: http://stackoverflow.com/comment/127564876
linked to: http://stackoverflow.com/q/46506850
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89603317
has comment: http://stackoverflow.com/comment/86840753
has comment: http://stackoverflow.com/comment/110217395
has comment: http://stackoverflow.com/comment/124589653
tagged with: gamecontroller
upvote count: 53
type: UnansweredQuestion

http://stackoverflow.com/q/49858421
has title: Serve React production App (local server) through Flask-Python
tagged with: node.js
score: 8
tagged with: reactjs
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49860855
possible better answer: http://stackoverflow.com/a/49862002
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/49862002
type: Question
type: AnsweredQuestion
upvote count: 8
accepted answer: http://stackoverflow.com/a/49860855
tagged with: production-environment
has body: I'm producing an application with these two technologies: React-app &amp; Flask-Python. Its intended to run a react client to represent data received from Flask-server. The flask server and react client are on the same machine and communicate trough sockets (SocketIO). In Dev mode, in order to run the application, I have to run the react server with npm start (node) and the flask server with python. In production mode, after the react server is built, I have to serve the build folder with the serve option available on Node. Otherwise the app will not work properly (I think its because I use react-router, and when I go to another place of my react app, the browser cannot find the URL's specified. When serving the build folder with serve option of Node, no problem shows up). So, my question is: Can I serve the build folder of my react application with flask instead of serve option of node? I want to do this, in order to eliminate the Node.js dependency so if I want to run my application on another machine, I will not have to install node.
tagged with: python

http://stackoverflow.com/comment/86640543
has text: This is an excellent way to do it - the work has been done for you, if probably a bit heavyweight to include if you aren't using pandas for anything else
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49813028
type: Comment

http://stackoverflow.com/comment/136872669
type: Comment
comment on: http://stackoverflow.com/a/73805291
type: AnswerComment
has text: I like to append the `DataFrame` into a list and then concat them all at once for large lists as indicated by Zeugma. It would avoid the low_memory issue.
score: 0

http://stackoverflow.com/comment/86775625
score: 0
comment on: http://stackoverflow.com/q/49866788
has text: @BryanOakley Hum. well I worked on the problem for hours and tried many different things. But I guess its fine. It ended up being a silly mistake that I should have noticed anyway.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49764594
type: Question
has comment: http://stackoverflow.com/comment/86546257
type: UnansweredQuestion
has title: Any way to batch load the data in SQLAlchemy's relationships?
has comment: http://stackoverflow.com/comment/86559875
tagged with: python
linked to: http://stackoverflow.com/q/34886407
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86683504
has body: So, using SQLAlchemy's Many-To-Many example (with 1 extra table), class ExternalString(Base): id = Column(Integer, primary_key=True) string = Column(String(50)) def __repr__(self): return self.string association_table = Table( 'association', Base.metadata, Column('left_id', Integer, ForeignKey('left.id')), Column('right_id', Integer, ForeignKey('right.id')) ) class Parent(Base): __tablename__ = 'left' id = Column(Integer, primary_key=True) name_id = Column(Integer, ForeignKey(ExternalString.id)) name = relationship(ExternalString) children = relationship("Child", secondary=association_table) class Child(Base): __tablename__ = 'right' id = Column(Integer, primary_key=True) name_id = Column(Integer, ForeignKey(ExternalString.id)) name = relationship(ExternalString) If you do something like below, for p in Parent.query.all(): print(p.name) for child in p.children: print(child.name) I'm ok with the query.all() SQL call to the Parent table, but every time you print out a parent or child name, that's another SQL call to the ExternalString table, and then there's another SQL call when you access any parent rows children. Debug output below, INFO:sqlalchemy.engine.base.Engine:SELECT `right`.id AS right_id, `right`.name_id AS right_name_id FROM `right`, association WHERE %s = association.left_id AND `right`.id = association.right_id INFO:sqlalchemy.engine.base.Engine:SELECT external_strings.id AS external_strings_id, external_strings.string AS external_strings_string FROM external_strings WHERE external_strings.id = %s What I'm asking, after I've got all the parent rows, is there any way I can instruct SQLAlchemy to do a batch operation for getting all the parent's children? The internal operation is doing a fairly straightforward call to get the children, and what I'd like to instruct SQLAlchemy to do is populate all the parent rows children in 1 SQL call, rather than 1 call per parent. After that point (I understand this might be a little too much to ask for for a Many-To-…
tagged with: sqlalchemy
favorite count: 0

http://stackoverflow.com/q/49906034
upvote count: 2
score: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86834497
favorite count: 0
type: Question
has title: Python Asyncio run_forever() and Tasks
tagged with: python-asyncio
tagged with: python
accepted answer: http://stackoverflow.com/a/49912853
has answer: http://stackoverflow.com/a/49912853
has body: I adapted this code for using Google Cloud PubSub in Async Python: https://github.com/cloudfind/google-pubsub-asyncio import asyncio import datetime import functools import os from google.cloud import pubsub from google.gax.errors import RetryError from grpc import StatusCode async def message_producer(): """ Publish messages which consist of the current datetime """ while True: await asyncio.sleep(0.1) async def proc_message(message): await asyncio.sleep(0.1) print(message) message.ack() def main(): """ Main program """ loop = asyncio.get_event_loop() topic = "projects/{project_id}/topics/{topic}".format( project_id=PROJECT, topic=TOPIC) subscription_name = "projects/{project_id}/subscriptions/{subscription}".format( project_id=PROJECT, subscription=SUBSCRIPTION) subscription = make_subscription( topic, subscription_name) def create_proc_message_task(message): """ Callback handler for the subscription; schedule a task on the event loop """ print("Task created!") task = loop.create_task(proc_message(message)) subscription.open(create_proc_message_task) # Produce some messages to consume loop.create_task(message_producer()) print("Subscribed, let's do this!") loop.run_forever() def make_subscription(topic, subscription_name): """ Make a publisher and subscriber client, and create the necessary resources """ subscriber = pubsub.SubscriberClient() try: subscriber.create_subscription(subscription_name, topic) except: pass subscription = subscriber.subscribe(subscription_name) return subscription if __name__ == "__main__": main() I basically removed the publishing code and only use the subscription code. However, initially I did not include the loop.create_task(message_producer()) line. I figured that tasks were created as they were supposed to however they never actually run themselves. Only if I add said line the code properly executes and all created Tasks run. What causes this behaviour?
has comment: http://stackoverflow.com/comment/86833006
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86841303
tagged with: google-cloud-platform

http://stackoverflow.com/comment/86722238
type: Comment
score: 0
type: AnswerComment
has text: Thank you very much, that solved it! One question: now that I've saved this model (via checkpoint), how can I deploy/load/use it to make predictions with single image files?
comment on: http://stackoverflow.com/a/49844549

http://stackoverflow.com/comment/86545647
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49765019
has text: I get True, True, False, False on py3
type: Comment

http://stackoverflow.com/q/49800487
has answer: http://stackoverflow.com/a/49800632
favorite count: 0
type: Question
has body: Hi guys I don't know why but pandas really can't manage to load my csv file in my python code. The file is in the same folder of my python project, I'm working with tensorflow, theano, pandas, numpy and matplotlib libraries. It's been 2 hrs and I tried uninstalling everything and reinstalling once again using the pip3 commands. I uninstalled tensorflow, pandas, theano, numpy, and even python2 and python3. Nothing. I also updated and upgraded my linux distro. useless. this is the error I keep getting when I execute the part of my code in the Spyder3 internal terminal: dataset = pd.read_csv('Churn_Modelling.csv') Traceback (most recent call last): File "&lt;ipython-input-4-610b2f33ea04&gt;", line 1, in &lt;module&gt; dataset = pd.read_csv('Churn_Modelling.csv') File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 709, in parser_f return _read(filepath_or_buffer, kwds) File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 449, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 818, in __init__ self._make_engine(self.engine) File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 1049, in _make_engine self._engine = CParserWrapper(self.f, **self.options) File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 1695, in __init__ self._reader = parsers.TextReader(src, **kwds) File "pandas/_libs/parsers.pyx", line 402, in pandas._libs.parsers.TextReader.__cinit__ File "pandas/_libs/parsers.pyx", line 718, in pandas._libs.parsers.TextReader._setup_parser_source FileNotFoundError: File b'Churn_Modelling.csv' does not exist And this is the freaking line of code: dataset = pd.read_csv('Churn_Modelling.csv') What is wrong with it guys?? I also tried to rename it.
has comment: http://stackoverflow.com/comment/86615992
tagged with: python-3.x
has title: can't load csv file in python3 with pandas
score: -2
has comment: http://stackoverflow.com/comment/86615807
tagged with: dataset
tagged with: python
accepted answer: http://stackoverflow.com/a/49800632
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/86615922
downvote count: 2
has comment: http://stackoverflow.com/comment/86616593
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
answer count: 1

http://stackoverflow.com/q/49897889
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49897980
answer count: 4
has answer: http://stackoverflow.com/a/49898116
score: 0
has answer: http://stackoverflow.com/a/49898011
has body: I'm trying to scrape the rating of yelp restaurants, with no luck. I'm using beautiful soup to do so Basically, the source code looks like this: &lt;div class="i-stars i-stars--regular-5 rating-large" title="5.0 star rating"&gt; &lt;img class="offscreen" height="303" src="https://s3-media2.fl.yelpcdn.com/assets/srv0/yelp_design_web/9b34e39ccbeb/assets/img/stars/stars.png" width="84" alt="5.0 star rating"&gt; &lt;/div&gt; As you can see, the class name changes given the rating, so I'm trying to have somekind of “partial” match with my find function rating = r.find_all('div', {'class':'i-stars i-stars--regular'}).get('title', 'No title attribute') print(rating) But it does not seem to work.
has title: Extracting variable element with beautiful soup
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/49897951
type: Question
tagged with: python

http://stackoverflow.com/comment/86622181
comment on: http://stackoverflow.com/q/49803673
has text: python read it: https://gyazo.com/3d42a56c8cb18941c7cbe7769fa6145b and writes it to data.json: https://gyazo.com/b97a3655fc517cd2b72545479f7f3fee
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49760059
has body: find objects in a custom list that are equal based on custom function This is exactly what groupby was made for t1 = MyClass({"a" : ["X1"] , "b" : [1,2] }) t2 = MyClass({"a" : ["X2"] , "b" : [1,2] }) t3 = MyClass({"a" : ["Y1"] , "b" : [3] }) l = [t1,t3,t2] data = sorted(l, key = lambda t: t.b) for k, g in itertools.groupby(data, lambda t: t.b): print("key =", k) for t in g: print(t) Output: key = [1, 2] {'a': ['X1'], 'b': [1, 2]} {'a': ['X2'], 'b': [1, 2]} key = [3] {'a': ['Y1'], 'b': [3]}
answers question: http://stackoverflow.com/q/49759495
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/86537742

http://stackoverflow.com/comment/86571161
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49777732
has text: @ABDULNIYASPM The way `operator.itemgetter(n)` works is it constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it. So here calling it with argument 1 or 0 will not matter. It will return a tuple containing the maximum of both the columns. Hence note the subscript at the end `[0]` which means to say show max for only first column (and `[1]` in min means to say show min for only second column). So here `operator.itemgetter(0)` and `operator.itemgetter(1)` will work the same

http://stackoverflow.com/comment/86539933
has text: It that related to [this question](https://stackoverflow.com/questions/726471/how-big-can-a-memory-mapped-file-be)?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49762240
score: 0

http://stackoverflow.com/comment/86596025
has text: Your function returns a result. You want to re-use that result in a next function call, the local variables in a function themselves don't hang around.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49790545
score: 0

http://stackoverflow.com/q/49792494
type: AnsweredQuestion
upvote count: 0
has body: I was writing some python code and I found a strange behaviour in my code. This is the code: import sys f=open("test1","wb") test="1000000000" f.write(bytearray(int(test))) f.close() It generates the file test1 with lenght 1000000000 (1,0 GB) filled with 0. Is this supposed to happen(if yes, why?) or is a bug?
has answer: http://stackoverflow.com/a/49792578
accepted answer: http://stackoverflow.com/a/49792578
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49792604
possible better answer: http://stackoverflow.com/a/49792604
has comment: http://stackoverflow.com/comment/86599482
answer count: 2
has comment: http://stackoverflow.com/comment/86599480
has title: Strange python behaviour of f.write()
score: -4
has comment: http://stackoverflow.com/comment/86599519
tagged with: python
downvote count: 4

http://stackoverflow.com/comment/86689684
score: 0
has text: `POpen` does not wait for the command to complete then you sleep 400 seconds, presumably to make up for that. You could `subprocess.check_call(args)` which waits for the command to complete and raises an exception on non-zero return code. The error is coming from the app and there is no way we'd know what that means. It seems strange, though, that you don't pass the full file name (`currentFileName = (os.path.join(root, name))[21:-5]`) or check to see if its really a file you want to process. Add `print(args)` right before the call to `check_call` and run that manually.
comment on: http://stackoverflow.com/q/49837100
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49894338
downvote count: 0
has comment: http://stackoverflow.com/comment/91861918
score: 23
accepted answer of: http://stackoverflow.com/q/49891688
type: Answer
has body: It depends on the amount of javascript present on the page. You must know that to render all the javascript the splash takes some time and the python application proceeds without waiting for the rendering to be complete. So sometimes splash is also not able to do it. You can explicitly put a wait for rendering as it needs some time generally. Also it is a good practice to put up some wait. Here, import scrapy from scrapy_splash import SplashRequest yield scrapy.Request(url, callback=self.parse, meta={'splash':{'args':{'wait':'25'},'endpoint':'render.html'}}) or import scrapy from scrapy_splash import SplashRequest yield SplashRequest(url, self.parse, endpoint='render.html', args={'wait': 5, 'html' : 1 } ) Between scrapy and selenium Selenium is only used to automate web browser interaction, Scrapy is used to download HTML, process data and save it(whole web crawling framework). Talking about scraping I would recommend scrapy and if the problem is javascript. Scrapy already has its own official project for javascript called scrapy-splash Also, you can create new instance of webdriver from Selenium in the scrapy spider, do some work, extract the data, and then close it after all work done.
has comment: http://stackoverflow.com/comment/91842224
upvote count: 23
answers question: http://stackoverflow.com/q/49891688
type: AcceptedAnswer

http://stackoverflow.com/comment/86537449
score: 0
type: Comment
has text: Doesn't this "jump" also occur with classes that have absolutely no relation to each other? At the end you use a distance criteria to transform the continuous output into a discrete classification. The embedding would do the same, but with a more complex criteira.
type: QuestionComment
comment on: http://stackoverflow.com/q/49759946

http://stackoverflow.com/q/49913317
tagged with: python-2.7
score: 0
type: UnansweredQuestion
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/7332299
tagged with: pyinstaller
has title: How to call Verbose Imports?
has body: how to pass a -v (verbose imports) flag to the embedded Python interpreter. Have given in the documentation. I have tried with pyinstaller -v wxpython.py. It was displaying pyinstaller version. I am new to python, I don't know how to find these hidden imports, build the app with the -v flag.
tagged with: python
has answer: http://stackoverflow.com/a/55497249

http://stackoverflow.com/comment/86721422
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49851934
has text: i reduced. it worked but it will filter a lot of documents for me which i don't think will be an optimal solution @Val
score: 0

http://stackoverflow.com/comment/86541363
type: AnswerComment
has text: Wasn't me. +1 for this solution.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49762822

http://stackoverflow.com/comment/86684937
has text: Ivan and shmee... You guys are awesome! I googled a lot trying to find an answer but only got more confused. Your help was perfect and really quick! I'll post my final code in case it helps someone else in the future.
score: 0
comment on: http://stackoverflow.com/a/49820179
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49824410
downvote count: 2
answer count: 1
upvote count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3276489
has answer: http://stackoverflow.com/a/49824437
has title: Isn't the python code below, properly indented?
tagged with: python
duplicate of: http://stackoverflow.com/q/3276489
accepted answer: http://stackoverflow.com/a/49824437
has body: This is a small game I made. Simple rules, the player must determine the number in my mind. I will later import random module though. print('Hello!, What is your name?') userName = input() print(myName + 'Welcome to Guess it! Ralph') print('You must guess the number that I have in my mind(from 1 to 10) within 5 chances') myNumber = 3 print('Give your prediction') for no_of_chances in range(5, 0, -1): usersPrediction = input() I get this error when I run in pycharm: if usersPrediction &lt; myNumber: ^ IndentationError: unexpected indent if usersPrediction &lt; myNumber: print('It is lower than required,try a higher value') elif usersPrediction &gt; myNumber: print('It is higher than required,try a lower value') elif usersPrediction == myNumber: print('yahoo!, you did it') print('You always have a next chance, try it again')
favorite count: 0
score: -1
type: Question
tagged with: indentation

http://stackoverflow.com/comment/86771872
type: Comment
type: QuestionComment
has text: [Here's a similar piece of code I wrote](https://stackoverflow.com/a/47441298/6779307) that has some explanation and slightly simpler structure.
comment on: http://stackoverflow.com/q/49878112
score: 0

http://stackoverflow.com/q/49863862
has title: df.to_csv(fileName, sep='|', header=True, index=False) produces column misalignment due to commas in column value
tagged with: dataframe
tagged with: delimiter
type: Question
tagged with: export-to-csv
has comment: http://stackoverflow.com/comment/86743767
has comment: http://stackoverflow.com/comment/86743370
has body: I'm reading data from a SQL Server table into a dataframe using: df = pd.read_sql(querystring, conn) and then writing the dataframe to a CSV file using: df.to_csv(fileName, sep='|', header=True, index=False) One of the columns in the table is a comments field that may contain commas. This is causing the CSV file that gets created has misaligned columns. I was expecting the sep='|' parameter to df.to_csv to only separate columns, not replace commas within the columns. How can I get around this issue?
answer count: 0
has comment: http://stackoverflow.com/comment/86743375
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86743722
has comment: http://stackoverflow.com/comment/86743667
has comment: http://stackoverflow.com/comment/86743622
tagged with: python
has comment: http://stackoverflow.com/comment/86743222
score: 0
tagged with: pandas

http://stackoverflow.com/q/49867587
tagged with: python
downvote count: 1
favorite count: 0
has body: here's my code from django.db import models Trying to run this command(already imported Album class succesfully)-- newAlbum=Album.objects(name="1",Artist=newArtist).save() I am getting error: TypeError: 'Manager' object is not callable'
score: -1
type: Question
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49868099
has comment: http://stackoverflow.com/comment/87025528
answer count: 1
has title: how to resolve TypeError: 'Manager' object is not callable in django python
tagged with: django

http://stackoverflow.com/q/49912262
tagged with: sendkeys
tagged with: python-2.7
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: selenium
has answer: http://stackoverflow.com/a/49915190
has title: Selenium Key Press not working in Firefox
has body: I'm building a web crawler package and I'm trying to do some key press using selenium. However, I find that keys like Keys.SHIFT or Keys.CONTROL doesn't work at all. But if I manually press them, they will work. I've tried both of lines of codes below, and neither of them worked. ac.key_down(Keys.LEFT_SHIFT).send_keys(Keys.F2).key_up(Keys.LEFT_SHIFT).perform() elem1.send_keys(Keys.SHIFT+Keys.F2) I was trying to open the developer tools in Firefox
has answer: http://stackoverflow.com/a/49912996
has comment: http://stackoverflow.com/comment/86937324
has comment: http://stackoverflow.com/comment/86842618
tagged with: python
type: Question

http://stackoverflow.com/q/49783691
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86709901
has title: Redirecting stdout of a child process
has comment: http://stackoverflow.com/comment/86582885
tagged with: pipe
tagged with: stdout
tagged with: python
tagged with: unix
has body: I am trying to create a program which forks a child process and then monitors its stdout. My understanding is that this should be achievable by creating a set of pipe fds and then setting the write end of the pipe to STDOUT in the child using dup. The code below attempts to do this import os import sys import time pid = os.fork() pr, pw = os.pipe() if pid == 0: #Inside child os.close(pr) os.dup2(pw, sys.stdout.fileno()) print("Inside the child") exit(1) print("Inside parent, waiting for child output..") result = os.read(pr, 1024) print(result) But yields the 'broken pipe' error below. BrokenPipeError: [Errno 32] Broken pipe Exception ignored in: &lt;_io.TextIOWrapper name='&lt;stdout&gt;' mode='w' encoding='UTF-8'&gt; BrokenPipeError: [Errno 32] Broken pipe Traceback (most recent call last): File "/tmp/master.py", line 14, in &lt;module&gt; result = os.read(pr, 1024) I have looked at a few examples but can't seem to figure out what I am doing wrong. The error suggests that the read end of the pipe is prematurely closed but this does not appear to be the case.
has comment: http://stackoverflow.com/comment/86583033
type: Question

http://stackoverflow.com/q/49847548
answer count: 1
downvote count: 1
has title: Average of List Attributes in Python
has answer: http://stackoverflow.com/a/49851897
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86710046
favorite count: 0
type: Question
tagged with: numpy
has body: I have a list of objects, with an attribute (attributions) that I want to average (element-wise) together. What is the best way of doing it? I have the objects (ExplanationObjects) in a list attr, each of which has an attribute attributions that I want to average together, in an element-wise fashion. For instance, if I had: a.attribution=[[2,1],[4,6]] and b.attribution=[[4,3],[8,8]] I would want to get [[3,2],[6,7]] Right now, I'm doing that by using (sum(a.attribution for a in attrs))/len(attrs) Is that the best way of doing it, or is there another method (numpy preferred) that you'd suggest?
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49843822
upvote count: 5
has comment: http://stackoverflow.com/comment/86704426
tagged with: python
score: 4
has body: I have an assignment, building a system on google app engine with python backend(not flask), and Vue.js front end. The system needs to load the vue.js app(some basic hello world app), on google app engine(google cloud SDK). I've built the python &amp; yaml side and loaded it to GAE and also built the vue.js side.. but i'm stuck a long time on how can i connect the parts so the python/yaml will load my app on loading the url.. Please Help, Thanks ahead either way! :)
type: AnsweredQuestion
tagged with: google-cloud-platform
tagged with: yaml
accepted answer: http://stackoverflow.com/a/49844967
answer count: 1
has title: Connecting a python backend and vue.js frontend on Google App Engine
has answer: http://stackoverflow.com/a/49844967
has comment: http://stackoverflow.com/comment/86703091
downvote count: 1
favorite count: 0
type: Question
tagged with: vue.js
tagged with: google-app-engine

http://stackoverflow.com/comment/89417233
type: AnswerComment
comment on: http://stackoverflow.com/a/50419127
type: Comment
has text: Its in the process of being peer reviewed, I'll just add it to my post
score: 0

http://stackoverflow.com/comment/86780454
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49880971
type: QuestionComment
has text: It would be helpful if you made a few lines of data and also what the desired result it. That said I think you need to pick one "tool" although all the tools you mention will let you do this.

http://stackoverflow.com/comment/86736541
score: 0
type: Comment
has text: sorry, i've made a little update, i forgot to make a copy of some lists in the previous edit, this one should match your needs : [[1,3 ], [1, 3], [1,2,3], [1,3], []] returns [1,3]
type: AnswerComment
comment on: http://stackoverflow.com/a/49860067

http://stackoverflow.com/q/49826968
has comment: http://stackoverflow.com/comment/86669690
has title: Python Multi Requests URLs
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49835399
has body: Hi Guys, im new with python (im just begining less than 2 weeks) so i need some advices and tricks :p what is the fastest and most efficient way to fetch around 1500 api request ? use async function that execute them all and return to get the results ? dividing them into lists of 300 urls and put every list inside a Thread which will execute them inside an async loop ? do the same thing as the second suggestion but with Processes instead of Threads ? for the moment it's working for me but it takes something like 8s to execute 1400 api requests but when i try a single request without threads it takes 9s im i doing something wrong ??! Fetch one URL ( i tried to pass the Session as param but i get errors when reachs the 700 requests ) async def fetch_one(url): async with curio_http.ClientSession() as session: response = await session.get(url) content = await response.json() return content fetch a list of URLs inside an async loop async def fetchMultiURLs(url_list): tasks = [] responses = [] for url in url_list: task = await curio.spawn(fetch_one(url)) tasks.append(task) for task in tasks: content = await task.join() responses.append(content) print(content) Create Threads and put inside them Async Loops depending on URLs / X URL by Loop for example MultiFetch(URLS[600],200) will create 3 threads that will call 200 requests by thread and in async way def MultiFetch(URLS,X): MyThreadsList = [] MyThreadsResults = [] N_Threads = (lambda x: int (x/X) if (x % X == 0) else int(x/X)+1) (len(URLS)) for i in range( N_Threads ): # will iterate X = ListSize / X MyThreadsList.append( Thread( target = curio.run , args = (fetchMultiURLs( (URLS[ i*X:(X*i+X)]) ) ,) ) ) MyThreadsList[i].start() for i in range( N_Threads ): MyThreadsResults.append(MyThreadsList[i].join()) return MyThreadsResults
score: 0
has comment: http://stackoverflow.com/comment/86681488
tagged with: async-await
tagged with: python
tagged with: curl
type: Question
tagged with: python-3.x
tagged with: api
has answer: http://stackoverflow.com/a/49835399
answer count: 1

http://stackoverflow.com/comment/86822323
has text: Is the server getting the request?
type: AnswerComment
comment on: http://stackoverflow.com/a/49888368
score: 0
type: Comment

http://stackoverflow.com/comment/134882709
type: Comment
score: 0
type: AnswerComment
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
comment on: http://stackoverflow.com/a/76492953

http://stackoverflow.com/a/49777827
has comment: http://stackoverflow.com/comment/86576655
has comment: http://stackoverflow.com/comment/86575493
has comment: http://stackoverflow.com/comment/86581750
type: Answer
answers question: http://stackoverflow.com/q/49775515
has comment: http://stackoverflow.com/comment/86575578
score: 0
has comment: http://stackoverflow.com/comment/86575767
has comment: http://stackoverflow.com/comment/86598334
has comment: http://stackoverflow.com/comment/86577148
has body: Using matplotlib you can plot slices. You should separate the slices yourself, such as: import matplotlib.pyplot as plt #normalize these filters first, otherwise they won't be in a suitable range for plotting: maxVal = filters.max() minVal = filters.min() absMax = max(abs(minVal),abs(maxVal)) filters = (filters / absMax)*255 for outputChannel in range(6): for inputChannel in range(3): filt = filters[:,:,inputChannel,outputChannel] #a trick to see negatives as blue and positives as red imageRed = np.array(filt) imageBlue = np.array(filt) imageRed[imageRed&lt;0] = 0 imageBlue[imageBlue&gt;0]= 0 print(imageRed) print(imageBlue) finalImage = np.zeros((filt.shape[0],filt.shape[1],3)) finalImage[:,:,0] = imageRed finalImage[:,:,2] = -imageBlue #plot image here plt.figure() plt.imshow(finalImage)
has comment: http://stackoverflow.com/comment/86576722
has comment: http://stackoverflow.com/comment/86576610
has comment: http://stackoverflow.com/comment/86576699
has comment: http://stackoverflow.com/comment/86575760
has comment: http://stackoverflow.com/comment/86576685
has comment: http://stackoverflow.com/comment/86575577

http://stackoverflow.com/comment/86583088
has text: It is showing `Making HTTP connection to <ip>:8080` and hanged there.
comment on: http://stackoverflow.com/a/49783763
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49827487
has comment: http://stackoverflow.com/comment/86670523
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49827411
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86686709
has body: The with open will automatically close the file when it is finished. The while loop is getting caught in an infinite loop as the condition it is checking is simply while file_reader file_reader is in existence so it will remain true. A better approach is to use a loop that takes into account the number of files. something like: while file_count &lt; number_of_files: ... or as an example: num_files = 5 count = 0 while count &lt; num_files: print(n_files) count += 1 This way the while loop will break when it finishes iterating over all the files and ultimately close the last one If you need to find out how many rows are in the file you can count them like so import csv with open('lines.csv') as lines: l = csv.reader(lines) # will read in larger files much better row_count = sum(1 for row in l) - 1 # -1 to not count the header row, if it exists. print(row_count)
type: Answer
accepted answer of: http://stackoverflow.com/q/49827411

http://stackoverflow.com/a/49840979
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86696645
accepted answer of: http://stackoverflow.com/q/49840828
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49840828
has body: The first \ in your specified path tells the runtime too look for your naivebayes.exe in the root directory of the drive (which I assume wasn't your goal). You should specify your filename without a leading \ (or use a leading dot even before it, since .\ construct would point relatively).

http://stackoverflow.com/q/49879993
favorite count: 0
type: Question
score: 31
has answer: http://stackoverflow.com/a/79337794
linked to: http://stackoverflow.com/q/79238532
has answer: http://stackoverflow.com/a/76155161
has answer: http://stackoverflow.com/a/74221291
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/65465322
has answer: http://stackoverflow.com/a/67152755
has comment: http://stackoverflow.com/comment/86777221
has answer: http://stackoverflow.com/a/77880402
tagged with: python
has title: Push notification from python to android
has answer: http://stackoverflow.com/a/61701062
has comment: http://stackoverflow.com/comment/86777435
has answer: http://stackoverflow.com/a/61239489
upvote count: 31
downvote count: 0
has body: I'm running some scripts and looking for an easy way to ping my phone once the script has finished running. Doing some research on the web, I've seen ways of sending messages using Slack, Push bullet, twilio, email etc. I am looking for recommendations for an easy way to send a ping/message from python to my phone. Easy in the sense it dose not require considerable configuring of outside accounts or pay services.
tagged with: push-notification
linked to: http://stackoverflow.com/q/41174831
has comment: http://stackoverflow.com/comment/86777644
answer count: 10
has answer: http://stackoverflow.com/a/54132916
has answer: http://stackoverflow.com/a/74159900

http://stackoverflow.com/comment/86597580
type: QuestionComment
comment on: http://stackoverflow.com/q/49791178
has text: Have you installed it using `pip install git+https://www.github.com/keras-team/keras-contrib.git`?
type: Comment
score: 4

http://stackoverflow.com/q/49881391
tagged with: python
answer count: 4
favorite count: 0
tagged with: movie
type: Question
tagged with: python-3.x
downvote count: 0
has answer: http://stackoverflow.com/a/49881721
has answer: http://stackoverflow.com/a/49884321
upvote count: 1
accepted answer: http://stackoverflow.com/a/49881721
has answer: http://stackoverflow.com/a/49881611
has answer: http://stackoverflow.com/a/49901116
tagged with: count
tagged with: text
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49881611
has body: I already managed to uncover the spoken words with some help. Now I'm looking for to get the text spoken by a chosen person. So I can type in MIA and get every single words she is saying in the movie Like this: name = input("Enter name:") wordsspoken(script, name) name1 = input("Enter another name:") wordsspoken(script, name1) So I'm able to count the words afterwards. This is how the movie script looks like An awkward beat. They pass a wooden SALOON -- where a WESTERN is being shot. Extras in COWBOY costumes drink coffee on the steps. Revision 25. MIA (CONT'D) I love this stuff. Makes coming to work easier. SEBASTIAN I know what you mean. I get breakfast five miles out of the way just to sit outside a jazz club. MIA Oh yeah? SEBASTIAN It was called Van Beek. The swing bands played there. Count Basie. Chick Webb. (then,) It's a samba-tapas place now. MIA A what? SEBASTIAN Samba-tapas. It's... Exactly. The joke's on history.
has title: Counting the words a character said in a movie script
score: 1

http://stackoverflow.com/comment/86539476
type: AnswerComment
score: 0
type: Comment
has text: I´m using Windows 10, and after trying what you recommend and some variations of it, I'm having the same error from Facebook: "Can't Load URL: The domain of this URL isn't included in the App's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.". Could it be something about how my Django app communicates with Facebook?
comment on: http://stackoverflow.com/a/49758686

http://stackoverflow.com/comment/86547120
type: Comment
comment on: http://stackoverflow.com/a/49765419
score: 0
has text: Thanks for the info and explanation!
type: AnswerComment

http://stackoverflow.com/q/49902729
has comment: http://stackoverflow.com/comment/86821135
has answer: http://stackoverflow.com/a/49903837
type: Question
has answer: http://stackoverflow.com/a/49903611
downvote count: 2
has comment: http://stackoverflow.com/comment/86821463
upvote count: 1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86821522
has answer: http://stackoverflow.com/a/49903415
favorite count: 0
has title: python regular expression to extract date
has comment: http://stackoverflow.com/comment/86821142
answer count: 3
has body: I am trying to extract a date from a text.Text must contain 'Expiration Date:' some where in line. i have written this python script date = re.findall('Expiration Date:*(.+)', w.text) but this is not working in some case. Like in case of 'Registrar Registration Expiration Date:'. Also, how can check for multiple types of match like if the text has 'Expiry date' in place of 'Expiration date'
score: -1
tagged with: regex

http://stackoverflow.com/comment/86626279
type: QuestionComment
has text: This: http://www.cs.sjsu.edu/~pearce/modules/patterns/distArch/pipeline.htm or this: https://gerardnico.com/data/processing/stream/stream or this: https://learn.microsoft.com/en-us/azure/architecture/patterns/pipes-and-filters or this: https://stackoverflow.com/questions/17305173/how-to-set-up-a-pipeline-using-queues-in-multiprocessing
score: 0
comment on: http://stackoverflow.com/q/49782852
type: Comment

http://stackoverflow.com/a/66007569
downvote count: 0
has body: zip is useful to enumerate the elements in the 2 different list and make a single list example : x: y for x, y in zip(Class_numbers, students_per_class) explanation: the element form Class_number is assigned to x which is a "Key" for the dictionary and the students_per_class is assigned to y which is a "value until the loop end it will iterate to dictionary.
answers question: http://stackoverflow.com/q/49783594
type: Answer
score: 2
upvote count: 2

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/49887142
tags question: http://stackoverflow.com/q/49909609
tag name: kivy-language
tags question: http://stackoverflow.com/q/49807052
tags question: http://stackoverflow.com/q/49761150
tags question: http://stackoverflow.com/q/49896686
tags question: http://stackoverflow.com/q/49786095

http://stackoverflow.com/q/49838068
favorite count: 0
type: Question
has body: This is the code i'm trying to run on an virtual environment in python3.6. I use ubuntu newest version 17.10, I run the code as python3 gather_annotations.py import numpy as np import cv2 import argparse from imutils.paths import list_images from selectors import BoxSelector #parse arguments ap = argparse.ArgumentParser() ap.add_argument("-d","--dataset",required=True,help="path to images dataset...") ap.add_argument("-a","--annotations",required=True,help="path to save annotations...") ap.add_argument("-i","--images",required=True,help="path to save images") args = vars(ap.parse_args()) #annotations and image paths annotations = [] imPaths = [] #loop through each image and collect annotations for imagePath in list_images(args["dataset"]): #load image and create a BoxSelector instance image = cv2.imread(imagePath) bs = BoxSelector(image,"Image") cv2.imshow("Image",image) cv2.waitKey(0) #order the points suitable for the Object detector pt1,pt2 = bs.roiPts (x,y,xb,yb) = [pt1[0],pt1[1],pt2[0],pt2[1]] annotations.append([int(x),int(y),int(xb),int(yb)]) imPaths.append(imagePath) #save annotations and image paths to disk annotations = np.array(annotations) imPaths = np.array(imPaths,dtype="unicode") np.save(args["annotations"],annotations) np.save(args["images"],imPaths) And I get the following errors I have this Folder named '2' where I have all the scripts and other folder named selectors where there is 2 scripts init and box_selector 2(folder) ----selectors/ ------------_ init _.py ------------box_selector.py ----detector.py ----gather_annotations.py ----test.py ----train.py How can I fix that, in the post where I got the code from says something about 'relative imports' but i couln't fix it, thank you.
tagged with: opencv3.0
has comment: http://stackoverflow.com/comment/86691437
score: 1
has comment: http://stackoverflow.com/comment/86691302
has comment: http://stackoverflow.com/comment/86691652
tagged with: python
has answer: http://stackoverflow.com/a/49838309
has comment: http://stackoverflow.com/comment/86691516
accepted answer: http://stackoverflow.com/a/49838309
has title: Module not found error (imutils.paths)
has comment: http://stackoverflow.com/comment/86691543
type: AnsweredQuestion
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/55944023
upvote count: 1
has comment: http://stackoverflow.com/comment/86691479
has comment: http://stackoverflow.com/comment/86691481
has answer: http://stackoverflow.com/a/55944023
has comment: http://stackoverflow.com/comment/86691500
linked to: http://stackoverflow.com/q/4142151

http://stackoverflow.com/q/49886186
tagged with: emacs
has title: Emacs: starting a new inferior python shell when evaluating buffer
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86789087
tagged with: python
has answer: http://stackoverflow.com/a/65496992
has comment: http://stackoverflow.com/comment/86799851
score: 2
has body: I am working in vanilla Emacs 23 on various python programs, when I evaluate a buffer, an inferior python shell is started as expected and the scripts run fine... This is all fine, however, when working on multiple (unrelated) projects, the same python instance is used, is there a way I can create a new inferior python shell per source file? Thanks
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49901874

http://stackoverflow.com/q/49802553
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86620629
accepted answer: http://stackoverflow.com/a/49804090
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49804090
downvote count: 1
has comment: http://stackoverflow.com/comment/86621363
favorite count: 0
type: Question
has title: Merge Pandas Dataframes based on same hour
has comment: http://stackoverflow.com/comment/86619886
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/87607502
tagged with: python
has body: I have a history of values at hour intervals, and I want to add a column to the dataframe that puts the average at that hour across every day. So if the average value for 4:00 is 34, I want every date with the hour 4:00 to have 34 in a column called 'Average'. Right now I can get the averages in a table with the hours, but can't seem to get it to join in more than one spot. Timestamp Value 2018-04-12 13:00:00 12.0 2018-04-12 12:00:00 38.0 2018-04-12 11:00:00 12.0 2018-04-12 10:00:00 28.0 2018-04-12 09:00:00 26.0 2018-04-12 08:00:00 22.0 ... Average 00:00 7.0 01:00 0.0 02:00 0.0 03:00 0.0 04:00 0.0 05:00 1.5 06:00 11.5 07:00 11.0 08:00 10.5 ... Goal: Timestamp Value Average 2018-04-12 13:00:00 12.0 8.5 2018-04-12 12:00:00 38.0 8.4 2018-04-12 11:00:00 12.0 15.5 2018-04-12 10:00:00 28.0 19.0 2018-04-12 09:00:00 26.0 12.4 2018-04-12 08:00:00 22.0 10.5 I've tried merging, and joining, but haven't figured out how to loop through manually to do it.

http://stackoverflow.com/q/49799114
type: Question
has body: I want to create a function that goes through my Pandas Dataframe and converts all date variables in the following format: %b-%Y, for example: Jun-2017, Apr-2017, May-2017, and so on, into the difference between the current year and the year of the date in each registry (for example: 2018 - year_corresponding_to_each_registry). My function is: def date_to_numeric(df): for col in dates: print("Converting date variables to years: " + col, flush = True) df[col] = df[col].apply(pd.to_datetime, format = '%b-%Y', errors = 'coerce') df[col] = df[col].apply(dt.year) return df I am having a problem in the following line: df[col] = df[col].apply(dt.year) I am receiving the following error message: AttributeError: module 'datetime' has no attribute 'year' P.D. I have imported datetime library with the following line code: import datetime as dt Thanks in advance for any help provided in how to accomplish this in an efficient way. ANSWER Thanks to @DeepSpace answer (check it below marked as correct answer): def date_to_numeric(df): for col in dates: print("Converting date variables to years: " + col, flush = True) df[col] = df[col].apply(pd.to_datetime, format = '%b-%Y', errors = 'coerce') df[col] = 2018 - df[col].apply(pd.to_datetime, errors = 'coerce').dt.year return df
tagged with: datetime
tagged with: dataframe
tagged with: python
has title: Year extraction with datetime library for several columns
has comment: http://stackoverflow.com/comment/86613168
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86613037
has answer: http://stackoverflow.com/a/49799300
accepted answer: http://stackoverflow.com/a/49799300
has answer: http://stackoverflow.com/a/49799316
possible better answer: http://stackoverflow.com/a/49799316

http://stackoverflow.com/q/49860522
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has title: Getting extra data from named pipe, C program (writer) and Python (reader)
has comment: http://stackoverflow.com/comment/86736198
has comment: http://stackoverflow.com/comment/86737037
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86736968
has comment: http://stackoverflow.com/comment/86736300
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86736904
has comment: http://stackoverflow.com/comment/86736107
tagged with: named-pipes
has body: I have a C program that is writing to a named pipe which is just outputting strings and a "/n" character as a delimiter. When I read from this named pipe using another C program my string comes back as expected. I have a python script which is what I want to be reading the named pipe with. It get's the proper string but also outputs lots of other garage data along with it including device descriptors. EDIT: I should note I'm working with named-pipes on linux Here's the C program reader which works fine: #include &lt;fcntl.h&gt; #include &lt;stdio.h&gt; #include &lt;sys/stat.h&gt; #include &lt;unistd.h&gt; #define MAX_BUF 1024 int main() { int fd; char * myfifo = "/tmp/testpipe"; char buf[MAX_BUF]; while(1){ /* open, read, and display the message from the FIFO */ fd = open(myfifo, O_RDONLY); read(fd, buf, MAX_BUF); printf("Received: %s\n", buf); close(fd); } return 0; } and the python version: import os import errno FIFO = '/tmp/testpipe' try: os.mkfifo(FIFO) except OSError as oe: if oe.errno != errno.EEXIST: raise while True: with open(FIFO) as fifo: for line in fifo: print('{0}',line) The output I'm getting is: ('{0}', 'systime=1523890481 ch=25 LAP=c969d3 err=0 clkn=286140 clk_offset=954 s=-68 n=-55 snr=-13\n') ('{0}', "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa0\x97\xfav(\xdc\xf7~\xc0\xf3\xd1v\x96\x06\x00\x00,\xdc\xf7~$F\xf8v\x01\x00\x00\x00\xb4e\xd2v\x96\x06\x00\x00\x04\x88\xd2…
has comment: http://stackoverflow.com/comment/86736855
tagged with: linux
has answer: http://stackoverflow.com/a/49860630
has comment: http://stackoverflow.com/comment/86736444
score: 1
has comment: http://stackoverflow.com/comment/86736469

md5
tags question: http://stackoverflow.com/q/49905732
tag name: md5
tags question: http://stackoverflow.com/q/49817624
type: Tag

http://stackoverflow.com/q/49886183
has answer: http://stackoverflow.com/a/54224597
has comment: http://stackoverflow.com/comment/86788478
has answer: http://stackoverflow.com/a/66575738
has answer: http://stackoverflow.com/a/64739046
has answer: http://stackoverflow.com/a/73254623
favorite count: 0
has title: ModuleNotFoundError: No module named 'discord'
has answer: http://stackoverflow.com/a/71663297
has comment: http://stackoverflow.com/comment/86788548
has answer: http://stackoverflow.com/a/77141028
has comment: http://stackoverflow.com/comment/86788587
has answer: http://stackoverflow.com/a/65839413
tagged with: discord.py
type: Question
answer count: 12
has answer: http://stackoverflow.com/a/49898898
has comment: http://stackoverflow.com/comment/86788948
type: UnansweredQuestion
tagged with: python
has body: Trying to run my .py file from CMD, but it can't find the discord module &gt;&gt;File 'C:\Users\\****\Desktop\Discord_Bot\main.py', line 1, in module &gt;&gt;import discord &gt;&gt;ModuleNotFoundError: No module named 'discord' Although, when I run: &gt;&gt;python &gt;&gt;import discord It works as intended, any suggestions?
has answer: http://stackoverflow.com/a/67437346
has answer: http://stackoverflow.com/a/51582000
downvote count: 0
has answer: http://stackoverflow.com/a/78451425
has comment: http://stackoverflow.com/comment/117690917
has answer: http://stackoverflow.com/a/64477144
has comment: http://stackoverflow.com/comment/86788433
upvote count: 10
tagged with: discord
score: 10
has comment: http://stackoverflow.com/comment/86788818

http://stackoverflow.com/comment/86776897
has text: Mention *ploting timedelta is not supported yet* , definitely deserve many upvotes : -)
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/49880446
type: Comment

http://stackoverflow.com/comment/86538532
type: Comment
type: QuestionComment
has text: your indentation is off- can you [edit](https://stackoverflow.com/posts/49761287/edit) your question and fix it?
score: 0
comment on: http://stackoverflow.com/q/49761287

http://stackoverflow.com/a/49904302
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/49904181
score: 8
has body: create a set from dict tuples then test if the set is a subset of the other item tuples def is_subset(A,B): return set(A.items()).issubset(B.items()) Once created, set guarantees a very fast lookup. (if the operation has to be repeated with the same A it's better to "cache" set(A.items()) for better performance) It works because values of the dictionaries are hashable. If they aren't, the good old all(x in y for ...) method is another option (see other answers).
accepted answer of: http://stackoverflow.com/q/49904181
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86749902
comment on: http://stackoverflow.com/q/49866788
score: 0
type: Comment
type: QuestionComment
has text: @BryanOakley Thanks. It is something I should have seen on my own. Now to work it into my program tomorrow when I get back to my desk. I didn't combine the example into one file because I considered the problem could be related to how I am importing or because my pages are all different files. So I figured writing my example would be best to follow the same logic.

http://stackoverflow.com/comment/86671989
type: Comment
type: QuestionComment
has text: For those desiring to vote to close this question, [RTFM is not a close reason](https://meta.stackoverflow.com/a/253484/5376789).
score: 6
comment on: http://stackoverflow.com/q/49827518

http://stackoverflow.com/q/49841625
upvote count: 2
duplicate of: http://stackoverflow.com/q/1411186
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/13914495
downvote count: 0
has body: I would like to know how to "cleanly" finish the execution of a python application on Windows shutdown. My application starts at startup, opens a text file and keeps running while Windows is on, What I want to do is to, somehow, capture the shutdown signal and inmediately stop the processes running and close the text file with the io method myFile.close(), finishing the program by itself, and not forced by Windows. Any idea about how that could be done? Thank you in advance. Regards
duplicate of: http://stackoverflow.com/q/16145516
duplicate of: http://stackoverflow.com/q/13914495
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/25104119
tagged with: operating-system
linked to: http://stackoverflow.com/q/24413713
linked to: http://stackoverflow.com/q/25104119
tagged with: python
linked to: http://stackoverflow.com/q/1411186
tagged with: python-3.x
score: 2
has title: Cleanly finish Python 3.6 application at shutdown on Windows
tagged with: shutdown
answer count: 0
linked to: http://stackoverflow.com/q/16145516

http://stackoverflow.com/q/49842120
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
has comment: http://stackoverflow.com/comment/86711127
has comment: http://stackoverflow.com/comment/86705671
tagged with: tkinter
answer count: 0
has title: can we use a single thread by creating and deleting it and again using it?
type: UnansweredQuestion
score: 1
tagged with: multithreading
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/2846653
has body: I am using tkinter and python and using speech recong and talkback for that. The problem is I have to create a lot of threads every time I want the function of talkback to call.is there any way to create a single thread and delete it after using it.
has comment: http://stackoverflow.com/comment/86701814

http://stackoverflow.com/comment/112448981
score: 0
type: Comment
comment on: http://stackoverflow.com/a/63587520
type: AnswerComment
has text: Maybe could you insert the reply within stackoverflow to avoid to insert a dependency.

http://stackoverflow.com/q/49764861
has comment: http://stackoverflow.com/comment/116631506
has comment: http://stackoverflow.com/comment/86578190
tagged with: javascript
tagged with: python
has body: Is it possible to copy cached video data from a browser after the video finishes loading? I would like to use python or javascript.
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/116665012
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86546139
has title: How to copy cached video from browser?
type: UnansweredQuestion

http://stackoverflow.com/comment/86744640
type: AnswerComment
comment on: http://stackoverflow.com/a/49864541
score: 1
type: Comment
has text: This would assign `non-luxury` category to cars not in `nonluxury` list.

http://stackoverflow.com/a/49844634
has body: If I'm understanding your needs correctly, then you might be able to use the turtle screen's ontimer() method. You want to do done() which turns control over to tkinter's event loop. But by having an ontimer() event, which reinvokes itself as the last thing it does, you can have event-friendly code constantly checking for more datapoints. Roughly: from turtle import Turtle, Screen def my_update(): # get the new data # ... # draw the new data turtle.forward(...) # reinvoke one-shot (5 secs. from now) screen.ontimer(my_update, 5000) screen = Screen() turtle = Turtle() # invoke one-shot (5 secs. from now) screen.ontimer(my_update, 5000) screen.mainloop()
type: Answer
answers question: http://stackoverflow.com/q/49790366
score: 0

http://stackoverflow.com/comment/86625616
type: Comment
has text: I don't understand how to use psycopg2.extensions.AsIs. And yes 4000.
score: 0
comment on: http://stackoverflow.com/q/49804961
type: QuestionComment

http://stackoverflow.com/comment/86651624
score: 0
has text: Glad to know your scripts are back on track. Possibly you can raise a ticket on [serverfault](https://serverfault.com/tour) to get a clear understanding. Do keep me updated.
type: QuestionComment
comment on: http://stackoverflow.com/q/49771424
type: Comment

http://stackoverflow.com/comment/86627925
type: QuestionComment
comment on: http://stackoverflow.com/q/49803188
score: 0
has text: You may be able to make that work with serious time investment or you can switch to App Service Linux and build a Dockerfile for your app with all the _pips_ installed - https://learn.microsoft.com/en-us/azure/app-service/containers/tutorial-custom-docker-image
type: Comment

http://stackoverflow.com/a/53700609
has body: You can resolve this issue by reinstalling pip. Use one of the following command line commands to reinstall pip: Python2: python -m pip uninstall pip &amp;&amp; sudo apt install python-pip --reinstall Python3: python3 -m pip uninstall pip &amp;&amp; sudo apt install python3-pip --reinstall
answers question: http://stackoverflow.com/q/49836676
score: 18
downvote count: 0
type: Answer
upvote count: 18

http://stackoverflow.com/q/49824358
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 1
tagged with: django
has title: Updating django model with highest value in json array
has body: The issue I'm running into is that I would like to update a Django model with json values. The trouble is that some of the values in the json are a lists with multiple numbers. This is what the json looks like: json = {'fields': {'resources': [], 'initiative': [8, 21, 22]}, 'pk': 81} {'fields': {'resources': [], 'initiative': [5, 8, 22]}, 'pk': 82} {'fields': {'resources': [], 'initiative': [8, 22]}, 'pk': 83} {'fields': {'resources': [], 'initiative': [6]}, 'pk': 84} def update_model(): for row in json: Model.objects.filter(id=row['pk']).update(initiative_id=row['fields']['initiative'][0], resources_id=row['fields']['resources'][0]) I can't figure how to get the Model line spaced correctly on Stack. Anyway, when I run this I get "IndexError: list index out of range" presumably because this method can only handle a list with 1 value. I need the highest value in the arrays for resources and initiatives to update Model with. Model: class Model(models.Model): name = models.CharField(max_length=100, unique=True) genre = models.ManyToManyField(Genre, blank=False) platform = models.ManyToManyField(Platform, blank=True) standard_type = models.ForeignKey(StandardType, default=SetDefaults.set_standard_type_default, blank=True) owner = models.ManyToManyField(Owner, blank=True) evaluated_by = models.ForeignKey(Evaluator, blank=True, default=SetDefaults.set_default_evaluator()) business_driver= models.ManyToManyField(BusinessDriver, blank=True) initiative = models.ForeignKey(Initiative, null=True, blank=True) solution = models.ManyToManyField(Solution, blank=True) point_of_contact = models.ForeignKey(Contact, null=True, default=SetDefaults.set_default_contact, blank=True) description = models.TextField(blank=True) required_by = models.ForeignKey(LifecycleStage, null=False, default=SetDefaults.set_required_by_default, blank=True) resources = models.ForeignKey(Resource, null=True, blank=True) change_notes = models.TextField(null=True, blank=True) change_date = models.DateField(nu…
type: Question
has answer: http://stackoverflow.com/a/49824706
accepted answer: http://stackoverflow.com/a/49824706
tagged with: http://stackoverflow.com/tag/json
tagged with: python

http://stackoverflow.com/q/49908270
accepted answer: http://stackoverflow.com/a/49908413
upvote count: 2
tagged with: jython
has answer: http://stackoverflow.com/a/49908413
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
answer count: 1
has title: Websphere 9X unable to deploy ear file via jython script
tagged with: websphere-9
has body: I'm writing due to an error I just cannot seem to work around. WASX7017E: Exception received while running file "/root/wsDeploy.py"; exception information: com.ibm.ws.scripting.ScriptingException: WASX7115E: Cannot read input file "/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/installableApps/my_ear_file.ear,'[-node DefaultNode01 -cell DefaultCell01 -server server1 -MapWebModToVH [[ "Our War One" first_war.war,WEB-INF/web.xml default_host ]["Our War Two" second_war.war,WEB-INF/web.xml default_host]["Our War Three" third_war.war,WEB-INF/web.xml default_host]]]'" Now that script has the following variables and syntax: ParameterStr = "-node DefaultNode01 -cell DefaultCell01 -server server1 -MapWebModToVH [[ \"Our War One\" first_war.war,WEB-INF/web.xml default_host ][\"Our War Two\" second_war.war,WEB-INF/web.xml default_host][\"Our War Three\" third_war.war,WEB-INF/web.xml default_host]]" EAR_FILE=/path/to/file/my_ear_file.ear This is the portion of code which is choking when executed by websphere in jython(2.7) (Also fails in 2.1) elif UpdateExistingorNewApp == "INITIAL" and ConditionForUpdate == 0: AdminApp.install(EAR_FILE + "," + "'" + "[" + ParameterStr + "]" + "'") AdminConfig.save() I have tried AdminApp.install( 'EAR_FILE' + "," + "'" + "[" + ParameterStr + "]" + "'") AdminApp.install( "'" + EAR_FILE + "'" +"," + "'" + "[" + ParameterStr + "]" + "'") AdminApp.install( \' EAR_FILE \' + "," + "'" + "[" + ParameterStr + "]" + "'") I have even tried adding the "[ ]" pair inside the ParameterStr variables as well. I have looked at the following documents for guidance: https://www.ibm.com/developerworks/community/forums/html/topic?id=43cee700-9074-49e1-9223-7c4db2d89680 https://developer.ibm.com/answers/questions/258458/ucd-install-application-fails-with-wasx7115e-canno/ I have verified the path to the ear, the permissions on the ear, and the ownership of the ear. Am I having an issue similar to globbing? The input file is there, and is world readable. I have even …
favorite count: 0
type: Question
tagged with: websphere

http://stackoverflow.com/comment/86541893
comment on: http://stackoverflow.com/a/49763114
has text: Is it? I think it's about making the text matched by the first group as short as possible. If that's what the question is about, why would you suggest prepending `.*`? That does something completely different than your lookahead.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86696296
comment on: http://stackoverflow.com/a/49837970
type: Comment
has text: It's only the code above. The turtle window opens in both environments. Interestingly, I'm unable to move the turtle window at all when it first opens in Windows but I can do so on Linux. I've also tried both powershell and command prompt on Windows and two different windows machines now.
type: AnswerComment
score: 0

http://stackoverflow.com/q/49869291
tagged with: python
possible better answer: http://stackoverflow.com/a/49869332
has body: I am implementing K-Means in Spark and when I try to run my script using spark-submit Kmeans.py I keep getting the error unexpected character after line continuation. I am using the backslash for line continuation but I don't see how I am using it wrong. I will post my algorithm below. import pyspark from pyspark.context import SparkContext from pyspark import SparkConf from pyspark.sql import SparkSession, SQLContext, Row from pyspark.sql.functions import * from pyspark.ml.clustering import KMeans import json import os conf = SparkConf() sc = SparkContext(conf = conf) sc.setLogLevel("ERROR") spark = SparkSession \ .builder \ .appName("Phone Book - Country Look up") \ .config("spark.some.config.option", "some-value") \ .getOrCreate() dataset = spark.read.format("libsvm") \ .load("/home/jay/Assignment6/Input.txt") dataset.show(200) dataset.printSchema() kmeans = KMeans().setK(2).setSeed(1) model = kmeans.fit(dataset) var1 = model.computeCost(dataset) print("Within Set Sum of Squared Errors =" + str(var1)) centers = model.clusterCenters() print("Cluster centers: ") for center in centers: print(center)
type: Question
accepted answer: http://stackoverflow.com/a/49872744
has answer: http://stackoverflow.com/a/49869332
answer count: 2
has answer: http://stackoverflow.com/a/49872744
has title: Unexpected character after line continuation when running python for Kmeans
upvote count: 0
score: -2
downvote count: 2
tagged with: k-means
has comment: http://stackoverflow.com/comment/86753987
tagged with: ubuntu
favorite count: 0
type: AnsweredQuestion
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/86754002

http://stackoverflow.com/comment/86576513
type: QuestionComment
has text: This question is "too broad"/"primarily opinion based"/"offtopic" for StackOverflow. However, I personally would *really like* to hear an answer for that question. Would it make sense to move it to [Software Recommendations Stack Exchange](https://softwarerecs.stackexchange.com)?
score: 3
type: Comment
comment on: http://stackoverflow.com/q/49780463

http://stackoverflow.com/comment/86681977
type: Comment
has text: The error is very suggestive: `userShop[buyFrom]` returns an `integer` and not a `list` as you expect..
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49833341

http://stackoverflow.com/q/49776015
tagged with: minimize
answer count: 2
tagged with: compiler-errors
score: 7
downvote count: 0
upvote count: 7
tagged with: scipy
has answer: http://stackoverflow.com/a/49776137
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86567938
has answer: http://stackoverflow.com/a/49776182
type: UnansweredQuestion
has title: scipy.minimize - "TypeError: numpy.float64' object is not callable running"
has body: Running the scipy.minimize function "I get TypeError: 'numpy.float64' object is not callable". Specifically during the execution of: .../scipy/optimize/optimize.py", line 292, in function_wrapper return function(*(wrapper_args + args)) I already looked at previous similar topics here and usually this problem occurs due to the fact that as first input parameter of .minimize is not a function. I have difficulties in figure it out, because "a" is function. What do you think? ### "data" is a pandas data frame of float values ### "w" is a numpy float array i.e. [0.11365704 0.00886848 0.65302202 0.05680696 0.1676455 ] def a(data, w): ### Return a negative float value from position [2] of an numpy array of float values calculated via the "b" function i.e -0.3632965490830499 return -b(data, w)[2] constraint = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1}) ### i.e ((0, 1), (0, 1), (0, 1), (0, 1), (0, 1)) bound = tuple((0, 1) for x in range (len(symbols))) opts = scipy.minimize(a(data, w), len(symbols) * [1. / len(symbols),], method = 'SLSQP', bounds = bound, constraints = constraint)
tagged with: python

directed-acyclic-graphs
type: Tag
tags question: http://stackoverflow.com/q/49858685
tags question: http://stackoverflow.com/q/49902599
tag name: directed-acyclic-graphs

http://stackoverflow.com/a/49904508
has comment: http://stackoverflow.com/comment/86895512
has comment: http://stackoverflow.com/comment/86826395
downvote count: 0
has comment: http://stackoverflow.com/comment/86826277
has body: You can just concatenate and convert to set: res = set(df['a'].astype(str) + df['b'].astype(str)) Example: df = pd.DataFrame({'idx': [1, 2, 3], 'a': [4, 4, 5], 'b': [5, 5,6]}) res = set(df['a'].astype(str) + df['b'].astype(str)) print(res) # {'56', '45'} If you need to map indices too: df = pd.DataFrame({'idx': [1, 2, 3], 'a': [41, 4, 5], 'b': [3, 13, 6]}) df['conc'] = (df['a'].astype(str) + df['b'].astype(str)) df = df.reset_index() res = df.groupby('conc')['index'].apply(set).to_dict() print(res) # {'413': {0, 1}, '56': {2}}
has comment: http://stackoverflow.com/comment/86895102
has comment: http://stackoverflow.com/comment/86826171
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49904462
has comment: http://stackoverflow.com/comment/86895183
has comment: http://stackoverflow.com/comment/86826366
has comment: http://stackoverflow.com/comment/86895497
answers question: http://stackoverflow.com/q/49904462
type: Answer
has comment: http://stackoverflow.com/comment/86826443
score: 2
upvote count: 2

http://stackoverflow.com/q/49758413
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86531831
has body: I am trying to extract a text between the strings " DNA sequence " and " ": handle = open(i, 'r') name = i.split('=')[1] print name soup = BeautifulSoup(handle,"lxml") for item in soup: seq = soup.findAll(seq) print seq Ends IR Length : 44/49 IRL : GAGGGTCGGCAGGGATTCGTGTAAAACACAGCCAAAAGTGAGCTAACTCC IRR : GAGGGTCGACAGGGATTTGTGTAAAAAACAGCCAAAATTGAGCTAAATCT Insertion site Left flank Direct repeat Right flank DR Length TCCACTACCT TCGTTGAGCA 0 IS1007 Family IS6 Group MGE type ISRelated element(s) : Isoform Synonym(s) DNA sequence GGCACTGTTGCAAATAGGCTGACATGATAAGCTAAATATCTTATTTATTTCGAGATACAGCAGATGAATCCCTTCCACGGTCGGCACTTTCAAGGTGAAA GAGAAGTTTGGCTAGTAAATAGAGTTTTCGGTCTCTAAGCTTTTTTGAAGGGAAAATCATTGACTCAGAT CCCTATTTGCAACAGTGCC And the output is this: IS1007 [] [] If I can get this I can remove the {\<\br/>} after. TATCTTATTTATTTCGAGATACAGCAGATGAATCCCTTCCACGGTCGGCACTTTCAAGGTGAAA GAGAAGTTTGGCTAGTAAATAGAGTTTTCGGTCTCTAAGCTTTTTTGAAGGGAAAATCACTCAG ATCCCTATTTGCAACAGTGCC Any suggestion to extract the sequence contained between: \<\div\>\<\p class='entete_propriete'>DNA sequence \<\/\p\> and \<\div\>
upvote count: 0
has title: Python div class extract content
answer count: 1
tagged with: string
downvote count: 1
has comment: http://stackoverflow.com/comment/86531863
favorite count: 0
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49758579

http://stackoverflow.com/q/49770095
upvote count: 8
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/86557287
has comment: http://stackoverflow.com/comment/86555093
has answer: http://stackoverflow.com/a/49778546
has body: I just ran the following code in Python to take all of the certain emails out of an IMAP folder. The extraction part works fine and the BeautifulSoup part works okay, but the output has a lot of '\r' and '\n' within. I tried to remove these with REGEX sub function but it's not working...not even giving an error message. Any idea what is wrong? I am attaching the code...please note (this is not complete code but everything above the code I'm posting works okay. It still prints the output, it's "prettified", but the \r and \n are still there. Have tried with find_all() but that doesn't work either. mail.list() # Lists all labels in GMail mail.select('INBOX/Personal') # Connected to inbox. resp, items = mail.search(None, '(SEEN)') items = items[0].split() # getting the mails id for emailid in items: # getting the mail content resp, data = mail.fetch(emailid, '(UID BODY[TEXT])') text = str(data[0]) # [1] don't forget to add this back soup = bs(text, 'html.parser') soup = soup.prettify() soup = re.sub('\\r\\n', '', soup) print(soup)
tagged with: python
tagged with: regex
has title: beautiful soup regex
has comment: http://stackoverflow.com/comment/86555309
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86555098
has comment: http://stackoverflow.com/comment/86555330
answer count: 2
has answer: http://stackoverflow.com/a/49778048
accepted answer: http://stackoverflow.com/a/49778048
possible better answer: http://stackoverflow.com/a/49778546
score: 7
downvote count: 1

http://stackoverflow.com/q/49841989
duplicate of: http://stackoverflow.com/q/22086116
tagged with: python
has comment: http://stackoverflow.com/comment/86698594
downvote count: 1
upvote count: 6
has answer: http://stackoverflow.com/a/49842016
duplicate of: http://stackoverflow.com/q/13851535
has body: I want to drop rows with zero value in specific columns &gt;&gt;&gt; df salary age gender 0 10000 23 1 1 15000 34 0 2 23000 21 1 3 0 20 0 4 28500 0 1 5 35000 37 1 some data in columns salary and age are missing and the third column, gender is a binary variables, which 1 means male 0 means female. And 0 here is not a missing data, I want to drop the row in either salary or age is missing so I can get &gt;&gt;&gt; df salary age gender 0 10000 23 1 1 15000 34 0 2 23000 21 1 3 35000 37 1
tagged with: pandas
has comment: http://stackoverflow.com/comment/86698660
favorite count: 0
has comment: http://stackoverflow.com/comment/134071627
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86698689
score: 5
type: UnansweredQuestion
answer count: 1
has title: Python: drop value=0 row in specific columns

http://stackoverflow.com/q/49869041
tagged with: regex
tagged with: nlp
has title: ERROR while loading & reading custom 20newsgroups corpus with NLTK
has answer: http://stackoverflow.com/a/49884614
score: 0
tagged with: corpus
answer count: 1
type: Question
has body: I am trying to load the 20newsgroups corpus with the NLTK corpus reader and thereafter I am extracting words from all documents and tagging them. But it is showing error when I am trying to build the word extracted and tagged list. Here is the CODE: import nltk import random from nltk.tokenize import word_tokenize newsgroups = nltk.corpus.reader.CategorizedPlaintextCorpusReader( r"C:\nltk_data\corpora\20newsgroups", r'(?!\.).*\.txt', cat_pattern=r'(not_sports|sports)/.*', encoding="utf8") documents = [(list(newsgroups.words(fileid)), category) for category in newsgroups.categories() for fileid in newsgroups.fileids(category)] random.shuffle(documents) And the corresponding ERROR is: --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) &lt;ipython-input-10-de2a1a6859ea&gt; in &lt;module&gt;() 1 documents = [(list(newsgroups.words(fileid)), category) ----&gt; 2 for category in newsgroups.categories() 3 for fileid in newsgroups.fileids(category)] 4 5 random.shuffle(documents) &lt;ipython-input-10-de2a1a6859ea&gt; in &lt;listcomp&gt;(.0) 1 documents = [(list(newsgroups.words(fileid)), category) 2 for category in newsgroups.categories() ----&gt; 3 for fileid in newsgroups.fileids(category)] 4 5 random.shuffle(documents) C:\ProgramData\Anaconda3\lib\site-packages\nltk\corpus\reader\util.py in __len__(self) 231 # iterate_from() sets self._len when it reaches the end 232 # of the file: --&gt; 233 for tok in self.iterate_from(self._toknum[-1]): pass 234 return self._len 235 C:\ProgramData\Anaconda3\lib\site-packages\nltk\corpus\reader\util.py in iterate_from(self, start_tok) 294 self._current_toknum = toknum 295 self._current_blocknum = block_index --&gt; 296 tokens = self.read_block(self._stream) 297 assert isinstance(tokens, (tuple, list, AbstractLazySequence)), ( 298 'block reader %s() should return list or tuple.' % C:\ProgramData\Anaconda3\lib\site-packages\nltk\corpus\reader\plaintext.py in _re…
tagged with: nltk
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/86789450
has text: Why did you leave?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49885898

http://stackoverflow.com/q/49784924
tagged with: ssl
tagged with: python
tagged with: macos
has body: I am having a problem confirming the ssl certificate: ("bad handshake: Error([('SSL routines', 'SSL23_GET_SERVER_HELLO', 'tlsv1 alert protocol version')],)",) - skipping I'm trying to do something very basic and I don't understand why this keeps happening. Would someone please advise how to fix this issue? pip install fake-useragent
linked to: http://stackoverflow.com/q/49748063
favorite count: 0
type: Question
tagged with: openssl
duplicate of: http://stackoverflow.com/q/49748063
has answer: http://stackoverflow.com/a/49784960
downvote count: 0
has comment: http://stackoverflow.com/comment/86585316
upvote count: 1
tagged with: pip
has title: SSL Problems in Mac using pip install
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49784960
score: 1
answer count: 1

ctypes
tags question: http://stackoverflow.com/q/49841577
tags question: http://stackoverflow.com/q/49915698
tags question: http://stackoverflow.com/q/49913956
tags question: http://stackoverflow.com/q/49878901
tags question: http://stackoverflow.com/q/49898751
tags question: http://stackoverflow.com/q/49860726
tags question: http://stackoverflow.com/q/49889218
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/49901708
tags question: http://stackoverflow.com/q/49913221
tags question: http://stackoverflow.com/q/49882728
tags question: http://stackoverflow.com/q/49803464
tags question: http://stackoverflow.com/q/49840133

http://stackoverflow.com/a/49914211
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49914046
score: 2
has comment: http://stackoverflow.com/comment/86844114
type: Answer
has comment: http://stackoverflow.com/comment/86844074
has comment: http://stackoverflow.com/comment/86843968
has body: EDIT What you actually want: &gt;&gt;&gt; n = 1 &gt;&gt;&gt; [x[i:i+n] for i in range(0, len(x)-n+1)] [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h'], ['i'], ['j']] &gt;&gt;&gt; n=3 &gt;&gt;&gt; [x[i:i+n] for i in range(0, len(x)-n+1)] [['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e'], ['d', 'e', 'f'], ['e', 'f', 'g'], ['f', 'g', 'h'], ['g', 'h', 'i'], ['h', 'i', 'j']] &gt;&gt;&gt; n = 4 &gt;&gt;&gt; [x[i:i+n] for i in range(0, len(x)-n+1)] [['a', 'b', 'c', 'd'], ['b', 'c', 'd', 'e'], ['c', 'd', 'e', 'f'], ['d', 'e', 'f', 'g'], ['e', 'f', 'g', 'h'], ['f', 'g', 'h', 'i'], ['g', 'h', 'i', 'j']] &gt;&gt;&gt; So, use the stop parameter to your advantage, using len(x)-n+1. Your code doesn't produce permutations, it is a sliding window. In which case, you can make it more elegant. Use the step parameter to range, pass the slice using indexing syntactic sugar instead of building a slice object explicitly, and use len(your_list) - 1 as the stop parameter: &gt;&gt;&gt; x ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] &gt;&gt;&gt; n = 2 &gt;&gt;&gt; [x[i:i+n] for i in range(0, len(x)-1, n)] [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'j']] &gt;&gt;&gt; n = 3 &gt;&gt;&gt; [x[i:i+n] for i in range(0, len(x)-1, n)] [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] Note, when len(seq) is not divisible by n, this might not be the behavior you want. In the above example, with n=3, we swallowed the last part because the division has a remainder of 1. Or consider the following: &gt;&gt;&gt; n = 4 &gt;&gt;&gt; [x[i:i+n] for i in range(0, len(x)-1, n)] [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j']] &gt;&gt;&gt; n = 1 &gt;&gt;&gt; [x[i:i+n] for i in range(0, len(x)-1, n)] [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h'], ['i']] In which case, you may want the more strict but also more clunky: &gt;&gt;&gt; n = 1 &gt;&gt;&gt; [x[i:i+n] for i in range(0, len(x)-n+1, n)] [['a'], ['b'], ['c'], ['d'], ['e'], ['f'], ['g'], ['h'], ['i'], ['j']] &gt;&gt…
accepted answer of: http://stackoverflow.com/q/49914046
has comment: http://stackoverflow.com/comment/86844757
has comment: http://stackoverflow.com/comment/86843992

http://stackoverflow.com/comment/86691609
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49838284
type: Comment
has text: You can write your program, and then use the at module to schedule it at a certain time if you're running linux. See https://askubuntu.com/questions/339298/conveniently-schedule-a-command-to-run-later

http://stackoverflow.com/comment/86840517
score: 0
comment on: http://stackoverflow.com/q/49912393
type: QuestionComment
type: Comment
has text: tried it and gives blank

http://stackoverflow.com/a/49909811
has body: Removing a Label to place a widget with another text consumes recourses in an unavoidable way, you only have to update the text. So you must add the label the first time and then update the text. On the other hand it is recommended that the name of variables, classes and functions are not the same. And try to avoid using global variables because they are difficult to debug. Making those changes we obtain the following code: from kivy.app import App from kivy.lang import Builder from kivy.uix.label import Label from kivy.uix.screenmanager import Screen class GameScreen(Screen): def __init__(self, **args): Screen.__init__(self, **args) self.money = 0 self.label = Label(text=str(self.money), color=(1,0,0,1), font_size=(45),size_hint=(0.2,0.1), pos_hint={"center_x":0.5, "center_y":0.9}) self.add_widget(self.label) def add_money(self): self.money += 1 self.label.text = str(self.money) Builder.load_string(''' &lt;GameScreen&gt;: name: "GameScreen" canvas: Color: rgb: 1, 1, 1 Rectangle: pos: self.pos size: self.size Button: size: self.texture_size on_release: root.add_money() text: "Press" font_size: 50 color: 1,1,1,1 background_color: (0,0,0,1) background_normal: "" background_down: "" size_hint: None, None pos_hint: {"center_x":0.5, "center_y":0.6} width: self.texture_size[0] + dp(10) height: self.texture_size[1] + dp(10) ''') class TestApp(App): def build(self): return GameScreen() if __name__ == '__main__': TestApp().run()
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49909495
has comment: http://stackoverflow.com/comment/86835911
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49909495

http://stackoverflow.com/comment/86658332
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49821485
has text: @Bahrom. Thanks :)
score: 1

http://stackoverflow.com/comment/138187273
comment on: http://stackoverflow.com/q/49817409
type: Comment
score: 0
type: QuestionComment
has text: Why wouldn't you just put foo in a .py file and import it?

http://stackoverflow.com/comment/86781287
type: Comment
score: 0
type: AnswerComment
has text: You probably meant: `(screenWidth // 2 - myText.get_width(), screenHeight // 2 - myText.get_height())`.
comment on: http://stackoverflow.com/a/49860925

http://stackoverflow.com/a/49777096
has comment: http://stackoverflow.com/comment/86569768
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49776490
has body: This may help you: result_dataframe = dataframe_name.groupby('state_code ').sum()

http://stackoverflow.com/comment/86824757
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49904109
has text: Possible duplicate of [Open web in new tab Selenium + Python](https://stackoverflow.com/questions/28431765/open-web-in-new-tab-selenium-python)

http://stackoverflow.com/q/49835838
favorite count: 0
has comment: http://stackoverflow.com/comment/86687040
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49836207
downvote count: 0
has comment: http://stackoverflow.com/comment/86687080
score: 1
accepted answer: http://stackoverflow.com/a/49836180
tagged with: python
has body: I'm trying to run train.py from, here. It is based on this tutorial. I wanted to find the confusion matrix, and added that after the last line in train.py: confusionMatrix = tf.confusion_matrix(labels=y_true_cls,predictions=y_pred_cls) with session.as_default(): print confusionMatrix.eval() I'm however getting the following error: InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'x' with dtype float and shape [?,128,128,3] [[Node: x = Placeholder[dtype=DT_FLOAT, shape=[?,128,128,3], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]] Why is that? How can I find the confusion matrix? Thanks.
has comment: http://stackoverflow.com/comment/86686778
has comment: http://stackoverflow.com/comment/86686782
type: Question
has comment: http://stackoverflow.com/comment/86686930
answer count: 2
tagged with: confusion-matrix
has title: tf.confusion_matrix and InvalidArgumentError
upvote count: 1
has answer: http://stackoverflow.com/a/49836207
has answer: http://stackoverflow.com/a/49836180
has comment: http://stackoverflow.com/comment/86686966
tagged with: tensorflow

http://stackoverflow.com/comment/94776339
type: Comment
comment on: http://stackoverflow.com/a/49997169
type: AnswerComment
score: 1
has text: @Birish You're wrong here. Refer [here](https://stackoverflow.com/questions/53966446/lstm-architecture-in-keras-implementation/53968886#53968886)

http://stackoverflow.com/comment/86622275
type: QuestionComment
comment on: http://stackoverflow.com/q/49802789
type: Comment
score: 0
has text: @Hai Vu yes the script finishes independently.

http://stackoverflow.com/comment/86718236
type: QuestionComment
comment on: http://stackoverflow.com/q/49851776
score: 0
has text: @LutzHorn tree = {} node is an item of tree
type: Comment

http://stackoverflow.com/q/49759495
has comment: http://stackoverflow.com/comment/86534158
type: Question
tagged with: reduce
has answer: http://stackoverflow.com/a/49760059
tagged with: python
has body: Here is my code : &gt;&gt;&gt; class MyClass() : ... def __init__( self, item ) : ... self.a = item["a"] ... self.b = item["b"] ... def __eq__(self, other ) : ... return self.a == other.a and self.b == other.b ... def myEqualityFunc(self,other) : ... return self.b == other.b ... def __str__(self) : ... return str( self.__dict__ ) ... &gt;&gt;&gt; t1 = MyClass({"a" : ["X1"] , "b" : [1,2] }) &gt;&gt;&gt; t2 = MyClass({"a" : ["X2"] , "b" : [1,2] }) &gt;&gt;&gt; t3 = MyClass({"a" : ["Y1"] , "b" : [3] }) &gt;&gt;&gt; &gt;&gt;&gt; l = [t1,t3,t2 ] &gt;&gt;&gt; for l_ in l : ... print l_ ... {'a': ['X1'], 'b': [1, 2]} {'a': ['Y1'], 'b': [3]} {'a': ['X2'], 'b': [1, 2]} What I am trying to do is find the objects in my list that are equal based on myEqualityFunc -> in my example these will be t1 and t2 since they have the same b attribute. I know that a is unique. Is there a more pythonic way than that : for outer_l in l: for inner_l in l : if outer_l.myEqualityFunc( inner_l ) and outer_l != inner_l : # remove inner_l from l since found and keep it in anotehr data structure. Ultimate goal is to end up with something like this but right now I am doing it in more than one steps : &gt;&gt;&gt; for r in result : ... print r ... {'a': ['X1' , 'X2'], 'b': [1, 2]} {'a': ['Y1'], 'b': [3]}
has title: python - find objects in a custom list that are equal based on custom function
has answer: http://stackoverflow.com/a/49759695
score: 0
tagged with: list
answer count: 2
tagged with: filter
type: UnansweredQuestion

http://stackoverflow.com/q/49875778
accepted answer: http://stackoverflow.com/a/49876176
has comment: http://stackoverflow.com/comment/86767048
has answer: http://stackoverflow.com/a/49876176
favorite count: 0
type: Question
tagged with: python-3.x
has title: Applying statistics methods on numpy arrays: unexpected results
score: 3
has comment: http://stackoverflow.com/comment/86767022
tagged with: python-internals
has comment: http://stackoverflow.com/comment/86767035
has body: Please explain. import statistics x = [0,1] statistics.mean(x) ## 0.5 But: import numpy import statistics x = numpy.array([0,1]) statistics.mean(x) ## 0 I'm pretty sure it's a basic, well-known, over-discussed issue: please link to a duplicate, as I couldn't find one.
tagged with: python
has comment: http://stackoverflow.com/comment/86767043
tagged with: statistics
tagged with: numpy
type: AnsweredQuestion
upvote count: 3
downvote count: 0
answer count: 1

list
tags question: http://stackoverflow.com/q/49880210
tags question: http://stackoverflow.com/q/49770819
tags question: http://stackoverflow.com/q/49888416
type: Tag
tags question: http://stackoverflow.com/q/49849355
tags question: http://stackoverflow.com/q/49837899
tags question: http://stackoverflow.com/q/49772590
tags question: http://stackoverflow.com/q/49773486
tags question: http://stackoverflow.com/q/49770284
tags question: http://stackoverflow.com/q/49875924
tags question: http://stackoverflow.com/q/49851375
tags question: http://stackoverflow.com/q/49796271
tags question: http://stackoverflow.com/q/49914046
tags question: http://stackoverflow.com/q/49880579
tags question: http://stackoverflow.com/q/49803550
tags question: http://stackoverflow.com/q/49832443
tags question: http://stackoverflow.com/q/49839622
tags question: http://stackoverflow.com/q/49842652
tags question: http://stackoverflow.com/q/49874287
tags question: http://stackoverflow.com/q/49874001
tags question: http://stackoverflow.com/q/49879369
tags question: http://stackoverflow.com/q/49848261
tags question: http://stackoverflow.com/q/49781476
tags question: http://stackoverflow.com/q/49786967
tags question: http://stackoverflow.com/q/49866765
tags question: http://stackoverflow.com/q/49874999
tags question: http://stackoverflow.com/q/49818754
tags question: http://stackoverflow.com/q/49823714
tags question: http://stackoverflow.com/q/49885478
tags question: http://stackoverflow.com/q/49879111
tags question: http://stackoverflow.com/q/49912743
tags question: http://stackoverflow.com/q/49851545
tags question: http://stackoverflow.com/q/49848563
tags question: http://stackoverflow.com/q/49870482
tags question: http://stackoverflow.com/q/49807720
tags question: http://stackoverflow.com/q/49765985
tags question: http://stackoverflow.com/q/49827330
tags question: http://stackoverflow.com/q/49888412
tags question: http://stackoverflow.com/q/49801952
tags question: http://stackoverflow.com/q/49911524
tags question: http://stackoverflow.com/q/49767087
tags question: http://stackoverflow.com/q/49760402
tags question: http://stackoverflow.com/q/49842547
tags question: http://stackoverflow.com/q/49895866
tags question: http://stackoverflow.com/q/49818868
tags question: http://stackoverflow.com/q/49835925
tags question: http://stackoverflow.com/q/49908859
tags question: http://stackoverflow.com/q/49769796
tags question: http://stackoverflow.com/q/49762795
tags question: http://stackoverflow.com/q/49916268
tags question: http://stackoverflow.com/q/49776834
tags question: http://stackoverflow.com/q/49890532
tags question: http://stackoverflow.com/q/49900511
tags question: http://stackoverflow.com/q/49786624
tags question: http://stackoverflow.com/q/49887524
tags question: http://stackoverflow.com/q/49773027
tags question: http://stackoverflow.com/q/49777262
tags question: http://stackoverflow.com/q/49787852
tags question: http://stackoverflow.com/q/49895760
tags question: http://stackoverflow.com/q/49835547
tags question: http://stackoverflow.com/q/49815235
tags question: http://stackoverflow.com/q/49885943
tags question: http://stackoverflow.com/q/49902298
tags question: http://stackoverflow.com/q/49843167
tags question: http://stackoverflow.com/q/49777249
tags question: http://stackoverflow.com/q/49896864
tags question: http://stackoverflow.com/q/49845034
tags question: http://stackoverflow.com/q/49909792
tags question: http://stackoverflow.com/q/49773008
tags question: http://stackoverflow.com/q/49848688
tags question: http://stackoverflow.com/q/49872752
tags question: http://stackoverflow.com/q/49859091
tags question: http://stackoverflow.com/q/49763716
tags question: http://stackoverflow.com/q/49791658
tags question: http://stackoverflow.com/q/49792393
tags question: http://stackoverflow.com/q/49874965
tags question: http://stackoverflow.com/q/49763476
tags question: http://stackoverflow.com/q/49778996
tags question: http://stackoverflow.com/q/49859825
tags question: http://stackoverflow.com/q/49866044

http://stackoverflow.com/q/49853470
has title: How to convert .py script and .ui file with images to .exe
has body: I wrote a program in Python that includes external files, including images and a GUI .ui file. I want to convert the Python script to a single executable (.exe) file using PyInstaller. When I try to open the .exe file, the program does not open.
score: -5
has answer: http://stackoverflow.com/a/49883168
upvote count: 0
type: UnansweredQuestion
answer count: 1
favorite count: 0
type: Question
downvote count: 5
tagged with: python

http://stackoverflow.com/comment/86695114
has text: @hpaulj What problems do you anticipate in reading a pair of values from a memmapped `indptr` and getting a slice each from memmapped `data` and `indices`
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49835342

http://stackoverflow.com/q/49822609
has comment: http://stackoverflow.com/comment/86662110
score: 0
has comment: http://stackoverflow.com/comment/86661173
tagged with: regex
linked to: http://stackoverflow.com/q/42742810
type: Question
has comment: http://stackoverflow.com/comment/86663781
has comment: http://stackoverflow.com/comment/86660847
answer count: 2
has comment: http://stackoverflow.com/comment/86661861
accepted answer: http://stackoverflow.com/a/49823284
has title: Return list of comments with list of words in list of sentences
has answer: http://stackoverflow.com/a/49823284
linked to: http://stackoverflow.com/q/3640359
possible better answer: http://stackoverflow.com/a/49823374
tagged with: python
has body: I have a long (1.5m) list of sentences and a similarly long list of words that I am looking for within the list of sentences. For example: list_of_words = ['Turin', 'Milan'] list_of_sents = ['This is a sent about turin.', 'This is a sent about manufacturing.'] I would like to have a function that is able to return those sentences that contain the target word without alphanumeric characters next to them. In other words, only the first of the sentences above should match. I have developed the function below but it takes too long to parse through each the millions of words and sentences. I was wondering if there is a package or alternative that could mitigate this computational intensity. def find_target_sents(list_of_words, list_of_sents): target_sents = [] i, j = 0, 0 word_len = len(list_of_words) sent_len = len(list_of_sents) for word in list_of_words: i += 1 for sent in list_of_sents: j += 1 print('%s out of %s words and %s out of %s sentences' % (j, word_len , i, sent_len)) match = re.compile(r'\%s\b' % word, re.I) y = match.search(sent) if y != None: print(sent) t = (word, sentence) target_sent.append(t) print(target_sent)
has answer: http://stackoverflow.com/a/49823374
type: AnsweredQuestion

http://stackoverflow.com/a/49817150
has body: The problem is this line: change = 'UPDATE batch SET ? WHERE ?' (ToThis, ChangeThis) You're defining a string literal, then trying to call it like a function with the arguments (ToThis, ChangeThis). That's never going to work, since as the exception says, 'str' objects are not callable. There's no need for the parameters to be on that line. Add them instead to the cur.execute() call: change = 'UPDATE batch SET ? WHERE ?' cur.execute(change, (ToThis, ChangeThis)) ...or just cur.execute('UPDATE batch SET ? WHERE ?', (ToThis, ChangeThis))
accepted answer of: http://stackoverflow.com/q/49816092
type: Answer
answers question: http://stackoverflow.com/q/49816092
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49837383
linked to: http://stackoverflow.com/q/7336802
tagged with: pygame
score: 1
downvote count: 1
linked to: http://stackoverflow.com/q/10113383
has body: So I am making a small game using Pygame just to get some experience. For this example, we'll just say I have two files(a.py and b.py). In a.py I have a variable called 'score'. I to be able to change the value of score from both a.py and b.py. I know to access score from my class in b.py I would simply need to put in the line import a at the start of b.py. The problem I'm having is that a.py imports a class from b.py. So a imports b which imports a. Obviously that doesn't work. My work-around to this was to create a separate file(let's say c.py) and keep the score variable in there. Then a will import b and c, b will just import c, and all is well. This seems like bad practice though, and I feel like there must be some other way to do this, though I haven't found one. So my question is a) Is this considered a 'wrong' way to do this? and b) Is there a better way?
favorite count: 0
type: Question
has title: Making a variable available to multiple files in Python
has comment: http://stackoverflow.com/comment/86690090
has comment: http://stackoverflow.com/comment/86690128
duplicate of: http://stackoverflow.com/q/7336802
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86690106
tagged with: python
has comment: http://stackoverflow.com/comment/86690088
has comment: http://stackoverflow.com/comment/86690115
linked to: http://stackoverflow.com/q/31429641
answer count: 0
linked to: http://stackoverflow.com/q/40035593

http://stackoverflow.com/a/49873577
answers question: http://stackoverflow.com/q/49863206
has comment: http://stackoverflow.com/comment/87330004
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/87328019
has comment: http://stackoverflow.com/comment/87329356
score: 1
has body: You can't do changes before calling Gtk.main(), because at that point, your application is not even shown. If you want a 2 seconds delay, use GLib.timeout_add_seconds, and pass the object you want to modify (your label) as the data parameter. The function parameter you need to pass is the callback that will be called after those 2 seconds. In that callback, you just call set_label (or your label_bye) on the label you have passed as the data parameter, and you're done. Another thing is that you should create the label and add it to your widget tree in your constructor, not in your label_hi method. label_hi and label_bye just need to call set_label to change the message displayed.
type: Answer

for-loop
tags question: http://stackoverflow.com/q/49863266
tags question: http://stackoverflow.com/q/49837521
tags question: http://stackoverflow.com/q/49838357
tags question: http://stackoverflow.com/q/49823714
tags question: http://stackoverflow.com/q/49881196
tags question: http://stackoverflow.com/q/49793652
tags question: http://stackoverflow.com/q/49807720
tags question: http://stackoverflow.com/q/49894880
tags question: http://stackoverflow.com/q/49898985
tags question: http://stackoverflow.com/q/49829320
tags question: http://stackoverflow.com/q/49904121
tags question: http://stackoverflow.com/q/49803339
tags question: http://stackoverflow.com/q/49836956
tags question: http://stackoverflow.com/q/49819657
tags question: http://stackoverflow.com/q/49801140
tags question: http://stackoverflow.com/q/49862726
tags question: http://stackoverflow.com/q/49834317
tags question: http://stackoverflow.com/q/49857185
tags question: http://stackoverflow.com/q/49763225
tags question: http://stackoverflow.com/q/49784279
tags question: http://stackoverflow.com/q/49846437
tags question: http://stackoverflow.com/q/49765676
type: Tag
tags question: http://stackoverflow.com/q/49850895
tags question: http://stackoverflow.com/q/49783145
tags question: http://stackoverflow.com/q/49902438
tags question: http://stackoverflow.com/q/49806078
tag name: for-loop
tags question: http://stackoverflow.com/q/49774174
tags question: http://stackoverflow.com/q/49783594
tags question: http://stackoverflow.com/q/49908354
tags question: http://stackoverflow.com/q/49847272
tags question: http://stackoverflow.com/q/49911183
tags question: http://stackoverflow.com/q/49901216
tags question: http://stackoverflow.com/q/49846916
tags question: http://stackoverflow.com/q/49821663
tags question: http://stackoverflow.com/q/49839750
tags question: http://stackoverflow.com/q/49827007

http://stackoverflow.com/comment/86533550
score: 0
type: Comment
type: QuestionComment
has text: See my answer to a similar question, https://stackoverflow.com/a/49570796/7811673. But in this case i'd use `urllib` instead of calling `curl`.
comment on: http://stackoverflow.com/q/49758988

music21
type: Tag
tags question: http://stackoverflow.com/q/49782895
tag name: music21

http://stackoverflow.com/comment/86687620
has text: To get a "current state" for your log, you need to copy the current list. Your first line inside the outer loop should be `log.append(A[:])`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49836243
score: 1

http://stackoverflow.com/a/49878910
upvote count: 4
has body: You can use only one groupby for improve performance: df = (cat_df['depth'].ne(0) .groupby(cat_df['category']) .value_counts() .unstack(fill_value=0) .rename(columns={0:'depth=0', 1:'depth&gt;0'}) .assign(total=lambda x: x.sum(axis=1)) .reindex(columns=['total','depth=0','depth&gt;0'])) print (df) depth total depth=0 depth&gt;0 category food 3 1 2 school 3 2 1 sport 1 0 1 Explanation: First compare depth columns by not equal Series.ne (!=) groupby by column category with SeriesGroupBy.value_counts Reshape by unstack Rename columns by dictionary Create new total column by assign For custom order of columns add reindex EDIT: cat_df = pd.DataFrame({'category': ['food', 'food', 'sport', 'food', 'school', 'school', 'school'], 'depth': [0.0, 1.0, 1.0, 3.0, 0.0, 0.0, 1.0], 'num_of_likes': [10, 10, 10, 20, 20, 20, 20]}) print (cat_df) category depth num_of_likes 0 food 0.0 10 1 food 1.0 10 2 sport 1.0 10 3 food 3.0 20 4 school 0.0 20 5 school 0.0 20 6 school 1.0 20 df = (cat_df['depth'].ne(0) .groupby([cat_df['num_of_likes'], cat_df['category']]) .value_counts() .unstack(fill_value=0) .rename(columns={0:'depth=0', 1:'depth&gt;0'}) .assign(total=lambda x: x.sum(axis=1)) .reindex(columns=['total','depth=0','depth&gt;0']) .reset_index() .rename_axis(None, axis=1) ) print (df) num_of_likes category total depth=0 depth&gt;0 0 10 food 2 1 1 1 10 sport 1 0 1 2 20 food 1 0 1 3 20 school 3 2 1 EDIT1: s = cat_df.groupby('category')['num_of_likes'].sum() print (s) category food 40 school 60 sport 10 Name: num_of_likes, dtype: int64 df = (cat_df['depth'].ne(0) .groupby(cat_df['category']) .value_counts() .unstack(fill_value=0) .rename(columns={0:'depth=0', 1:'depth&gt;0'}) .assign(total=lambda x: x.sum(axis=1)) .reindex(columns=['total','depth=0','depth&gt;0']) .reset_index() .rename_axis(None, axis=1) .assign(num_of_likes=lambda x: x['category'].map(s)) ) print (df) category total depth=0 depth&gt;0 num_of_likes 0 food 3 1 2 40 1 school 3 2 1 60 2 sport 1 0 1 10
answers question: http://stackoverflow.com/q/49878814
type: AcceptedAnswer
type: Answer
score: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49878814

http://stackoverflow.com/comment/86751975
has text: Are you sure you're allocating a dense array? Run `similarities.count_nonzero()` and tell us what it returns.
comment on: http://stackoverflow.com/q/49868167
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86807106
type: Comment
type: QuestionComment
score: 0
has text: Comparing issue tracker to SO, well
comment on: http://stackoverflow.com/q/49869058

http://stackoverflow.com/a/49880446
accepted answer of: http://stackoverflow.com/q/49880375
type: AcceptedAnswer
score: 10
upvote count: 10
answers question: http://stackoverflow.com/q/49880375
has comment: http://stackoverflow.com/comment/86800465
has comment: http://stackoverflow.com/comment/86800617
has body: It is possible, but ploting timedelta is not supported yet natively. df['Object1'] = pd.to_timedelta(df['Object1'], unit='s') df['Object2'] = pd.to_timedelta(df['Object2'], unit='s') Or: cols = ['Object1', 'Object2'] df[cols] = df[cols].apply(lambda x: pd.to_timedelta(x, unit='s')) print (df) day Object1 Object2 0 2017-01-01 01:40:00 00:20:34 But is possible it by FuncFormatter: df = pd.DataFrame({'Object1': [6000, 4000, 3000], 'Object2':[3000,5000,2110]}) import matplotlib.ticker as tkr import datetime def func(x, pos): return str(datetime.timedelta(seconds=x)) fmt = tkr.FuncFormatter(func) ax = df.plot(x='Object1', y='Object2', rot=90) ax.xaxis.set_major_formatter(fmt) ax.yaxis.set_major_formatter(fmt)
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86776897

http://stackoverflow.com/comment/86838562
score: 0
type: Comment
has text: For Eg. model.add(Dense(1)) is my final layer. How do i add min, max constraints?
type: QuestionComment
comment on: http://stackoverflow.com/q/49911206

http://stackoverflow.com/comment/86697371
type: QuestionComment
comment on: http://stackoverflow.com/q/49839558
type: Comment
score: 0
has text: @JimmyJoe for that I believe you need to go call native window API. because listen to a keypress on background service can be dangerous use. Also, you will be required to run your app under admin privileges.

http://stackoverflow.com/a/49799742
has body: I don't think you can do a virtualenv of a Python version you don't have. What you can do is one of these options: If you want to test your code in several versions of Python, the right way to go is Tox. If you want multiples python installations available in your system, I recommend you asdf for Python.
answers question: http://stackoverflow.com/q/49794432
downvote count: 1
has comment: http://stackoverflow.com/comment/86614733
upvote count: 0
type: Answer
score: -1

http://stackoverflow.com/a/69586997
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49823033
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49823033
has body: As commented by @darthbith, using the --use-local flag with the package name, conda install -n my_env --use-local my_pkg works as intended. Using a path to a tarball directly triggers Conda to install without dependencies.
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/49864679
downvote count: 0
tagged with: python
has body: Creating a lambda function to calculate weighted average and sending that to a dictionary. wm = lambda x: np.average(x, weights=df.loc[x.index, 'WEIGHTS']) # Define a dictionary with the functions to apply for a given column: f = {'DRESS_AMT': 'max', 'FACE_AMT': 'sum', 'Other_AMT': {'weighted_mean' : wm}} # Groupby and aggregate with dictionary: df2=df.groupby(['ID','COL1'], as_index=False).agg(f) This code works but the weighted average lambda function fails if the weights add up to 0 ZeroDivisionError. In these case(s) I want the output 'Other_AMT' to just be 0. I read a document on using np.ma.average (masked average) but could not understand how to implement it
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75132667
possible better answer: http://stackoverflow.com/a/75132667
tagged with: pandas
has answer: http://stackoverflow.com/a/49864754
accepted answer: http://stackoverflow.com/a/49864754
tagged with: divide-by-zero
tagged with: weighted-average
has title: Pandas/numpy weighted average ZeroDivisionError
favorite count: 0
type: Question
tagged with: numpy
answer count: 2
score: 5
upvote count: 5

http://stackoverflow.com/q/49816256
answer count: 0
linked to: http://stackoverflow.com/q/46131410
tagged with: machine-learning
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86648543
tagged with: deep-learning
linked to: http://stackoverflow.com/q/45562755
score: 0
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86650508
has body: I followed these two posts to understand about restoring a saved model and then extracting variables from it: Extracting weights values from a tensorflow model checkpoint How to examine the feature weights of a Tensorflow LinearClassifier? But now I am unable to understand as to what do those variables mean exactly and how to understand the relative importance given by the model to the features in the learning process? Below is the output of tf.train.list_variables and tf.train.load_variables (respectively) from my code: &gt;&gt; tf.train.list_variables('./dnn_fe_trial1/model.ckpt-1') [('dnn/hiddenlayer_0/biases', [50]), ('dnn/hiddenlayer_0/biases/enlayer_0/biases/part_0/Adam', [50]), ('dnn/hiddenlayer_0/biases/enlayer_0/biases/part_0/Adam_1', [50]), ('dnn/hiddenlayer_0/weights', [61, 50]), ('dnn/hiddenlayer_0/weights/nlayer_0/weights/part_0/Adam', [61, 50]), ('dnn/hiddenlayer_0/weights/nlayer_0/weights/part_0/Adam_1', [61, 50]), ('dnn/input_from_feature_columns/brand_embedding/weights', [10000, 16]), ('dnn/input_from_feature_columns/brand_embedding/weights/mbedding/weights/part_0/Adam', [10000, 16]), ('dnn/input_from_feature_columns/brand_embedding/weights/mbedding/weights/part_0/Adam_1', [10000, 16]), ('dnn/input_from_feature_columns/city_embedding/weights', [12, 3]), ('dnn/input_from_feature_columns/city_embedding/weights/mbedding/weights/part_0/Adam', [12, 3]), ('dnn/input_from_feature_columns/city_embedding/weights/mbedding/weights/part_0/Adam_1', [12, 3]), ('dnn/input_from_feature_columns/dow_embedding/weights', [7, 3]), ('dnn/input_from_feature_columns/dow_embedding/weights/mbedding/weights/part_0/Adam', [7, 3]), ('dnn/input_from_feature_columns/dow_embedding/weights/mbedding/weights/part_0/Adam_1', [7, 3]), ('dnn/input_from_feature_columns/l_cat_embedding/weights', [11, 3]), ('dnn/input_from_feature_columns/l_cat_embedding/weights/mbedding/weights/part_0/Adam', [11, 3]), ('dnn/input_from_feature_columns/l_cat_embedding/weights/mbedding/weights/part_0/Adam_1'…
type: Question
tagged with: regression
has title: How to extract relative importance of features from a tensorflow DNNRegressor model?

http://stackoverflow.com/comment/86605101
comment on: http://stackoverflow.com/q/49794899
score: 0
type: Comment
type: QuestionComment
has text: Awesome. Yes it is a duplicate, have solved this by using `synchronize_session=False` in the delete function.

http://stackoverflow.com/a/49778248
has body: I'm not certain this is the most elegant of solutions, but you could do: to_remove = ['foo', 'bar'] df = pd.DataFrame({'Text': [ 'spam foo&amp; eggs', 'foo bar eggs bacon and lettuce', 'spam and foo eggs' ]}) df['Text'].str.replace('|'.join(to_remove), '')
answers question: http://stackoverflow.com/q/49778025
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49787904
type: Question
has title: How do I edit the /etc/hosts file in fabric python library?
has answer: http://stackoverflow.com/a/50084829
has body: I want to ensure an entry in the /etc/hosts file on all target hosts is correct in the /etc/hosts file with the fabric. How do I do that?
type: UnansweredQuestion
answer count: 1
tagged with: python
score: 0

http://stackoverflow.com/comment/86677470
score: 0
type: QuestionComment
has text: Abhilash just remove those square brackets for the column names in your code.
comment on: http://stackoverflow.com/q/49830394
type: Comment

http://stackoverflow.com/a/49876098
answers question: http://stackoverflow.com/q/49869971
type: AcceptedAnswer
has body: You can use a custom function to match your requirements. For example, if you want to scrape this page (current page) and get all links that don't start with https://stackoverflow.com, you can use this: import requests from bs4 import BeautifulSoup def get_links(root, html): soup = BeautifulSoup(html, 'lxml') for link in soup.find_all('a', href=lambda h: h and h.startswith('http') and not h.startswith(root)): yield link['href'] r = requests.get('https://stackoverflow.com/questions/49869971/extracting-non-local-links-beautiful-soup') base = 'https://stackoverflow.com' for link in get_links(base, r.text): print(link) Partial output: https://chat.stackoverflow.com https://meta.stackoverflow.com https://stackexchange.com/sites https://stackoverflow.blog https://meta.stackoverflow.com https://www.stackoverflowbusiness.com/?ref=topbar_help https://stackexchange.com/users/?tab=inbox https://stackexchange.com/users/?tab=reputation https://stackexchange.com https://plus.google.com/share? You can modify the function lambda h: h and h.startswith('http') and not h.startswith(root) as per your needs. Also, in your code, you use re module for this line: soup.find_all('a', href=re.compile('https://www\.eecs\.mitx\.edu/')) You can do it without using re with the help of CSS selector with partial match (^). For example: soup.select('a[href^="https://www.eecs.mitx.edu/"]')
downvote count: 0
score: 1
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49869971

http://stackoverflow.com/q/49804961
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86625616
tagged with: postgresql
has title: Creating Multiple Tables Using Psycopg2
tagged with: python
has answer: http://stackoverflow.com/a/49805506
has comment: http://stackoverflow.com/comment/86625116
score: 2
has comment: http://stackoverflow.com/comment/86625839
upvote count: 2
has body: I'm trying to create and import multiple (4000) csv files into my postgres database using psycopg2. All the csv files have the same column names and types. I just can't figure out how to order this efficiently. Python 3.5, Postgre - 9.5.12 Problems: .format is not working properly (not replacing '%s' with sec_name) Should I specify the columns I want to insert into or use copy_from Can I simplfy this process anymore import psycopg2 import os conn = psycopg2.connect("dbname=postgres user=postgres") cur = conn.curser() # file_dir == directory containing all the .csv sec_files = os.listdir("file_dir") for files in sec_files: # Cuts off all whitespace and .csv sec_name = ''.join(files.split())[:-4] cur.execute(''' CREATE TABLE '%s' ( Date NOT NULL UNIQUE DATE PRIMARY KEY col2 FLOAT NOT NULL col3 FLOAT NOT NULL col4 FLOAT NOT NULL col5 FLOAT NOT NULL col6 FLOAT NOT NULL col7 INTEGER NOT NULL )''').format(sec_name) print("Table created ",sec_name) with open(os.path.abspath(files),'r') as f: next(f) for row in reader: cur.copy_from(f,sec_name, sep=',') conn.commit() print('Data inserted into ', sec_name, ' completed')
type: UnansweredQuestion
downvote count: 0
answer count: 1
tagged with: psycopg2

tensorflow-datasets
tags question: http://stackoverflow.com/q/49853718
tags question: http://stackoverflow.com/q/49762314
tag name: tensorflow-datasets
tags question: http://stackoverflow.com/q/49840100
type: Tag
tags question: http://stackoverflow.com/q/49899526
tags question: http://stackoverflow.com/q/49799998
tags question: http://stackoverflow.com/q/49797450
tags question: http://stackoverflow.com/q/49890820
tags question: http://stackoverflow.com/q/49876643

http://stackoverflow.com/comment/86638672
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49809032
has text: I can't reproduce the error. I was just testing on cpu and got `[-1, -1], (train_loss: 2.3224891445520894, train error: 0.8735254156010229) , (test loss: 2.3210103873965107, test error: 0.8691653481012658) about to start training [0, 391], (train_loss: 1.8232954066732656, train error: 0.6340393222506394) , (test loss: 1.7517535837390754, test error: 0.6045292721518988) ...`. The loss makes sense: If you have 10 classes with random guessing you will be right ~ 1/10 of the time resulting in a crossentropy loss of `ln(-1/10) = 2.3`. So the error should be in the `error_criterion` function.

http://stackoverflow.com/comment/86775610
type: Comment
has text: You need for loop then : -)
type: QuestionComment
comment on: http://stackoverflow.com/q/49879942
score: 0

http://stackoverflow.com/comment/86603083
has text: Hmm, wouldn't redirecting stderr in the `system` call to a file of your choice be enough then?
comment on: http://stackoverflow.com/q/49793399
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49808381
type: UnansweredQuestion
answer count: 1
tagged with: google-chrome
type: Question
has body: I am new to python and webscraping, I want to retrieve some information on a website but some of the information is displayed on a popup window. The problem I'm having now is switching from the main page to the popup window to get the html and then switch back to the main page. In order words after getting some information from page A, i need to switch to this link https://www.dibbs.bsm.dla.mil/Refs/cage.aspx?Cage=0VET6 to obtain the company name and then switch back to page A this a section of the code that I have for batch in containers: try: print(" ") awardid = batch.find('a', text=True).text ordernumber = batch.find_all('span')[1].text cagecode = batch.find_all('span')[6].text price = batch.find_all('span')[7].text date = batch.find_all('span')[8].text NSN = batch.find_all('span')[10].text Nomenclature= batch.find_all('span')[11].text purchasereq = batch.find_all('span')[12].text if cagecode : cagelink = 'https://www.dibbs.bsm.dla.mil/Refs/cage.aspx?Cage='+cagecode #switch to pop-up window try: driver.execute_script("window.open("+cagelink+",'new window')") except Exception as e: print("error from driver ", str(e)) continue try: cagesoup = BeautifulSoup(driver.page_source,"lxml") bodycontainer = cagesoup.find("tbody") print('cage code body',bodycontainer) except Exception as e: print("error from soup ", str(e)) continue except Exception as e: print(colorama.Fore.MAGENTA + "award error.."+ str(e) ) # print(container1) continue except Exception as e: continue the problem I have now is that i am getting an error that I am missing a ) at the end of the argument here driver.execute_script("window.open("+cagelink+",'new window')") and when I try to remove the cagelink and use https://www.dibbs.bsm.dla.mil/Refs/cage.aspx?Cage=0VET6 it display none. what am I doing wrongly and how can I switch between the windows to obtain the company name on the popup window?
tagged with: python
has answer: http://stackoverflow.com/a/49808971
has title: switching between windows using chrome webdriver is not working
tagged with: selenium-webdriver
score: 0

http://stackoverflow.com/comment/86891975
comment on: http://stackoverflow.com/a/49812722
type: AnswerComment
has text: Still it shows same error. Can you please check once and edit it. Thanks.
score: 0
type: Comment

http://stackoverflow.com/comment/86633989
comment on: http://stackoverflow.com/a/49809682
type: Comment
has text: Since `item` is not used anywhere it would be better to write `mylist = [True for _ in mylist]`
type: AnswerComment
score: 1

http://stackoverflow.com/comment/106980882
score: 0
type: Comment
type: QuestionComment
has text: @PatrickHaugh `str.join` can still be used by itself as unbounded method, `str.join(", ", ["a", "b", "c"])` will work just fine
comment on: http://stackoverflow.com/q/49837475

http://stackoverflow.com/q/49876077
has body: Say I have the following Excel file: A B C 0 - - - 1 Start - - 2 3 2 4 3 7 8 4 4 11 2 17 I want to read the file in a dataframe making sure that I start to read it below the row where the Start value is. Attention: the Start value is not always located in the same row, so if I were to use: import pandas as pd xls = pd.ExcelFile('C:\Users\MyFolder\MyFile.xlsx') df = xls.parse('Sheet1', skiprows=4, index_col=None) this would fail as skiprows needs to be fixed. Is there any workaround to make sure that xls.parse finds the string value instead of the row number?
tagged with: python
possible better answer: http://stackoverflow.com/a/63019714
tagged with: excel
has title: Pandas: reading Excel file starting from the row below that with a specific value
tagged with: pandas
type: AnsweredQuestion
answer count: 3
downvote count: 0
upvote count: 10
accepted answer: http://stackoverflow.com/a/49877673
score: 10
has answer: http://stackoverflow.com/a/49876908
linked to: http://stackoverflow.com/q/42386629
favorite count: 0
has answer: http://stackoverflow.com/a/63019714
has answer: http://stackoverflow.com/a/49877673
type: Question

http://stackoverflow.com/comment/86800166
score: 0
type: Comment
has text: I'm unable to reproduce it with the version from Github; the fact that your code is asking for an 'http' address, makes me think you are using an old version. If that's not the case, do you have an up-to-date system, with a recent set of CAs?
type: QuestionComment
comment on: http://stackoverflow.com/q/49889788

http://stackoverflow.com/q/49866190
has answer: http://stackoverflow.com/a/49873335
has comment: http://stackoverflow.com/comment/86747878
has body: I tried to get the indices of elements in a list, which summed of the value equal to certain number. a = [50, 50, 50, 50, 75, 75] b = 125 in the example above, I am looking for indices of element in list a that summed values equal to b (=125). indices combination that I am looking for is [0, 4], corresponding to the first number 50 and the first number 75. I found a way by first creating possible combinations of the element in list a using itertools.combinations and then filter all combination that summed value equal to 125. it leads to indices [0,4], [1,4], [2,4],... This is quite problematic for list a that has many elements. is there any simple way in python? thank you.
has comment: http://stackoverflow.com/comment/86747963
favorite count: 0
type: Question
tagged with: selection
has comment: http://stackoverflow.com/comment/86748352
type: UnansweredQuestion
score: -2
downvote count: 2
has title: Get indices of elements in a list that satisfies certain sum value
tagged with: python
has comment: http://stackoverflow.com/comment/86747899
has answer: http://stackoverflow.com/a/74869379
tagged with: conditional-statements
tagged with: list
answer count: 2
linked to: http://stackoverflow.com/q/6012963
upvote count: 0

http://stackoverflow.com/q/49827518
has comment: http://stackoverflow.com/comment/86670551
tagged with: python
has comment: http://stackoverflow.com/comment/86671989
has title: What does the return value of gc.collect() actually mean?
type: Question
has comment: http://stackoverflow.com/comment/118870311
has comment: http://stackoverflow.com/comment/86670578
type: UnansweredQuestion
downvote count: 9
has answer: http://stackoverflow.com/a/49827616
answer count: 1
tagged with: garbage-collection
has body: When I do gc.collect() in my Python script, it returns values like 86, 14, etc. I understand that this call performs garbage collection and I've already gone through the documentation here. But can someone explain through an example what do the numbers actually mean?
score: 29
favorite count: 0
has comment: http://stackoverflow.com/comment/86965695
upvote count: 38

http://stackoverflow.com/comment/86775805
type: Comment
type: QuestionComment
has text: What is `LogonDialog`? What version of Python, wxPython, and Twisted? What OS and wx backend?
comment on: http://stackoverflow.com/q/49871639
score: 0

http://stackoverflow.com/q/49779905
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86580751
score: 1
has body: I'm currently using Selenium and Beautiful soup to grab all the HTML data from a website. Currently all the data is stored in a variable in Python. soup = BeautifulSoup(driver.page_source, 'lxml') What is the best way to look for the occurrence of two different words, either exactly "Open" or exactly "Closed" and print them to the console in the order that they are found. I tried the following: for node in soup.find_all(text=lambda x: x and "Open" in x): print(node) But how would I also get it to search for exactly "Closed" Updated code I have: soup = BeautifulSoup(driver.page_source, 'lxml') status = soup.find('div', attrs={"class":"pagebodydiv"}) with open("status.txt", "w") as file: for node in status.find_all(text=lambda t: t in ('Open', 'Closed')): file.write(node.encode("utf-8")+"\n")
has answer: http://stackoverflow.com/a/49780254
accepted answer: http://stackoverflow.com/a/49780254
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/86575261
has title: BeautifulSoup find two different strings
downvote count: 0
upvote count: 1
tagged with: python
answer count: 1
type: Question

http://stackoverflow.com/q/49885711
tagged with: django
tagged with: python
answer count: 1
downvote count: 0
score: 1
upvote count: 1
has body: I am using python3.6 and Django 2.0.3 on Ubuntu 17.10. I'm a bit new to Django and trying to understand it. I have a table with some input fields in the html page where the users will enter data. My AJAX code below gets the data from the table rows and passes it to django view. CSRF is handled as per the django documentation as I have no form in my html. Here is my AJAX code (using jQuery) $(document).ready(function() { var table = $('#example').DataTable(); $('button').click( function() { var TableData = new Array(); $('#example tr').each(function(row, tr){ TableData[row]={ "id" : $(tr).find('td:eq(0)').text() , "student_name" :$(tr).find('td:eq(1)').text() , "marks" : $(tr).find('td:eq(2) input', this).val() , "is_present" : $(tr).find('td:eq(3) select', this).val() } }); TableData.shift(); // first row will be empty - so remove TableData = JSON.stringify(TableData); alert(TableData); $.ajax({ type: "POST", url: "{% url 'result:ajax_update_result' %}", dataType: 'json', data: TableData, success: function(msg){ alert(msg); } }); return false; } ); }); Here is the result of the alert call in the above AJAX. The same data is passed to the djago view code which handles this AJAX call. [{"id":"1","student_name":"Test Student","marks":"0.00","is_present":"1"},{"id":"2","student_name":"Test Student3","marks":"0.00","is_present":"1"}] Below is my django view for the above AJAX call. import json def save_result(request): table_data = json.dumps(request.GET.get('TableData')) print(table_data) return render(request, 'data/dummy.html', {'msg': 'Data Saved.'}) The django console prints null for the above print(table_data) Please note: I used json.loads in the django view code and got a type error. I am expecting the data from the AJAX call to be passed to the django function and the data printed in console as dictionary.
tagged with: jquery
favorite count: 0
has answer: http://stackoverflow.com/a/49885796
type: Question
tagged with: ajax
tagged with: python-3.x
type: UnansweredQuestion
has title: passing JSON data to django using AJAX

http://stackoverflow.com/q/49826208
type: AnsweredQuestion
has body: Have an assignment where I must sort a list of names and then display it. Then have the user input one of the names and searches the array and displays the ordered number in the array. I pretty much have everything done but I cannot get that part to work. If I type in one of the names, it just returns the same name but doesn't give me the ordered number in the index. How can the code be changed so it correctly displays the number of the name that is input into the program? def main(): SIZE = 10 names = ['Ross Harrison', 'Hannah Beauregard', 'Bob White', 'Ava Fisher', 'Chris Rich', 'Xavier Adams', 'Sasha Ricci', 'Danielle Porter', 'Gordon Pike', 'Matt Hoyle'] searchName = str() index = int() selectionSort(names, SIZE) print('Sorted order:') for index in range (0, SIZE): print(names[index]) searchName = input('Enter a name to search for: ') index = binarySearch(names, searchName, SIZE) if index != -1: print('The ordered number of this name is ' + str(names[index])) else: print(searchName + 'was not found.') def selectionSort(array, arraySize): startScan = int(); minIndex = int(); minValue = int(); index = int() for startScan in range (0, arraySize - 1): minIndex = startScan minValue = array[startScan] for index in range (startScan + 1, arraySize): if array[index] &lt; minValue: minValue = array[index] minIndex = index array[minIndex] = array[startScan] array[startScan] = minValue def binarySearch(array, value, arraySize): position = -1 first = 0 last = arraySize - 1 found = False middle = int() while not found and first &lt;= last: middle = int((first + last) / 2) if array[middle] == value : found = True position = middle elif array[middle] &gt; value: last = middle - 1 else: first = middle + 1 return position main()
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86668192
score: -6
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86668136
has answer: http://stackoverflow.com/a/49826250
accepted answer: http://stackoverflow.com/a/49826250
has comment: http://stackoverflow.com/comment/86668121
tagged with: python
downvote count: 6
has title: How to display position of an element in an array?

http://stackoverflow.com/a/53276910
has body: you can also try following: brew install cmake brew install boost then create a virtual environment using conda command conda create -n dlib python=3.6 anaconda Activate the environment source activate dlib run the following command conda install pip and finally install dlib using below command pip install dlib This worked for me.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49889855

http://stackoverflow.com/q/49816143
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49816388
tagged with: php
tagged with: regex
score: 0
answer count: 1
has title: convert python scraping code in PHP to scrape instagram
has body: so here is working code of python to scrape the images from instagram from __future__ import print_function import json, re, requests user = 'thefatfoxcamden' profile = 'https://www.instagram.com/' + user with requests.session() as s: s.headers['user-agent'] = 'Mozilla/5.0' end_cursor = '' for count in range(1, 3): print('PAGE: ', count) r = s.get(profile, params={'max_id': end_cursor}) data = re.search(r'window._sharedData = (\{.+?});&lt;/script&gt;', r.text).group(1) j = json.loads(data) for node in j['entry_data']['ProfilePage'][0]['user']['media']['nodes']: if node['is_video']: page = 'https://www.instagram.com/p/' + node['code'] r = s.get(page) url = re.search(r'"video_url": "([^"]+)"', r.text).group(1) print('VIDEO:', url) else: print('IMAGE:', node['display_src']) end_cursor = re.search(r'"end_cursor": "([^"]+)"', r.text).group(1) Code is working awesome now i want to convert this code in PHP what i can get is right now that i can get only first loop which code is below &lt;?php function scrape_insta($username) { $insta_source = file_get_contents('http://instagram.com/'.$username); $shards = explode('window._sharedData = ', $insta_source); $insta_json = explode(';&lt;/script&gt;', $shards[1]); $insta_array = json_decode($insta_json[0], TRUE); return $insta_array; } //Supply a username $my_account = 'thefatfoxcamden'; $results_array = scrape_insta($my_account); $image_array= array(); $dataList = ($results_array['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges']); for($i=0; $i&lt;count($dataList); $i++){ if($dataList[$i]['node'][__typename]=='GraphImage'){ //echo '&lt;img src="'.$dataList[$i]['node']['display_url'].'"&gt;&lt;/br&gt;'; echo '&lt;img src="'.$dataList[$i]['node']['thumbnail_src'].'"&gt;&lt;/br&gt;'; } } above code is calling only for once i want to call in loop 3 times like the python code is doing. thanks in advance
type: Question
tagged with: instagram

http://stackoverflow.com/q/49906414
tagged with: python-imaging-library
score: 0
answer count: 1
has title: Pillow crop images keeping the ratio having a max width and max height
type: Question
has body: I need to crop something using Pillow, by keeping the ratio, and max_height or max_width. Some images can have a bigger width or a bigger height. I tried: image_clone = image.copy() width_percent = (size['width'] / float(image_clone.size[0])) height = int((float(image_clone.size[1]) * float(width_percent))) image_clone.thumbnail((size['width'], height), Image.LANCZOS) Doesn't work well for images that have a bigger width because the height will be small, and the image not very visible.
tagged with: python
accepted answer: http://stackoverflow.com/a/49929373
has comment: http://stackoverflow.com/comment/86844808
has answer: http://stackoverflow.com/a/49929373
has comment: http://stackoverflow.com/comment/86838309
type: AnsweredQuestion

http://stackoverflow.com/q/49798531
has title: TF Graph does not correspond to the code
downvote count: 0
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/48545477
answer count: 1
tagged with: neural-network
has body: I am trying to create a very simple neural network reading in information with the shape 1x2048 and to create a classification for two categories (object or not object). The graph structure however, deviates from what I believe to have coded. The dense layers should be included in the scope of "inner_layer" and should be receiving their input from the "input" placeholder. Instead, TF seems to be treating them as independent layers which do not receive any information from "input". Also, when using trying to use tensorboard summaries I get an error telling me that I have not mentioned inserting inputs for the apparent placeholders of the dense layers. When omitting tensorboard, everything works as I expected it based on the code. I have spent a lot of time trying to find the problem but I think I must be overlooking an something very basic. The graph I get in tensorboard is on this image. Which corresponds to the following code: tf.reset_default_graph() keep_prob = 0.5 # Graph Strcuture ## Placeholders for input with tf.name_scope('input'): x_ = tf.placeholder(tf.float32, shape = [None, transfer_values_train.shape[1]], name = "input1") y_ = tf.placeholder(tf.float32, shape = [None, num_classes], name = "labels") ## Dense Layer one with 2048 nodes with tf.name_scope('inner_layers'): first_layer = tf.layers.dense(x_, units = 2048, activation=tf.nn.relu, name = "first_dense") dropout_layer = tf.nn.dropout(first_layer, keep_prob, name = "dropout_layer") #readout layer, without softmax y_conv = tf.layers.dense(dropout_layer, units = 2, activation=tf.nn.relu, name = "second_dense") # Evaluation and training with tf.name_scope('cross_entropy'): cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels = y_ , logits = y_conv), name = "cross_entropy_layer") with tf.name_scope('trainer'): train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) with tf.name_scope('accuracy'): prediction = tf.argmax(y_conv, axis = 1) correct_prediction = tf.equal…
tagged with: machine-learning
has answer: http://stackoverflow.com/a/49819046
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: tensorboard
tagged with: python

http://stackoverflow.com/q/49897986
tagged with: python-3.x
answer count: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49898632
possible better answer: http://stackoverflow.com/a/49898632
has body: I have two list like that : my_list = [['can you change departure date to 30th March', '207443006734608218498'], ['can you downgrade to economy class?', '276566920664343421717'], ['book flight from San Francisco to Los Angeles on April 17-24', '897058868855606085615']] ids_list = ['207443006734608218498', '276566920664343421717', '897058868855606085615'] I check ids_list of element in my_list that match then i try to append on other list I try to get like that final list: [ ('can you change departure date to 30th March', { 'ids': { '207443006734608218498': 'True', '276566920664343421717': 'False', '897058868855606085615': 'False' } }), ('can you downgrade to economy class?', { 'ids': { '207443006734608218498': 'False', '276566920664343421717': 'True', '897058868855606085615': 'False' } }), ('book flight from San Francisco to Los Angeles on April 17-24', { 'ids': { '207443006734608218498': 'False', '276566920664343421717': 'False', '897058868855606085615': 'True' } }) ] for that i write simple loop and update tuple of dictionary like that &gt;&gt;&gt; data = {} &gt;&gt;&gt; for x in my_list: ... for y in ids_list: ... data.update({y: "True"} if x[1]==y else {y: "False"}) ... print((x[0],{"ids": data})) ... ('can you change departure date to 30th March', {'ids': {'207443006734608218498': 'True', '276566920664343421717': 'False', '897058868855606085615': 'False'}}) ('can you downgrade to economy class?', {'ids': {'207443006734608218498': 'False', '276566920664343421717': 'True', '897058868855606085615': 'False'}}) ('book flight from San Francisco to Los Angeles on April 17-24', {'ids': {'207443006734608218498': 'False', '276566920664343421717': 'False', '897058868855606085615': 'True'}}) but when i appending in list, data dict append with wrong value when i print that is as ablove then data dict value is correct what should i doing wrong? &gt;&gt;&gt; t = [] &gt;&gt;&gt; for x in my_list: ... for y in ids_list: ... data.update({y: "True"} if x[1]==y else {y: "False"}) …
accepted answer: http://stackoverflow.com/a/49898477
favorite count: 0
has comment: http://stackoverflow.com/comment/86811452
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86811669
tagged with: python
has answer: http://stackoverflow.com/a/49898477
tagged with: dictionary
has title: Appending to list of tuples with dictionary elements from input lists
type: Question

http://stackoverflow.com/q/49868725
type: Question
has comment: http://stackoverflow.com/comment/86760905
has body: I got this message whenever I try to open my blog article. my blog url is http://leonkong.com/ and post url is http://leonkong.com/1/ Error message: NoReverseMatch at /1/ Reverse for 'like_action' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)\\/like_action\\/$'] I use Django version 2.0.4 and recently created MySQL using AWS RDS. FYI, like_action function code(views.py): from django.contrib.auth.models import User from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.http import JsonResponse from django.shortcuts import get_object_or_404, redirect, render from django.utils import timezone from django.views.decorators.csrf import csrf_exempt def like_action(request, pk): """Like action: add +1 to post.like_button""" post = get_object_or_404(Post, pk=pk) post.like_button = post.like_button + 1 post.save() return redirect('post_detail', pk=post.pk) urls.py: from django.urls import path from . import views urlpatterns = [ path('keyboard', views.buttons, name='buttons'), path('message', views.message, name='message'), path('', views.post_list, name='post_list'), path('<int:pk>/', views.post_detail, name='post_detail'), path('post/new/', views.post_new, name='post_new'), path('post/<int:pk>/edit/', views.post_edit, name='post_edit'), path('about', views.about, name='about'), path('post/<int:pk>/remove/', views.post_remove, name='post_remove'), path('<str:category>', views.category_list, name='category_list'), path('<int:pk>/like_action/', views.like_action, name='like_action'), ] Here is html code for 'post_detail'. I always got error whenever I try to access 'post_detail' page. {% extends 'blog/base.html' %} {% load markdownify %} {% load static %} {% block content %} {% if post.created_date %} {{ post.created_date }} {% endif %} {{ post.title }} {% if user.is_authenticated %} edit delete {% endif %} {{ post.like_button }} {% if post.like_button < 2 %} Like {% else %} Likes…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86770938
tagged with: django
tagged with: python
tagged with: amazon-web-services
has title: django==2.0.4 with MySQL, NoReverseMatch at /1/
has comment: http://stackoverflow.com/comment/86817745
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86846084
tagged with: amazon-rds
tagged with: mysql
has comment: http://stackoverflow.com/comment/86763288

http://stackoverflow.com/comment/86653985
score: 0
has text: In case others get frustrated enough like me - I just ended up installing iceweasel and an older version of geckodriver and my script ended up working.
type: Comment
comment on: http://stackoverflow.com/q/49796818
type: QuestionComment

http://stackoverflow.com/q/49817273
downvote count: 1
possible better answer: http://stackoverflow.com/a/49817359
has answer: http://stackoverflow.com/a/49817359
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86649631
answer count: 2
has body: I have my modules in the following example structure: myapp --- application -- application.py -- __init__.py --- converter -- converter.py -- __init__.py --- gui --- panel.py --- __init__.py Now if I am in panel.py how should I import converter.py? would it be from myapp.converter import converter? (assuming sys.path is set) from converter import converter (assuming sys.path is set import converter (assuming sys.path is set) Do these points depend on where the main python application is run from? i.e. if converter.py was the program to run or panel.py was the program to run?
has title: What's the correct way to use import?
has answer: http://stackoverflow.com/a/49817375
accepted answer: http://stackoverflow.com/a/49817375
tagged with: python
has comment: http://stackoverflow.com/comment/86649488
type: AnsweredQuestion
score: 0
upvote count: 1

http://stackoverflow.com/a/49781472
has comment: http://stackoverflow.com/comment/86579207
has comment: http://stackoverflow.com/comment/86599410
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49781355
downvote count: 0
has comment: http://stackoverflow.com/comment/86599371
has comment: http://stackoverflow.com/comment/86578628
has comment: http://stackoverflow.com/comment/86579187
has comment: http://stackoverflow.com/comment/86600100
has comment: http://stackoverflow.com/comment/86600345
type: Answer
has comment: http://stackoverflow.com/comment/86578796
has comment: http://stackoverflow.com/comment/86578674
has body: I believe need first aggregate sum and then divide by div sum of columns per rows: print (df) company_name country_code state_code software finance commerce 0 google USA CA 1 0 4 1 jimmy GBR unknown 5 6 1 2 microsoft USA NY 1 0 0 #convert all columns without first to floats or ints cols = df.columns.difference(['company_name', 'country_code', 'state_code']) df[cols] = df[cols].astype(float) #if not possible use astype because some non numeric values #df[cols] = df[cols].apply(lambda x: pd.to_numeric(x, errors='coerce')) a = df.groupby(['state_code']).sum() df = a.div(a.sum(axis=1), axis=0) print (df) software finance commerce state_code CA 0.200000 0.0 0.800000 NY 1.000000 0.0 0.000000 unknown 0.416667 0.5 0.083333 If you need also percentage, multiply by 100 and if necessesary add round and cast to integers: df = a.div(a.sum(1), axis=0).mul(100).round(0).astype(int) print (df) software finance commerce state_code CA 20 0 80 NY 100 0 0 unknown 42 50 8 Last add percentage, but then values are not numeric, so no possible process later: df = a.div(a.sum(1), axis=0).mul(100).round(0).astype(int).astype(str).add('%') print (df) software finance commerce state_code CA 20% 0% 80% NY 100% 0% 0% unknown 42% 50% 8%

http://stackoverflow.com/comment/86597603
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49781417
has text: I changed the initial row values but the other rows do not react to this change in offset. E.g. `row+=[10,2]`..... the end row stays as `['B',2000, 265, 1]`... it should change to `['B', 2000, 275, 3]`
type: Comment

http://stackoverflow.com/q/49835801
tagged with: python
has answer: http://stackoverflow.com/a/49835990
has comment: http://stackoverflow.com/comment/86687045
type: AnsweredQuestion
tagged with: subprocess
downvote count: 0
has title: Understanding subprocess with a very simple example
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/21406887
answer count: 1
has body: Ok, im trying to understand how to use subprocess. I've made a little problem for practice and i just can't do it. what i want to do is: ping google then do a "cd" command so basically i want to see the ping command return values and then the directory where my program is This maybe to much info, so you can just jump to the last code section. ______________________________Jump______________________________________ I have tried many versions of a code. I managed to half do it with "run" command but that returns a "CompletedProcess" and i can't use that. So first try was pinging google result=subprocess.run('ping google.com', stdout=subprocess.PIPE) print(result.stdout.decode('utf-8')) this worked fine, then i susbtituted "'ping google.com'" for "'cd', shell=True" And finnaly substituted cd for dir, and decode could not decode the output (why?). Ok so after that i tried: result=subprocess.run(['cd ..'], shell=True, stdout=subprocess.PIPE) result.run(['cd'], shell=True, stdout=subprocess.PIPE) print(result.stdout.decode('utf-8')) And got: AttributeError: 'CompletedProcess' object has no attribute 'run' as expected. So this lead me to Popen, so i started all over with it: result=subprocess.Popen('ping google.com', stdout=subprocess.PIPE) print(result.communicate()[0].decode('utf-8')) _____________________Stop Jump____________________________ Now i want to send the "cd" after the ping, i have tried multiple ways of doing this, such as: result=subprocess.Popen('ping google.com',shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE) a='cd\n' result.communicate(a.encode('utf-8')) print(result.communicate()[0].decode('utf-8')) this prints just the ping. I tried removing "[0].decode('utf-8')" - no cd output I expected to see the ping result, then the cd output, what can i do? Ultimately i want to run several commands that depend on the previous output. Bonus question: I want to apply a program using Popen to a raspbian terminal, it's the same correct? Edit: my question is …
accepted answer: http://stackoverflow.com/a/49835990
favorite count: 0
has comment: http://stackoverflow.com/comment/86687136
type: Question
has comment: http://stackoverflow.com/comment/86686802
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86687020
has comment: http://stackoverflow.com/comment/86687134

http://stackoverflow.com/q/49768306
has body: I have a pytorch Tensor of shape [4, 3, 966, 1296]. I want to convert it to numpy array using the following code: imgs = imgs.numpy()[:, ::-1, :, :] How does that code work?
has title: Pytorch tensor to numpy array
upvote count: 189
tagged with: pytorch
type: AnsweredQuestion
downvote count: 3
possible better answer: http://stackoverflow.com/a/54585679
has answer: http://stackoverflow.com/a/54997162
score: 186
has comment: http://stackoverflow.com/comment/111270745
linked to: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/86552731
has comment: http://stackoverflow.com/comment/111270662
favorite count: 0
tagged with: numpy
has answer: http://stackoverflow.com/a/79215467
type: Question
has answer: http://stackoverflow.com/a/79407906
answer count: 8
has comment: http://stackoverflow.com/comment/111270476
has answer: http://stackoverflow.com/a/64566135
tagged with: python
has answer: http://stackoverflow.com/a/54585679
accepted answer: http://stackoverflow.com/a/49768500
has answer: http://stackoverflow.com/a/62921666
has answer: http://stackoverflow.com/a/64019204
has answer: http://stackoverflow.com/a/49768500

http://stackoverflow.com/q/49903336
type: Question
score: 2
has title: Python unittest loader throws TypeError during an __init__() call
upvote count: 2
accepted answer: http://stackoverflow.com/a/49919362
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49919362
has comment: http://stackoverflow.com/comment/86823044
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86822905
has comment: http://stackoverflow.com/comment/86822795
has comment: http://stackoverflow.com/comment/86822841
tagged with: python-unittest
tagged with: python
has body: I've written a bunch of tests for my Python application, but they've suddenly appeared to no longer be working properly! I've created a bunch of tests inside a tests module: Inside of tests.__main__.py, I've included the following code to load my test suite: import unittest if __name__ == "__main__": loader = unittest.TestLoader() start_dir = "." suite = loader.discover(start_dir=start_dir, pattern='*_test.py') runner = unittest.TextTestRunner() runner.run(suite) I know I am going to sound like a complete noob, but these tests were working perfectly for me about an hour ago. I would issue them by typing python3 -m tests from my base directory. However, I'm now receiving a really strange TypeError: 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 "/Users/yuchen/Desktop/myproj/myapp/tests/__main__.py", line 6, in &lt;module&gt; suite = loader.discover(start_dir=start_dir, pattern='*_test.py') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 341, in discover tests = list(self._find_tests(start_dir, pattern)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 406, in _find_tests yield from self._find_tests(full_path, pattern, namespace) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 406, in _find_tests yield from self._find_tests(full_path, pattern, namespace) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 398, in _find_tests full_path, pattern, namespace) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 452, in _find_test_path return self.loadTestsFromModule(module, pattern=pattern), Fal…

http://stackoverflow.com/a/49816935
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 7
has body: The OptionMenu class has no get method. The correct way to get the selected item from an OptionMenu is to use the get method of the OptionMenu's StringVar, which you named StudentLoanOp: def getStudentLoan(): global StudentLoan StudentLoan = StudentLoanOp.get()
accepted answer of: http://stackoverflow.com/q/49816795
has comment: http://stackoverflow.com/comment/86648410
answers question: http://stackoverflow.com/q/49816795
score: 7

http://stackoverflow.com/comment/86763259
comment on: http://stackoverflow.com/a/49871029
type: Comment
has text: the *rarfile* package use the *unrar* tool on your system; i.e.> It's not "autonomous"; if *unrar* doesn't work on your system, it'll never work on python. So, you need to do what it takes to get your *unrar* installation working properly on your Windows System, and then, try it on python. Open up a system console *cmd* (not python, don't open python) and try *unrar* command; if doesn't work properly, you need to fix that first, and only after that, try again inside python. If you have *unrar* installed on your system, probably you need to add *unrar* to your PATH environment variable.
score: 0
type: AnswerComment

http://stackoverflow.com/q/49790621
has comment: http://stackoverflow.com/comment/86596631
has comment: http://stackoverflow.com/comment/86596402
possible better answer: http://stackoverflow.com/a/49790872
accepted answer: http://stackoverflow.com/a/49790934
has comment: http://stackoverflow.com/comment/86596238
tagged with: python
has answer: http://stackoverflow.com/a/49790872
has answer: http://stackoverflow.com/a/49790934
has body: Im trying to get the number of lines in the output of ls -l | awk '{print $1}', which is 7 as shown below. total drwxrwxr-x drwxrwxr-x -rw-rw-r-- -rw-rw-r-- -rw-rw-r-- -rw-r--r-- I tried to store this value in the variable count but when I print count, the value is 0 instead of 7. I don't know why. import subprocess count = subprocess.call('ls -l | awk '{print $1}' | wc -l', shell=True) print count OUTPUT: 7 0
has comment: http://stackoverflow.com/comment/86597105
has comment: http://stackoverflow.com/comment/86596731
type: AnsweredQuestion
score: 3
answer count: 2
tagged with: subprocess
has comment: http://stackoverflow.com/comment/86596571
linked to: http://stackoverflow.com/q/9041141
has title: Storing subprocess.call() return value in a variable
has comment: http://stackoverflow.com/comment/86596213
downvote count: 1
has comment: http://stackoverflow.com/comment/86596510
has comment: http://stackoverflow.com/comment/86596120
favorite count: 0
type: Question
upvote count: 4

http://stackoverflow.com/comment/86699470
comment on: http://stackoverflow.com/q/49841147
type: QuestionComment
score: 0
type: Comment
has text: I built instead of installed, but when I run setup.py I get the same error `Permission Denied`. He has to write to to `/usr/local/lib/python3.5/`. Without `sudo` it can't!

http://stackoverflow.com/comment/86735916
comment on: http://stackoverflow.com/q/49860217
type: Comment
score: 0
type: QuestionComment
has text: @jpp I think my question is different. I am not asking the details of the implementation, but whether I can rely on the order or not, if not, are there specific cases I should be aware of etc...

http://stackoverflow.com/q/49829574
tagged with: wave
has answer: http://stackoverflow.com/a/49829786
has body: Say I have a code given in a string for example: str(00012333210-1) The numbers relate to a certain amplitude on a wave I wish to graph. I want to transform the code into a printable wave where the numbers are replaced by asterisks such as: 3: *** 2: * * 1: * * 0:*** * -1: * -2: -3: Any useful tools to go about doing this? So far I have tried to split the string into individual numbers however am struggling with the negatives. For example: file = "000123332101233321000" x = [int(i) for i in file] print(x) I only have a very basic understanding of python so i'm very stuck at the moment.
favorite count: 0
has title: Python, using print() and replace() function to interpret code given by string
tagged with: python-3.x
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49830059
downvote count: 0
tagged with: python
type: UnansweredQuestion
tagged with: replace
tagged with: printing
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86674383

sqlite
tags question: http://stackoverflow.com/q/49763571
tags question: http://stackoverflow.com/q/49865207
tags question: http://stackoverflow.com/q/49843817
tags question: http://stackoverflow.com/q/49760789
tags question: http://stackoverflow.com/q/49821802
tags question: http://stackoverflow.com/q/49765513
tags question: http://stackoverflow.com/q/49880562
tags question: http://stackoverflow.com/q/49758961
tags question: http://stackoverflow.com/q/49912226
tags question: http://stackoverflow.com/q/49768588
tags question: http://stackoverflow.com/q/49801522
tags question: http://stackoverflow.com/q/49820873
type: Tag
tags question: http://stackoverflow.com/q/49897336
tags question: http://stackoverflow.com/q/49866732
tags question: http://stackoverflow.com/q/49815405
tags question: http://stackoverflow.com/q/49861513
tags question: http://stackoverflow.com/q/49835272
tags question: http://stackoverflow.com/q/49884826
tags question: http://stackoverflow.com/q/49861541
tags question: http://stackoverflow.com/q/49846080
tags question: http://stackoverflow.com/q/49902863
tags question: http://stackoverflow.com/q/49886483
tags question: http://stackoverflow.com/q/49768897
tags question: http://stackoverflow.com/q/49893974
tags question: http://stackoverflow.com/q/49854686
tags question: http://stackoverflow.com/q/49905003
tags question: http://stackoverflow.com/q/49906212
tag name: sqlite
tags question: http://stackoverflow.com/q/49906071
tags question: http://stackoverflow.com/q/49812935
tags question: http://stackoverflow.com/q/49816092
tags question: http://stackoverflow.com/q/49838401
tags question: http://stackoverflow.com/q/49885478
tags question: http://stackoverflow.com/q/49779281
tags question: http://stackoverflow.com/q/49841244
tags question: http://stackoverflow.com/q/49888643

http://stackoverflow.com/q/49844685
tagged with: pandas
has answer: http://stackoverflow.com/a/49844931
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86759318
has comment: http://stackoverflow.com/comment/86730411
has title: I want to append an csv file using python pandas to add an array as new column
has comment: http://stackoverflow.com/comment/86704451
has comment: http://stackoverflow.com/comment/86715833
has comment: http://stackoverflow.com/comment/86704886
accepted answer: http://stackoverflow.com/a/49844977
has comment: http://stackoverflow.com/comment/86704092
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49844740
tagged with: python
has comment: http://stackoverflow.com/comment/86733681
has answer: http://stackoverflow.com/a/49844977
has comment: http://stackoverflow.com/comment/86718108
has answer: http://stackoverflow.com/a/49844740
has comment: http://stackoverflow.com/comment/86718160
type: AnsweredQuestion
score: 0
has body: I have tried the following code: import pandas as pd list1 = {'Names':[1,2,3,4,5]} df = pd.DataFrame(list1) df_csv = pd.read_csv('try.csv') df_csv['Names'] = list1 df_csv.to_csv('try.csv', index=False, mode= 'a') The error is as following: "ValueError: Length of values does not match length of index" I understand that the size of the dataframe doesn't match but how can I solve that? So, this is what I want in try.csv file after appending: try.csv file
answer count: 3

http://stackoverflow.com/a/49847018
accepted answer of: http://stackoverflow.com/q/49846461
answers question: http://stackoverflow.com/q/49846461
type: AcceptedAnswer
type: Answer
has body: Compare contiguous columns In order to check wheter or not A[i]==B[i+1] &amp; A[i+1]==B[i] for all the rows in the dataframe, you can compare the colums vectorially but shifted: A = np.array([1,2,3,5,14,16,16,13]) # I mdified input data from the question for the second example B = [2,1,6,19,16,15,14,12] df = pd.DataFrame({'A':A,'B':B}) eq_diag = (df['A'][:-1].values==df['B'][1:].values) &amp; (df['A'][1:].values==df['B'][:-1].values) # boolean array with rows=rows_in_df-1, eq_diag[i] will be true if the # diagonal between rows i and i+1 is equal # Output for eq_diag # [ True False False False False False False] Then, the values which are equal in these diagonal comparisons can be printed: print df[:-1][eq_diag] # the [:-1] is important for dimensions to match # Out A B 0 1 2 # it also returns the index i (not i+1) where the diagonal is equal Compare ALL column combinations in the dataframe If instead of comparing the column i with the column i+1, all possible combinations should be compared, the module itertools can be used: import itertools combinations = np.array(list(itertools.combinations(range(len(df)),2))) print combinations.T eq_diag = ((df['A'].values[combinations[:,0]]==df['B'].values[combinations[:,1]]) &amp; (df['A'].values[combinations[:,1]]==df['B'].values[combinations[:,0]])) # Out: all the column combinations [[0 0 0 0 0 0 0 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 5 5 6] [1 2 3 4 5 6 7 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7]] And then, the elemenst which are equal can be printed: for i,j in combinations[eq_diag]: print 'The criss cross element of columns {} and {} is equal:\n{}'.format(i,j,df.valuesi,j) # Out # The criss cross element of columns 0 and 1 is equal: # [[1 2] # [2 1]] # The criss cross element of columns 4 and 6 is equal: # [[14 16] # [16 14]]
score: 0
has comment: http://stackoverflow.com/comment/86750331

beautifulsoup
tags question: http://stackoverflow.com/q/49828707
tags question: http://stackoverflow.com/q/49908884
tags question: http://stackoverflow.com/q/49791969
type: Tag
tags question: http://stackoverflow.com/q/49900910
tags question: http://stackoverflow.com/q/49897889
tags question: http://stackoverflow.com/q/49909852
tags question: http://stackoverflow.com/q/49899927
tags question: http://stackoverflow.com/q/49833458
tags question: http://stackoverflow.com/q/49767309
tags question: http://stackoverflow.com/q/49814263
tags question: http://stackoverflow.com/q/49806786
tags question: http://stackoverflow.com/q/49766150
tags question: http://stackoverflow.com/q/49805467
tags question: http://stackoverflow.com/q/49860354
tags question: http://stackoverflow.com/q/49838179
tags question: http://stackoverflow.com/q/49836236
tags question: http://stackoverflow.com/q/49866985
tags question: http://stackoverflow.com/q/49907917
tags question: http://stackoverflow.com/q/49830115
tags question: http://stackoverflow.com/q/49779905
tags question: http://stackoverflow.com/q/49793128
tags question: http://stackoverflow.com/q/49778415
tags question: http://stackoverflow.com/q/49902438
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/49911592
tags question: http://stackoverflow.com/q/49833636
tags question: http://stackoverflow.com/q/49779445
tags question: http://stackoverflow.com/q/49834241
tags question: http://stackoverflow.com/q/49844084
tags question: http://stackoverflow.com/q/49861147
tags question: http://stackoverflow.com/q/49796735
tags question: http://stackoverflow.com/q/49906062
tags question: http://stackoverflow.com/q/49786254
tags question: http://stackoverflow.com/q/49899671
tags question: http://stackoverflow.com/q/49833207
tags question: http://stackoverflow.com/q/49911036
tags question: http://stackoverflow.com/q/49868937
tags question: http://stackoverflow.com/q/49888300
tags question: http://stackoverflow.com/q/49906794
tags question: http://stackoverflow.com/q/49826686
tags question: http://stackoverflow.com/q/49809055
tags question: http://stackoverflow.com/q/49762733
tags question: http://stackoverflow.com/q/49907219
tags question: http://stackoverflow.com/q/49857296
tags question: http://stackoverflow.com/q/49890130
tags question: http://stackoverflow.com/q/49876017
tags question: http://stackoverflow.com/q/49765471
tags question: http://stackoverflow.com/q/49792061
tags question: http://stackoverflow.com/q/49902433
tags question: http://stackoverflow.com/q/49770095
tags question: http://stackoverflow.com/q/49779725
tags question: http://stackoverflow.com/q/49900644
tags question: http://stackoverflow.com/q/49840504
tags question: http://stackoverflow.com/q/49770315
tags question: http://stackoverflow.com/q/49786624
tags question: http://stackoverflow.com/q/49787982
tags question: http://stackoverflow.com/q/49833484
tags question: http://stackoverflow.com/q/49786893
tags question: http://stackoverflow.com/q/49809407
tags question: http://stackoverflow.com/q/49857938
tags question: http://stackoverflow.com/q/49789877
tags question: http://stackoverflow.com/q/49869971
tags question: http://stackoverflow.com/q/49758413
tags question: http://stackoverflow.com/q/49839458
tags question: http://stackoverflow.com/q/49843116
tags question: http://stackoverflow.com/q/49847901
tags question: http://stackoverflow.com/q/49907823
tags question: http://stackoverflow.com/q/49826440
tags question: http://stackoverflow.com/q/49883361

http://stackoverflow.com/comment/86720465
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49852925
has text: Please print text_train_tfidf and show

http://stackoverflow.com/comment/86569726
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49777143
type: Comment
has text: Trailing whitespace in the actual csv maybe? It worked for the sample csv data you posted.

http://stackoverflow.com/a/49840565
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49840504
has body: The additional x avoids the problem that you had, i.e TypeError: argument of type 'NoneType'. Try calling the lambda function with None as the argument: &gt;&gt;&gt; f = lambda x: ".org" in x &gt;&gt;&gt; f &lt;function &lt;lambda&gt; at 0x7f5dd1215ea0&gt; &gt;&gt;&gt; f(None) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 1, in &lt;lambda&gt; TypeError: argument of type 'NoneType' is not iterable &gt;&gt;&gt; f('abcd.org/blah') True The first x in x and ".org" in x tests whether x is "truthy". If it is the rest of the expression is evaluated. If it is not "truthy", e.g. it is None, then the second part of the and expression is short circuited and not executed. This avoids attempting to perform the in operation, thereby avoiding the problem.

http://stackoverflow.com/comment/86838815
type: Comment
comment on: http://stackoverflow.com/q/49911427
score: 1
has text: `>>> (1, 2) in [[1, 2]]` `False`
type: QuestionComment

http://stackoverflow.com/q/49795270
has answer: http://stackoverflow.com/a/49801232
has body: I'm having a very strange issue and can't seem to find a way to fix it. The following code finds the prime factorisation of n, puts the prime factors into a list then finds all possible sum variations of the prime factors and prints out the unique values of that list. Example: The prime factors for 44 are 2*2*11 so for 44 it would print out 2,2+2,11,2+11,2+2+11 = 2,4,11,13,15: Here is my code: import math import sys import itertools from itertools import permutations def primes(n): primfac = [] d = 2 while d*d &lt;= n: while (n % d) == 0: primfac.append(d) n //= d d += 1 if n &gt; 1: primfac.append(n) return primfac def primecombo(n): b = [] for i in range(1, len(primes(n))+1): for subset in permutations(primes(n), i): b.append(sum((subset))) a = list(set(b)) a.sort() return a the code itself seems to work fine and efficiently for the most part but for some very strange reason it becomes ridiculously slow when you're dealing with any number who's only prime factor is 2. if you try print primecombo(444444) or print primecombo(23452823) it'll print the results almost instantly but if you try 2048 or 4096 it becomes really really slow. Can anyone see why this is the case and what I can do to fix it?
tagged with: permutation
favorite count: 0
type: Question
has title: python itertools permutations for powers of 2 is too slow
tagged with: performance
tagged with: python-itertools
accepted answer: http://stackoverflow.com/a/49801232
linked to: http://stackoverflow.com/q/42601876
has comment: http://stackoverflow.com/comment/86605378
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/86605203
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86607960
has comment: http://stackoverflow.com/comment/86604999
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49805007
has answer: http://stackoverflow.com/a/49805100
has comment: http://stackoverflow.com/comment/86625055
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/86624986
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49805103
has body: I'm trying to program for a simple game. I want the countdown to be printed like 10, 9, 8, ... for seeing how much time is left to collect items. when the timer runs out I want the program to close. This is the error: int() argument must be a string, a bytes-like object or a number, not 'datetime.timedelta' can sombody correct it or better send me a working timer concept? Thanks import time import datetime now = datetime.datetime.now() later = datetime.datetime.now() diff = int(later - now) #countdown in sec tcount = 10 countd = tcount - diff countd = str(countd) while diff &lt; tcount: print("countdown:" + countd)
duplicate of: http://stackoverflow.com/q/39718271
has title: python timer based on datetime
tagged with: datetime
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/39718271
upvote count: 0
answer count: 2

http://stackoverflow.com/comment/86950983
has text: Going through a JSON structure followed by an OrderedDict when the data is a simple 2D matrix, appears extremely complicated compared the list-based solution. Remember the Zen of Python: "simple is better than complex" and "complex is better than complicated". But no problem if it fulfils your wishes...
type: AnswerComment
comment on: http://stackoverflow.com/a/49873917
score: 0
type: Comment

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/49863855
tag name: google-oauth
tags question: http://stackoverflow.com/q/49829002

http://stackoverflow.com/comment/86653439
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49819158
has text: just a minor edit, in the `if condition` it should be `media_channel` and not `channel_type`
score: 0

http://stackoverflow.com/comment/86788797
type: AnswerComment
comment on: http://stackoverflow.com/a/49848141
type: Comment
has text: OK, it looks like you going to solve your problem. You can also convert strings to a numeric type using pd.to_numeric https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html . If you have a problem with the density of ticks on your y axis then you can use plt.yticks(np.arange(0, 1000, 100)) before plt.show() and adjust the maximum and the step as appropriate.
score: 0

http://stackoverflow.com/comment/86818109
score: 0
type: Comment
type: QuestionComment
has text: @aja - I am trying to do this but cannot get it to work. Can you tell me how I can automaticly send "write_report(NULL_CHAR * 8)" after each report? Addint them in the dictionary gives an error. And adding them like this also generates an error: exec("write_report(NULL_CHAR * 8)".join(translated_list)). THANKS
comment on: http://stackoverflow.com/q/49887540

http://stackoverflow.com/comment/86562857
has text: Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49773957
type: QuestionComment

opencv3.0
tags question: http://stackoverflow.com/q/49881907
tags question: http://stackoverflow.com/q/49843069
tags question: http://stackoverflow.com/q/49838068
type: Tag
tags question: http://stackoverflow.com/q/49780551
tags question: http://stackoverflow.com/q/49770419
tags question: http://stackoverflow.com/q/49835662
tags question: http://stackoverflow.com/q/49786869
tag name: opencv3.0
tags question: http://stackoverflow.com/q/49762388
tags question: http://stackoverflow.com/q/49884890
tags question: http://stackoverflow.com/q/49907382

http://stackoverflow.com/a/49850149
upvote count: 1
has body: To write the rows to file, use: f.write("0,0,0\n") While reading from the file, remove the new line char with: data.append(line.rstrip('\n').split(","))
score: 1
answers question: http://stackoverflow.com/q/49849942
downvote count: 0
type: Answer

http://stackoverflow.com/a/50187026
answers question: http://stackoverflow.com/q/49782895
has body: iterate through offset each part. But take in account that there are a lot of notes which will not match and also for every note there usually is different length. oiter = stream.iterator.OffsetIterator(parts[0]) for groupedElements in oiter: print(groupedElements, groupedElements[0].quarterLength, groupedElements[0].offset) Later check if those parts have the same offsets. If they have then those notes are played at the same time.
score: 0
type: Answer

chemistry
type: Tag
tag name: chemistry
tags question: http://stackoverflow.com/q/49888634
tags question: http://stackoverflow.com/q/49896768

pypdf
tags question: http://stackoverflow.com/q/49888578
tags question: http://stackoverflow.com/q/49822853
tags question: http://stackoverflow.com/q/49765805
type: Tag
tag name: pypdf

http://stackoverflow.com/comment/86551095
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49767828
has text: Fair enough, but it resolves your Problem. You simply cannot recursively intantiate a class within itself.
type: Comment

http://stackoverflow.com/a/49806243
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49805467
type: AcceptedAnswer
type: Answer
has body: From BeautifulSoup's Documentation: decompose() removes a tag from the tree, then completely destroys it and its contents: Code: from bs4 import BeautifulSoup data = ''' Tournament Name TCG Saturday Tournament ID 000002 Category TCG: Unlimited Registration 12:15PM to 1:15PM Status Complete ''' soup = BeautifulSoup(data, 'html.parser') for lis in soup.find_all('li'): lis.label.decompose() print(soup.text) Output: TCG Saturday 000002 TCG: Unlimited 12:15PM to 1:15PM Complete
accepted answer of: http://stackoverflow.com/q/49805467

http://stackoverflow.com/q/49793932
has comment: http://stackoverflow.com/comment/86602443
has comment: http://stackoverflow.com/comment/86602128
has answer: http://stackoverflow.com/a/49795936
answer count: 1
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86602904
tagged with: windows
tagged with: django
tagged with: python
has title: Starting chrome in from batch file
has comment: http://stackoverflow.com/comment/86602222
has comment: http://stackoverflow.com/comment/86602574
score: 0
tagged with: batch-file
has body: I have django app that I am able to start from batch file.I want to start google chrome with address http://localhost:8000/.I tried with different solutions available but still the chrome is not starting. Server gets activated My bat script @echo off cmd /k "cd /d C:\Users\user1\Desktop\Website\code\myenvironment\Scripts &amp; activate &amp; cd /d C:\Users\user1\Desktop\Website\code\myapp &amp; python manage.py runserver" start C:\"Program Files (x86)"\Google\Chrome\Application\chrome.exe "http://localhost:8000/"

http://stackoverflow.com/comment/86826662
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49905298
has text: Thank you very much - this does it perfectly.

http://stackoverflow.com/a/49909054
answers question: http://stackoverflow.com/q/49909027
has body: You are using the % operator on a string: &gt;&gt;&gt; x = 'A' &gt;&gt;&gt; x % 2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: not all arguments converted during string formatting When using % on a string, you are not getting the modulus, but are using printf-style string formatting instead. And that requires a %-style placeholder for the value on the right to be formatted into. With no placeholders in the string on the left, you get the error you see. If you wanted to test if the length of the string is even, you need to use the len() function to get that length: myList3 = ['even' if len(x) % 2 == 0 else 'nope' for x in myNames] Demo: &gt;&gt;&gt; myNames = ['A','BB','CCC','DDDD'] &gt;&gt;&gt; ['even' if len(x) % 2 == 0 else 'nope' for x in myNames] ['nope', 'even', 'nope', 'even']
accepted answer of: http://stackoverflow.com/q/49909027
score: 5
upvote count: 5
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/comment/86836830
type: Comment
type: QuestionComment
has text: Does event1 have anything to do with event2? Should the calculations be done per ID?
score: 1
comment on: http://stackoverflow.com/q/49910451

http://stackoverflow.com/a/49783891
has body: The following creates two numpy arrays and plots a figure with 15 subplots, arranged in 5 rows and 3 columns. Note that you can dynamically assign your x and y variables inside of the for loop as well, especially if you would like to loop through a set of data while creating each individual subplot: import numpy as np import matplotlib.pyplot as plt x = np.linspace(1,10,10) y = np.linspace(1,10,10) fig = plt.figure(1) columns = 3 rows = 5 for i in range(1, columns*rows+1): fig.add_subplot(rows, columns, i) plt.scatter(x, y) plt.tight_layout() plt.show()
score: 3
has comment: http://stackoverflow.com/comment/86615566
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86615968
accepted answer of: http://stackoverflow.com/q/49783682
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49783682

http://stackoverflow.com/a/49807672
has comment: http://stackoverflow.com/comment/86630354
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49801029
has body: This solution doesn't need any external libraries, so might be easier if you're not familiar with Python. location_1= {"name_1":["0.0","0.0","0.0","4.1","2.2"], "name_2":["8.4","7.3","7.2","4.0","2.0"], "name_3":["7.0","7.0","5.0","6.0","3.0"]} location_2 = {"name_1":["8.0","8.0","8.0","0.0","3.0"]} . for key, value in location_2.items(): if key not in location_1: location_1[key] = value else: for i in range(len(value)): # each index in the list old = location_1[key][i] new = float(old)+float(value[i]) location_1[key][i] = str(new) # str optional At the end, the value is converted back into a string, but I would recommend keeping it as a numerical value. Also, a float stores a floating point number, which can have decimal places, and can be manipulated as a number rather than a string, if you're new to general coding. To leave the value as a float, replace the last line location_1[key][i] = str(new) with location_1[key][i] = new
type: Answer

http://stackoverflow.com/q/49763225
favorite count: 0
has answer: http://stackoverflow.com/a/49763265
score: 2
type: AnsweredQuestion
tagged with: typeerror
has body: This returns a type error difference = [1, 2, 3, 4, 5] for i in range(len(difference)-1): difference = difference[i+1] - difference[i] But this works fine difference = [difference[i+1]-difference[i] for i in range(len(difference)-1)] What am I missing here? I thought they were the same.
answer count: 3
has comment: http://stackoverflow.com/comment/86542127
has comment: http://stackoverflow.com/comment/86542216
has title: Why do I get TypeError: 'int' object is not subscriptable using for loop and not with list-comprehension in python
tagged with: python
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/49763298
type: Question
tagged with: for-loop
upvote count: 2
has answer: http://stackoverflow.com/a/49763335
downvote count: 0
possible better answer: http://stackoverflow.com/a/49763298
accepted answer: http://stackoverflow.com/a/49763265
has comment: http://stackoverflow.com/comment/86542076

http://stackoverflow.com/comment/86566964
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49775515
type: QuestionComment
has text: The shape looks a bit different. (5,5,3,6). I don't know how can I process that.

http://stackoverflow.com/q/49801361
tagged with: arduino
downvote count: 0
upvote count: 1
score: 1
tagged with: bluetooth
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has title: Bluetooth with Python and Arduino (HC-06)
favorite count: 0
type: Question
answer count: 2
has body: I'm trying to send information from my Arduino to Python. The information I'm sending is a string of 16 characters and the problem is I'm not receiving all the data at once. Arduino code: void setup(){ BTserial.begin(9600); } void loop() { BTserial.print("0123456789012345"); delay(500); } Python code: import bluetooth sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) sock.connect(("00:13:04:83:EC:45", 1)) while(True): print(sock.recv(10)) The output that comes out is: b'0' b'123456789' b'012345' The output that I want is: b'0123456789012345' or 0123456789012345 Thanks for any answer.
has answer: http://stackoverflow.com/a/49801993
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49808501

http://stackoverflow.com/comment/86710359
type: Comment
comment on: http://stackoverflow.com/q/49847677
score: 0
type: QuestionComment
has text: I changed your title to reflect your actual issue and recommended for reopening. Recommended reading https://stackoverflow.com/questions/588004/is-floating-point-math-broken

multi-index
tags question: http://stackoverflow.com/q/49906335
tag name: multi-index
type: Tag
tags question: http://stackoverflow.com/q/49841674
tags question: http://stackoverflow.com/q/49826003
tags question: http://stackoverflow.com/q/49875793

http://stackoverflow.com/comment/86562900
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49774076
has text: Yes... yes there is, it is called `groupby`

http://stackoverflow.com/q/49900145
has answer: http://stackoverflow.com/a/49900500
has body: I have this data extracted from Email body Data=("""-------- Forwarded Message -------- Subject: Sample Report Date: Thu, 6 Apr 2017 16:39:19 +0000 From: test1@abc.com To: test2@xyz.com""") I want to extract this particular date and month , and copy it in the variables Need output as Date = 6 Month = "Apr" Can anyone please help with this using regular expressions?
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 0
upvote count: 2
possible better answer: http://stackoverflow.com/a/49900254
downvote count: 2
has answer: http://stackoverflow.com/a/49900254
tagged with: string
has comment: http://stackoverflow.com/comment/86815830
accepted answer: http://stackoverflow.com/a/49900483
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49900483
tagged with: python-3.x
has title: Extract Date from string using regex in Python 3.5.2
answer count: 3
has comment: http://stackoverflow.com/comment/86815719
tagged with: datetime

http://stackoverflow.com/a/49811003
type: Answer
has comment: http://stackoverflow.com/comment/86636676
answers question: http://stackoverflow.com/q/49810960
score: 0
has body: The value is a string still. so you're just evaluating whether the string is empty or not. If you really need booleans, remove the quotes or check if the string is "True" 'False' == 'True'

http://stackoverflow.com/q/49858821
favorite count: 0
type: Question
has title: Python getpass doesn't work on Windows Git Bash (MINGW64)
has comment: http://stackoverflow.com/comment/94928354
has answer: http://stackoverflow.com/a/54046572
tagged with: windows
has comment: http://stackoverflow.com/comment/94928369
has comment: http://stackoverflow.com/comment/94928262
tagged with: python
accepted answer: http://stackoverflow.com/a/54046572
has comment: http://stackoverflow.com/comment/94928338
type: AnsweredQuestion
score: 3
answer count: 2
linked to: http://stackoverflow.com/q/24544353
has comment: http://stackoverflow.com/comment/94928153
upvote count: 3
has body: I have this simple python code to get a password without echoing it. import getpass password = getpass.getpass("Password: ") print(password) This code works as expected on Linux, but on Windows Git Bash it let's me type indefinitely. As a workaround I can use the script from PowerShell, but it's annoying to change shells just to run a script. Do you know any other non-echoing libraries in Python or any workaround for this issue?
possible better answer: http://stackoverflow.com/a/49859175
downvote count: 0
has comment: http://stackoverflow.com/comment/94928305
has answer: http://stackoverflow.com/a/49859175
linked to: http://stackoverflow.com/q/32597209

http://stackoverflow.com/q/49879146
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86774424
has comment: http://stackoverflow.com/comment/86776097
has comment: http://stackoverflow.com/comment/86774021
answer count: 1
upvote count: 1
has title: Why does gettatr transform a boolean into a string?
has comment: http://stackoverflow.com/comment/86774260
downvote count: 1
accepted answer: http://stackoverflow.com/a/49883989
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49883989
tagged with: django
tagged with: python
has body: I have a model with a boolean field: @python_2_unicode_compatible class Invoice(models.Model): ... is_paid = models.BooleanField(default=False) ... def __init__(self, *args, **kwargs): super(Invoice, self).__init__(*args, **kwargs) self.__tracked_fields = ['is_paid'] for field in self.__tracked_fields: setattr(self, '__original_%s' % field, getattr(self, field)) I'm trying to track the change in this field before saving: def set_original_values(self): for field in self.__tracked_fields: original = '__original_%s' % field original_value = getattr(self, original) setattr(self, field, original_value) return self.__dict__ def has_changed(self): for field in self.__tracked_fields: original = '__original_%s' % field if getattr(self, original) != getattr(self, field): return True return False def save(self, *args, **kwargs): self.full_clean() if self.has_changed(): if not self.can_be_confirmed(): self.set_original_values() return super(Invoice, self).save(*args, **kwargs) But when testing, I get specific results. # THE FAILED TEST CODE def test_has_no_changed(self): self.invoice.amount = 1 self.invoice.is_paid = True self.invoice.save() print(self.invoice.is_paid) print(type(self.invoice.is_paid)) self.assertFalse(self.invoice.is_paid) Part of the test result: .False &lt;class 'str'&gt; AssertionError: 'False' is not false Of course, if I once again get an object from the database, the value in the field will be converted to Boolean But before getting the object from the database, the test passes only this way: self.assertEqual(self.invoice.is_paid, 'False') What could be the problem? ** UPDATE ** Problem in the set_original_values method. If I do, as shown in the example, then the field value type is a string. P.S. Thanks to everyone who puts a negative on my question, because it's so useful in solving my problem ...
has comment: http://stackoverflow.com/comment/86774621
has comment: http://stackoverflow.com/comment/86776071

http://stackoverflow.com/comment/86546884
score: 2
has text: @drooze. -1 probably easier than len(X) here.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49765578

http://stackoverflow.com/comment/86571898
type: Comment
comment on: http://stackoverflow.com/a/49773249
score: 0
type: AnswerComment
has text: @BoseSanamchai, pay attention at how did i use `param_grid` or, better, simply use my code to understand how does it work...

http://stackoverflow.com/q/49854608
favorite count: 0
type: Question
upvote count: 2
has title: Python OpenCV: Reading an image along x and y axis
tagged with: python
has comment: http://stackoverflow.com/comment/86726469
has body: Aim: I am trying to read the first point (non-zero) here in this image (shown as the red arrow) from __future__ import division import numpy as np import cv2 im1 = cv2.imread('C:/Users/Desktop/Line.png', 0) for x in range(0, im1.shape[0], 1): for y in range(0, im1.shape[1], 1): cpt = im1[x][y] if 0 &lt; cpt &lt;= 255 : print("This is the value", x,y) But, the point being printed is this (a zero point): How is this so? The original image:
tagged with: image
tagged with: opencv
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49856088
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86726547
has answer: http://stackoverflow.com/a/49856088
has comment: http://stackoverflow.com/comment/86726310

http://stackoverflow.com/comment/125906311
has text: Surprisingly, accessing this property is over an order of magnitude slower than `np.count_nonzero` but I couldn't find any explanation as to why.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/54377341
type: Comment

http://stackoverflow.com/comment/86570068
type: QuestionComment
has text: `psExec \\11.456.787.8 -u user -p pwd C:\imaging\run.bat` am trying it manually in cmd it is connecting fine and running the batch file
comment on: http://stackoverflow.com/q/49775390
score: 0
type: Comment

http://stackoverflow.com/a/60856778
downvote count: 0
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49848517
has body: pip3 ❌ didn't fully work for me as there was a problem with importing a function. conda install biopython ✔️ worked for me.
upvote count: 3

http://stackoverflow.com/q/49841155
has body: How to ensure that a list has a certain number of elements only, and extra inputs after that are ignored? import random diceboard = [1,2,0,4,5,0] #for example n=0 def roll(): dice1=random.randint(1,6) dice2=random.randint(1,6) dice3=random.randint(1,6) dice4=random.randint(1,6) dice5=random.randint(1,6) dice6=random.randint(1,6) return [dice1,dice2,dice3,dice4,dice5,dice6] while diceboard.index!=0: #this basically means that per each element that does not have a value of zero(pls correct my code) n=n+1 newroll=roll() newroll=newroll.split(None, n)[:n] #this limits the size of the list print(newroll)
has title: Limiting size of list
has comment: http://stackoverflow.com/comment/86697496
tagged with: python
has comment: http://stackoverflow.com/comment/86697448
has comment: http://stackoverflow.com/comment/86698972
tagged with: list
upvote count: 0
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49841495
type: UnansweredQuestion
score: -2
downvote count: 2

http://stackoverflow.com/q/49803909
answer count: 2
has title: TypeError while finding the first matching string from a list
downvote count: 1
has comment: http://stackoverflow.com/comment/86622477
has answer: http://stackoverflow.com/a/49803962
accepted answer: http://stackoverflow.com/a/49803962
favorite count: 0
has body: I am trying to get the URL from the below list, What am I doing wrong? &gt;&gt;&gt; op [b'key', b'Changes:', b'remote:', b'https://server-1.com/253', b'test', b'change', b'remote:', b'To', b'ssh://server-1:29418/a/ab', b'*', b'[new', b'branch]', b'HEAD', b'-&gt;', b'refs/for/foo'] &gt;&gt;&gt; &gt;&gt;&gt; next(x for x in op if "https" in x) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 1, in &lt;genexpr&gt; TypeError: a bytes-like object is required, not 'str' &gt;&gt;&gt;
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/33054527
has comment: http://stackoverflow.com/comment/86622468
tagged with: python
possible better answer: http://stackoverflow.com/a/49803972
score: -1
duplicate of: http://stackoverflow.com/q/33054527
has answer: http://stackoverflow.com/a/49803972
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/q/49768134
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49788360
score: 0
linked to: http://stackoverflow.com/q/34937302
has answer: http://stackoverflow.com/a/49788360
has comment: http://stackoverflow.com/comment/86551559
tagged with: matplotlib
answer count: 1
has comment: http://stackoverflow.com/comment/86551828
type: Question
has body: I've been looking at similar questions for about an hour now, but so far no suggestions I've seen have helped me troubleshoot this issue. For example: 'virtualenv' 'pip install sqlalchemy' but 'pip list' can not see did not help. Setup: In my project directory, I typed simply virtualenv env Then source env/bin/activate I confirmed pip and python are being run from my venv with which pip etc. pip install matplotlib, and it looks successful: ... Installing collected packages: subprocess32, kiwisolver, numpy, matplotlib Successfully installed kiwisolver-1.0.1 matplotlib-2.2.2 numpy-1.14.2 subprocess32-3.2.7 python and then >> import matplotlib produces: ImportError: No module named matplotlib I've looked in env/lib/python2.7/site-packages and sure enough, no matplotlib.
tagged with: python
tagged with: virtualenv
has title: virtualenv: pip claiming it successfully installs a package, but doesn't
linked to: http://stackoverflow.com/q/49748063

http://stackoverflow.com/q/49818007
tagged with: apache-spark
score: 1
has title: How do I read Spark processing log?
answer count: 1
accepted answer: http://stackoverflow.com/a/49818855
downvote count: 1
has answer: http://stackoverflow.com/a/49818855
favorite count: 0
type: Question
tagged with: hadoop
has body: I I have run a python script like this: spark-submit \ --master yarn \ --deploy-mode client \ --driver-memory 2G \ --driver-cores 2 \ --executor-memory 8G \ --num-executors 3 \ --executor-cores 3 \ script.py And I get logs like this: spark.yarn.driver.memoryOverhead is set but does not apply in client mode. [Stage 1:=================================================&gt; (13 + 2) / 15]18/04/13 13:49:18 ERROR YarnScheduler: Lost executor 3 on serverw19.domain: Container killed by YARN for exceeding memory limits. 12.0 GB of 12 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead. [Stage 1:=====================================================&gt; (14 + 1) / 15]18/04/13 14:01:43 ERROR YarnScheduler: Lost executor 1 on serverw51.domain: Container killed by YARN for exceeding memory limits. 12.0 GB of 12 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead. [Stage 1:====================================================&gt; (14 + -1) / 15]18/04/13 14:02:48 ERROR YarnScheduler: Lost executor 2 on serverw15.domain: Container killed by YARN for exceeding memory limits. 12.0 GB of 12 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead. [Stage 1:====================================================&gt; (14 + -8) / 15]18/04/13 14:02:49 ERROR YarnScheduler: Lost an executor 2 (already removed): Pending loss reason. [Stage 1:=======================================================(26 + -11) / 15]18/04/13 14:29:53 ERROR YarnScheduler: Lost executor 5 on serverw38.domain: Container killed by YARN for exceeding memory limits. 12.0 GB of 12 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead. [Stage 1:=======================================================(28 + -13) / 15]^[18/04/13 14:43:35 ERROR YarnScheduler: Lost executor 6 on serverw10.domain: Slave lost 18/04/13 14:43:35 ERROR TransportChannelHandler: Connection to serverw22.domain/10.252.139.122:54308 has been quiet for 120000 ms wh…
upvote count: 2
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/49835515
score: 1
favorite count: 0
has title: wxPython panel not filling parent
has comment: http://stackoverflow.com/comment/86688214
has body: I have a wxPython frame containing a single custom panel. I'd like this panel to fill its frame. class MyCustomFrame(wx.Frame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.mainPanel = MyCustomPanel(self) self.SetAutoLayout(True) Yet for some reason, the custom panel claims its size is always 20x20, no matter how I resize the main window. class MyCustomPanel(wx.Panel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) print('Panel size:', self.GetSize()) Panel size: (20, 20) What's going wrong? EDIT: From here: If a wxFrame (or derived class) is to have only one child, then you don't need a sizer at all, as the default behaviour of the frame's EVT_SIZE handler (assuming there is only one child) is to resize that child to occupy all of the frame's client area. But that's not what's happening.
has comment: http://stackoverflow.com/comment/86687355
has comment: http://stackoverflow.com/comment/86688100
has comment: http://stackoverflow.com/comment/86686519
answer count: 0
downvote count: 0
tagged with: wxpython
upvote count: 1
tagged with: python
type: UnansweredQuestion
type: Question
tagged with: user-interface

http://stackoverflow.com/a/49873335
type: Answer
has body: Try this: li = [] for i,j in enumerate(a): for z,x in enumerate(a): if int(x)+int(j) == int(b) and i&gt;z: li.append([i,z])
score: 0
answers question: http://stackoverflow.com/q/49866190
has comment: http://stackoverflow.com/comment/86773099

http://stackoverflow.com/q/49868654
type: Question
answer count: 2
type: UnansweredQuestion
has body: I'm using Python 3.6.5 with pyenv. pip 10 came out a while ago but pyenv is creating my new virtual environments with pip 9.0.3 and i have to update each one of them manually. It's annoying. I tried to update pyenv and re-installing Python version (i was hoping it will come with newer pip version but it didn't.) but no success. Should i wait for an update on pyenv side or am i missing something?
tagged with: pip
tagged with: python
score: 11
upvote count: 11
has answer: http://stackoverflow.com/a/77647902
downvote count: 0
has answer: http://stackoverflow.com/a/49868675
tagged with: pyenv
has title: How to update pip version installed by pyenv
favorite count: 0

http://stackoverflow.com/q/49874001
has comment: http://stackoverflow.com/comment/86763350
has comment: http://stackoverflow.com/comment/86763631
has comment: http://stackoverflow.com/comment/86764035
has answer: http://stackoverflow.com/a/49874554
has answer: http://stackoverflow.com/a/49874455
has comment: http://stackoverflow.com/comment/86763667
type: Question
has body: I'm doing the basic Python card trick and what I've searched for is too complicated, here's my code: import random import itertools deck = ["S A","S 2","S 3","S 4","S 5","S 6","S 7","D A","D 2","D 3","D 4","D 5","D 6","D 7","C A","C 2","C 3","C 4","C 5","C 6","C 7"] random.shuffle(deck) for z in range(3): print("Pile ",[z+1]) for i in range(7): print(deck[i]) What I am trying to do is get it so when I get my 3 piles, I don't want any duplicate values but I can't work out how I do it, or how I get them in 3 separate columns?
has comment: http://stackoverflow.com/comment/86763529
linked to: http://stackoverflow.com/q/312443
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86764153
answer count: 4
has answer: http://stackoverflow.com/a/49874411
has comment: http://stackoverflow.com/comment/86764393
has title: How can I get 3 lists of unique values from a list of 21 unique values?
has answer: http://stackoverflow.com/a/49874849
score: 0
tagged with: list

http://stackoverflow.com/a/49780254
has comment: http://stackoverflow.com/comment/86580707
has comment: http://stackoverflow.com/comment/86577782
has comment: http://stackoverflow.com/comment/86576185
has comment: http://stackoverflow.com/comment/86580554
type: Answer
has comment: http://stackoverflow.com/comment/86577810
score: 4
has comment: http://stackoverflow.com/comment/86577915
has comment: http://stackoverflow.com/comment/86577921
has body: You can use any() here. for node in soup.find_all(text=lambda t: t and any(x in t for x in ['Open', 'Closed'])): print(node) This will be useful as a general solution. If you have more words to search for, you can simply add them in the list. If you want to know what any() does, have a look at the documentation: any(iterable): Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to: def any(iterable): for element in iterable: if element: return True return False Edit: Use the above solution if you want to search sentences that contain the specified words. But, if you want to match the exact text (as mentioned in the edited question), you can use what @Jatimir mentioned in the comments: for node in soup.find_all(text=lambda t: t in ('Open', 'Closed')): print(node)
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49779905
has comment: http://stackoverflow.com/comment/86580656
has comment: http://stackoverflow.com/comment/86576306
has comment: http://stackoverflow.com/comment/86580465
has comment: http://stackoverflow.com/comment/86576226
answers question: http://stackoverflow.com/q/49779905

http://stackoverflow.com/comment/86645020
type: AnswerComment
has text: It works, thank you! But if i want to insert a value with a boolean. What kind of type do you use to represent the key as a boolean in SQLite?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49813931

http://stackoverflow.com/comment/105791387
has text: how do we host different applications inside this. For example, the hello world looks like below ` from flask import Flask app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): return "Hello World!" if __name__ == "__main__": app.run()` How do we host this
type: Comment
comment on: http://stackoverflow.com/a/59503554
score: 0
type: AnswerComment

http://stackoverflow.com/comment/95686280
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49886737
type: AnswerComment
has text: I had the same issue for a couple of days. Since I was trying to access the database through Apache, I added `www-data` to the group and gave it the required permissions. It worked. But then I realised that it only works the first time after I have given it the permissions, then it reverts back to the original permissions. So I had to make `www-data` the owner

http://stackoverflow.com/q/49808914
tagged with: pandas
has title: Panda Standardising with Condition
upvote count: 1
has answer: http://stackoverflow.com/a/49811195
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86633272
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86632742
tagged with: scikit-learn
tagged with: python
score: 0
has body: I need some help about standardize with condition, how can i standardise a column of data Score Rating Result 1 20 1200 -1.264911064 2 30 1300 -1.264911064 3 40 1200 -0.632455532 4 50 1300 -0.632455532 5 60 1200 0 6 70 1300 0 7 80 1200 0.632455532 8 90 1300 0.632455532 9 100 1200 1.264911064 10 110 1300 1.264911064 I am trying to standardise all the scoers that has the same rating, ie standardise all score that has rating 1200 and 1300. the scikit-learn. preprocessing.scalar seems to not support this function.

http://stackoverflow.com/comment/108637707
comment on: http://stackoverflow.com/a/61410848
score: 0
type: AnswerComment
has text: Hello! Sorry, i'll try to improve my answer. Thanks for the feedback!
type: Comment

http://stackoverflow.com/comment/133758523
type: AnswerComment
has text: You're a lifesaver! This helped me significantly resolve a lousy fit to a noisy curve (where I needed to "overfit" on purpose). Thanks a million!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50186036

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/49825133

http://stackoverflow.com/a/49776605
has body: Here's a quick and simple complete solution: import numpy as np import scipy.ndimage.measurements as mnts A = np.array([ [1, 0, 0, 0], [0, 1, 1, 0], [0, 1, 0, 0], [0, 1, 0, 0] ]) # labeled is a version of A with labeled clusters: # # [[1 0 0 0] # [0 2 2 0] # [0 2 0 0] # [0 2 0 0]] # # clusters holds the number of different clusters: 2 labeled, clusters = mnts.label(A) # sizes is an array of cluster sizes: [0, 1, 4] sizes = mnts.sum(A, labeled, index=range(clusters + 1)) # mnts.sum always outputs a float array, so we'll convert sizes to int sizes = sizes.astype(int) # get an array with the same shape as labeled and the # appropriate values from sizes by indexing one array # with the other. See the `numpy` indexing docs for details labeledBySize = sizes[labeled] print(labeledBySize) output: [[1 0 0 0] [0 4 4 0] [0 4 0 0] [0 4 0 0]] The trickiest line above is the "fancy" numpy indexing: labeledBySize = sizes[labeled] in which one array is used to index the other. See the numpy indexing docs (section "Index arrays") for details on why this works. I also wrote a version of the above code as a single compact function <a href="https://tio.run/##fZBNT8MwDIbv/RWW0LRGRFULt0m9wJUTOwKHrHW3SI0bJSlQ/nzJRxkFJnKxYr9@7Nd6cqeBbudZKj0YBzQqPYGwQDpbUraReiqolUocsVAo7GhQITkbdMrHLLuCbqTGyYHgFY31MWuxg14csL@b9vIDc2EM22XgX8xiy6HpR@u8HOqIKWIhCqPO@rZzzY4qVPh3t6QW32sj6Ij5mXQNFWOFsG7SmEtyiWTQjYYS8GkBvPD4Dbs7tA7epDuBp7WDAj9ITNAN5q8tX/IrkS6SNAY/Jy/5TQTWeVXyqmQs0ybkt48r5O6ZNnYLG4geA@shLZNuxEP@PlnZL@Z/n/AS9uuQyeB6yBp2uXW5Bhz@ofxYks3zJw" rel="nofollow noreferrer">that you can try out yourself online. It includes a test case based on a random array.
has comment: http://stackoverflow.com/comment/86779360
score: 3
has comment: http://stackoverflow.com/comment/86876990
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49776310
answers question: http://stackoverflow.com/q/49776310
has comment: http://stackoverflow.com/comment/86570723
has comment: http://stackoverflow.com/comment/86792550
has comment: http://stackoverflow.com/comment/86779947
type: Answer

http://stackoverflow.com/comment/88868976
has text: In my case, the .png file was empty. Hope you resolve this! :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49819971
score: 1

http://stackoverflow.com/comment/86841802
comment on: http://stackoverflow.com/a/49817683
has text: @nahusznaj - I check it and do you think this sample data? `d = { 'Primary area': [ 'Biological Sciences A', 'Cultures and Cultural Production', 'Mathematics' ], 'Discipline': [ 'Biochemistry and Molecular Biology', 'Philosophy', 'Computation Theory and Mathematics' ] } df = pd.DataFrame(data=d) Mydisciplines = ['Biological Sciences A', 'Mathematics', 'Philosophy','Computation Theory']` ?
score: 0
type: Comment
type: AnswerComment

imdb
tags question: http://stackoverflow.com/q/49889788
tags question: http://stackoverflow.com/q/49902780
type: Tag
tag name: imdb

http://stackoverflow.com/q/49826125
tagged with: scipy
has comment: http://stackoverflow.com/comment/86670414
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86735344
linked to: http://stackoverflow.com/q/49582252
has comment: http://stackoverflow.com/comment/86735134
has comment: http://stackoverflow.com/comment/86733871
has title: Faster N-dimensional interpolations and simulations in Python
type: UnansweredQuestion
tagged with: numba
has comment: http://stackoverflow.com/comment/86670161
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/38306335
has body: I am writing some software in Python that would allow the user to run simulations that involve simple additions and multiplications and interpolation on an arbitrary number of dimensions. In the process, the function has to repeatedly (and sequentially) add, multiply, and interpolate on an N-dimensional grid. I have to do this in a loop since in each iteration the results are dependent on the previous iteration (they're not parallelizable). In the 1 dimensional case, it looks like T = 1000000000 b = 0 for t in range(T): b = b * f(b) + np.random.randn() b = b + f(b) where f in the code above is an interpolant created by the data and grid supplied by the user. In each iteration, the same interpolant is used. The first thing that comes to mind is to use numba to speed up the loops. However, to be able to interpolate on an N dimensional grid, I have to use scipy.interpolate.RegularGridInterpolator but using this would prevent me from running numba in nopython mode. I know that there is this package that allows faster interpolations, but I'm not sure if I can use this in the nopython mode. Also, I'm wondering if there are other options to get over this bottleneck? Any help is greatly appreciated.
tagged with: interpolation
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/86734421
upvote count: 1
has comment: http://stackoverflow.com/comment/86675121

http://stackoverflow.com/a/49931350
score: 0
accepted answer of: http://stackoverflow.com/q/49913751
type: AcceptedAnswer
upvote count: 1
has body: Here in this function secret_exponent_to_wif def secret_exponent_to_wif(se, compressed): blob = to_bytes_32(se) if compressed: blob += b'\01' return BitcoinMainnet.ui.wif_for_blob(blob) Here it uses BitcoinMainnet to generate Bitcoin address.You just use LitecoinMannet to generate Litecoin address . It is already there in pycoin.coins.litecoin library. By changing the corresponding network values you can generate address of any crypto key
downvote count: 1
answers question: http://stackoverflow.com/q/49913751
type: Answer

http://stackoverflow.com/q/49904462
tagged with: set
downvote count: 0
has title: Pandas find duplicate concatenated values across selected columns
upvote count: 1
favorite count: 0
type: Question
has body: I want to find duplicates in a selection of columns of a df, # converts the sub df into matrix mat = df'idx', 'a', 'b'.values str_dict = defaultdict(set) for x in np.ndindex(mat.shape[0]): concat = ''.join(str(x) for x in mat[x][1:]) # take idx as values of each key a + b str_dict[concat].update([mat[x][0]]) dups = {} for key in str_dict.keys(): dup = str_dict[key] if len(dup) &lt; 2: continue dups[key] = dup The code finds duplicates of the concatenation of a and b. Uses the concatenation as key for a set defaultdict (str_dict), updates the key with idx values; finally uses a dict (dups) to store any concatenation if the length of its value (set) is >= 2. I am wondering if there is a better way to do that in terms of efficiency.
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49904508
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49904615
possible better answer: http://stackoverflow.com/a/49904615
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/49904508
tagged with: pandas
score: 1

http://stackoverflow.com/q/49909852
tagged with: pyqt4
has title: beautifulsoup return empty value
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/49909944
accepted answer: http://stackoverflow.com/a/49909944
answer count: 1
tagged with: web-scraping
has body: I'm using Jupyter Python 2.7 I was trying to retrieve data from this website and everything went on well with using beautifulsoup and lxml parser to scrape description or price. site = 'https://www.bedbathandbeyond.com/store/product/dyson-v7-motorhead-cord-free-stick-vacuum-in-fuchsia-steel/1061083288?brandId=162' however, when I was trying to scrape comments or location of the reviewer, I could not retrieve anything back, only an empty list [] I also tried PyQt4 to render it first yet it still didn't work. How should I fix it now? My code is attached below import PyQt4 from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtWebKit import * import sys from lxml import html from bs4 import BeautifulSoup import os import requests site = 'https://www.bedbathandbeyond.com/store/product/dyson-v7-motorhead-cord-free-stick-vacuum-in-fuchsia-steel/1061083288?brandId=162' class Render(QWebPage): def __init__(self, url): self.app = QApplication(sys.argv) QWebPage.__init__(self) self.loadFinished.connect(self._loadFinished) self.mainFrame().load(QUrl(url)) self.app.exec_() def _loadFinished(self, result): self.frame = self.mainFrame() self.app.quit() r = Render(site) result = r.frame.toHtml() formatted_result = str(result.toAscii()) tree = html.fromstring(formatted_result) soup = BeautifulSoup(formatted_result,'lxml') soup.find_all('span', class_ = 'BVRRValue BVRRUserLocation')#return value is [] Many thanks!
tagged with: beautifulsoup
type: Question

http://stackoverflow.com/comment/86628868
has text: `sorted(rows,key=lambda row:order_key.index(row['name_index']))` ... I guess
score: 0
comment on: http://stackoverflow.com/q/49807004
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86650437
score: 5
comment on: http://stackoverflow.com/q/49817963
type: Comment
has text: What have you tried so far? Where are you getting stuck?
type: QuestionComment

http://stackoverflow.com/comment/86818781
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49901590
score: 1
has text: Would be good to see the code that causes the error if possible?

http://stackoverflow.com/q/49861842
downvote count: 0
has comment: http://stackoverflow.com/comment/86739027
has body: I am trying to encode my text using my loaded tokenizer but am getting the following error AttributeError: 'Tokenizer' object has no attribute 'oov_token' I included the code below: from keras.preprocessing.text import Tokenizer from keras.preprocessing import sequence from keras.models import Model, Input, Sequential, load_model import pickle import h5py maxlen = 100 tok = open('tokenizer.pickle', 'rb') tokenizer = pickle.load(tok) tok.close() model = load_model('weights.h5') def predict(): new_text = sequence.pad_sequences((tokenizer.texts_to_sequences(['heyyyy'])), maxlen=maxlen) prediction = model.predict(new_text,batch_size=1,verbose=2) The problem occurs on the line tokenizer.texts_to_sequences(['heyyyy']) and I'm not sure why. Is the problem with pickle? the tokenizer.texts_to_sequences works with 'hey', 'heyy', and 'heyyy'. Any guidance is appreciated!
has comment: http://stackoverflow.com/comment/86739002
answer count: 1
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/49861987
type: Question
accepted answer: http://stackoverflow.com/a/49861987
has comment: http://stackoverflow.com/comment/86738843
has title: AttributeError: 'Tokenizer' object has no attribute 'oov_token' in Keras
tagged with: pickle
tagged with: python
upvote count: 4
score: 4
tagged with: nlp
type: AnsweredQuestion
tagged with: tokenize

http://stackoverflow.com/comment/86573402
comment on: http://stackoverflow.com/a/49777602
type: Comment
has text: It worked. I need the '>' sign also, but that's simple to add. Thanks.
type: AnswerComment
score: 0

http://stackoverflow.com/a/49871393
answers question: http://stackoverflow.com/q/49869501
has comment: http://stackoverflow.com/comment/86758124
has body: 1) "But I still cannot get the point, why not train all training data can avoid the problem?" - We will hold that data for validation purpose, just like the way we do in K-fold 2) "so should I also train M base-learner based on all train data for the input to predict?" - If you give same data to all the learners then the output of all of them would be same and there is no use in creating them. So we will give a subset of data to each learner.
type: Answer
score: 0

http://stackoverflow.com/q/49785938
linked to: http://stackoverflow.com/q/45874816
type: Question
has comment: http://stackoverflow.com/comment/86616677
has comment: http://stackoverflow.com/comment/86588495
type: UnansweredQuestion
tagged with: python
has body: I'm trying to understand how to read the anaconda *.yml files better, and couldn't find much documentation online: name: AdvML channels: defaults dependencies: jupyter=1.0.0=py36_3 numpy=1.13.1=py36_0 pip=9.0.1=py36_1 python=3.6.2=0 scikit-learn=0.19.0=np113py36_0 matplotlib=2.0.2=np113py36_0 pip: tensorflow==1.3.0 So I have two questions: What does - jupyter=1.0.0=py36_3 mean? I assumed it means that the dependency is jupyter version 1.0.0, but what does =py36_3 mean? And why does the following line have =py36_0? I don't understand why particular package versions are being referenced to particular python versions, and why different python versions are being referenced. Why is there a pip heading? If I activated an anaconda environment and then used pip to install a package (eg tensorflow in this case), why isn't tensorflow just part of the regular dependency list, rather than a separate pip list? Thanks.
score: 0
tagged with: anaconda
answer count: 0
has title: Why does my anaconda *.yml file reference two different versions of python?

http://stackoverflow.com/a/49909252
has body: I was able to determine the cause of the issue I was encountering. The function: markerImage = aruco.drawDetectedMarkers(img, corners) was setting markerImage and img to be the exact same object such that markerImage is img returned as True. To avoid this problem I coped img using: markerImage = img.copy() aruco.drawDetectedMarkers(markerImage, corners) This functionality is significantly different from most of my experience so hopefully it will help someone in the future.
answers question: http://stackoverflow.com/q/49887058
accepted answer of: http://stackoverflow.com/q/49887058
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/86534057
comment on: http://stackoverflow.com/a/49759348
score: 0
type: Comment
type: AnswerComment
has text: there's nothing wrong with your answer, I'm just commenting for future people looking at this answer :)

excel
tags question: http://stackoverflow.com/q/49763973
tags question: http://stackoverflow.com/q/49779995
tags question: http://stackoverflow.com/q/49764143
tags question: http://stackoverflow.com/q/49758593
tags question: http://stackoverflow.com/q/49833920
tags question: http://stackoverflow.com/q/49847534
tags question: http://stackoverflow.com/q/49896860
tags question: http://stackoverflow.com/q/49826003
tags question: http://stackoverflow.com/q/49819029
tags question: http://stackoverflow.com/q/49848360
tag name: excel
tags question: http://stackoverflow.com/q/49820878
tags question: http://stackoverflow.com/q/49826481
tags question: http://stackoverflow.com/q/49801060
tags question: http://stackoverflow.com/q/49848207
tags question: http://stackoverflow.com/q/49800332
type: Tag
tags question: http://stackoverflow.com/q/49870991
tags question: http://stackoverflow.com/q/49846754
tags question: http://stackoverflow.com/q/49876077
tags question: http://stackoverflow.com/q/49876778
tags question: http://stackoverflow.com/q/49783622
tags question: http://stackoverflow.com/q/49803369
tags question: http://stackoverflow.com/q/49758871
tags question: http://stackoverflow.com/q/49908361
tags question: http://stackoverflow.com/q/49856502
tags question: http://stackoverflow.com/q/49763957
tags question: http://stackoverflow.com/q/49846780
tags question: http://stackoverflow.com/q/49845235
tags question: http://stackoverflow.com/q/49882234
tags question: http://stackoverflow.com/q/49868352
tags question: http://stackoverflow.com/q/49761161
tags question: http://stackoverflow.com/q/49908098

http://stackoverflow.com/comment/86629924
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49807471
type: Comment
has text: First of all, why are you passing an entire weblink in as a delimiter...

http://stackoverflow.com/comment/86589053
type: Comment
has text: @YOLO [1,2] + [2,3]=[1,2,2,3], list concat :-)
type: AnswerComment
comment on: http://stackoverflow.com/a/49786379
score: 1

http://stackoverflow.com/q/49880429
favorite count: 0
has answer: http://stackoverflow.com/a/49880586
has body: I have code and followed up below reference but doesn't affect when working with repeat - &lt;p v-for="item in questionDataSet.options"&gt; &lt;label&gt; &lt;input name="question-data-row" type="radio" v-model="requestData.surveyDetails.answerSelection" value="{{item.key}}"&gt; &lt;span&gt;{{item.value}}&lt;/span&gt; here {{item.key}} is not working in radio value while have updated the jinja2 template binding but {{item.value}} still displaying well. My JSON data set for reference - {"options": [{"key": "A", "value": "Lucknow"}, {"key": "B", "value": "New Delhi"}, {"key": "C", "value": "Ahmedabad"}, {"key": "D", "value": "Patna"}], "question": "India’s first ever ‘Khadi Haat’ has launched in which city?"} I have followed this link for solution but not work fully.
has comment: http://stackoverflow.com/comment/98611474
tagged with: python
type: Question
upvote count: 2
has title: vue js with flask jinja2 conflict data rendering
score: 2
linked to: http://stackoverflow.com/q/46214132
tagged with: vue.js
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: flask
tagged with: jinja2

http://stackoverflow.com/q/49843881
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49846237
tagged with: python
accepted answer: http://stackoverflow.com/a/49844041
has title: How to convert output to a list
type: Question
possible better answer: http://stackoverflow.com/a/49843900
has answer: http://stackoverflow.com/a/49844041
has body: Below is the code for basic program that prints prime numbers in given range. I want prime numbers to be arranged in the list instead of just being printed one per line. lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) print("Prime numbers between", lower, "and", upper, "are:") for num in range(lower, upper + 1): if num &gt; 1: for i in range(2, num): if (num % i) == 0: break else: print(num)
has answer: http://stackoverflow.com/a/49843900
type: AnsweredQuestion

http://stackoverflow.com/q/49802416
has title: How to access Block reference attributes in pyautocad
tagged with: autocad
tagged with: python
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/49802417
upvote count: 2
has answer: http://stackoverflow.com/a/49802417
has body: If Bill of Material (BOM) in AutoCAD drawing are in 'Block Reference', to read BOM using pyautocad we can read it using following code. from pyautocad import Autocad acad = Autocad() for obj in acad.iter_objects(['Block']): if obj.HasAttributes: obj.GetAttributes() But it throws exception in comtypes\automation.py, line 457, in _get_value typ = _vartype_to_ctype[self.vt &amp; ~VT_ARRAY] KeyError: 9 How to read BoM in AutoCAD using pyautocad.
answer count: 1
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/q/49883807
has title: Joining Values with a common key in specific place
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49883915
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/49883915
score: 1
downvote count: 0
answer count: 1
has body: i try to find a way to join values that share a common key (in the below example it would be the ID) into a specified place in a dataframe. Where i start: df1 = pd.DataFrame({"ID" : ["x13", "x13", "", "x14", "" , "x13"], "Name":"Master1", "Slave1", "Master2", "Master3", "Master4" , "Slave2"],"value":["", "5", "7", "8", "", "1"]}) Output is as expected: ID Name value 0 x13 Master1 1 x13 Slave1 5 2 Master2 7 3 x14 Master3 8 4 Master4 5 x13 Slave2 1 What i want to achieve is the following result: ID Name value 0 x13 Master1 5,1 1 x13 Slave1 5 2 Master2 7 3 x14 Master3 8 4 Master4 5 x13 Slave2 1 In words: I want to loop through the datarame and find all not empty ID's. When found i want to join up all the values which have the common ID in a list, and store that back in the datframe on the Master of this specific ID. All my solution attemps ended up in loop in loop ... I am kind of sure that the solution would be related to the groupby functionality of pandas but I cannot get the desired output.
favorite count: 0
type: Question
upvote count: 1
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/49774996
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86578450
accepted answer: http://stackoverflow.com/a/49775407
tagged with: python
has title: Dynamic Wrapper in Python
has body: I'm looking to create a dynamic wrapper class that exposes the API calls from a provided object using data in the object. Statically it looks like this: class Concrete: def __init__(self, data): self.data = data def print_data(self): print(self.data) class Wrapper: ''' One day this will wrap a variety of objects. But today it can only handle Concrete objects. ''' def wrap_it(self, concrete): self.cco = concrete # concreteobject=cco def print_data(self): self.cco.print_data() cco = Concrete(5) wcco = Wrapper() wcco.wrap_it(cco) wcco.print_data() Produces 5 I'd like to figure out how to do the same thing but make wrap_it dynamic. It should search the concrete object find the functions, and create functions of the same name that call the same function in the concrete object. I imagine that the solution involves inspect.signature or at least some use of *args and **kwargs, but I've not seen an example on how to put all this together.
has comment: http://stackoverflow.com/comment/86578437
has answer: http://stackoverflow.com/a/49775264
possible better answer: http://stackoverflow.com/a/49775264
has comment: http://stackoverflow.com/comment/86578479
score: 2
type: AnsweredQuestion
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/49775407
downvote count: 1
has comment: http://stackoverflow.com/comment/86565549

http://stackoverflow.com/comment/86817224
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49899509
has text: Can you print the summary of `net_generator` **immediately before** this line?

http://stackoverflow.com/comment/86826898
has text: Googling around, I found [Pyrasite](http://pyrasite.readthedocs.io/en/latest/) which is supposed to let you inject code in a running process, or let you [drop into a shell](https://pyrasite.readthedocs.io/en/latest/Shell.html) and execute commands in a running process. Seems to be working on Python 2 and 3, on Widows and Linux. I have never used it, so I don't know what it's worth...
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49904516

cython
tags question: http://stackoverflow.com/q/49899269
tags question: http://stackoverflow.com/q/49793671
tags question: http://stackoverflow.com/q/49837155
tags question: http://stackoverflow.com/q/49803899
tags question: http://stackoverflow.com/q/49778057
tags question: http://stackoverflow.com/q/49777638
tags question: http://stackoverflow.com/q/49882554
tags question: http://stackoverflow.com/q/49888283
type: Tag
tags question: http://stackoverflow.com/q/49833200
tags question: http://stackoverflow.com/q/49913221
tags question: http://stackoverflow.com/q/49861124
tags question: http://stackoverflow.com/q/49850815
tag name: cython

http://stackoverflow.com/comment/86616241
type: Comment
type: QuestionComment
has text: This makes a lot more sense. There is no reason I have to keep the permutation matrices in memory at this point. Is `permutation.matrices` a list of them? Also, by `A`, do you mean `a` in my code? For say d=3, `a=[1,0,0]`, then `N=[[1,0,0],[0,1,0],[0,0,1]]`, and `P` is a list of matrices where the rows of N have been permuted. So I'm not sure I understand your comment. I also apologise for what may be obvious questions.
score: 0
comment on: http://stackoverflow.com/q/49799475

http://stackoverflow.com/comment/86606497
comment on: http://stackoverflow.com/q/49793849
type: Comment
has text: @anothernode Yes, agreed. I suspect the OP's system is somehow not quite clean though... and working out what's wrong with it is maybe harder than starting from clean... If you have other approaches to suggest, then feel free to go for it... I'm always happy to learn too.
type: QuestionComment
score: 0

http://stackoverflow.com/q/49799160
score: 2
downvote count: 0
tagged with: selenium
tagged with: web-scraping
has body: I faced the problem when I try to collect all the comments from https://ideas.lego.com/projects/6f1d4d6e-f47a-467a-8b10-d918d04e6d5c/comments_tab, there is two types of button for comments Load more comments, I solve it Show the reply, that one I couldn't solve it. i tred to add it as button and click it but not work fine from bs4 import BeautifulSoup from selenium import webdriver import time driver = webdriver.PhantomJS() driver.get('https://ideas.lego.com/projects/6f1d4d6e-f47a-467a-8b10-d918d04e6d5c/comments_tab') sbtn = driver.find_element_by_class_name("load-more") sbtn.click() SCROLL_PAUSE_TIME = 1 # Get scroll height last_height = driver.execute_script("return document.body.scrollHeight") while True: # Scroll down to bottom driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # Wait to load page time.sleep(SCROLL_PAUSE_TIME) # Calculate new scroll height and compare with last scroll height new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height html = driver.page_source soup = BeautifulSoup(html, "html.parser") z = soup.find_all('div', attrs={'class': 'comment-message cms'}) #print(z) print(len(z)) Thanks ====== Edits ====== what i did : Load all the page with scrolling all down the page and collect all the comments, except the under the reply, because I didn't find a way to click the button to complete load all of them
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
has title: python: scraping with button
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86614330
tagged with: python

http://stackoverflow.com/a/49789100
type: Answer
has comment: http://stackoverflow.com/comment/86754698
has comment: http://stackoverflow.com/comment/86712665
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49788994
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49788994
has comment: http://stackoverflow.com/comment/86712721
has body: No, while working with InternetExplorerDriver you shouldn't ignore the browser zoom settings. As per the Official Documentation of InternetExplorerDriver the Required Configuration mentions the following about Browser Zoom Level The browser zoom level must be set to 100% so that the native mouse events can be set to the correct coordinates. As the browser zoom level is set to 125% hence you see the error. As a solution you must set the browser zoom level back to 100%. Update Though you havn't replied/commented to my Answer which was constructed as per your question I can observe from your question update that you are trying to set the property ignore_protected_mode_settings to True. To achieve that you need to use an instance of DesiredCapabilities() Class and configure the WebDriver instance as follows : from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities cap = DesiredCapabilities().INTERNETEXPLORER cap['ignoreZoomSetting'] = True browser = webdriver.Ie(capabilities=cap, executable_path=r'C:\path\to\IEDriverServer.exe') browser.get('http://google.com/') browser.quit()

http://stackoverflow.com/comment/86557121
score: 0
has text: Kindly share your code and explain about the issue you are facing to help you efficiently.
comment on: http://stackoverflow.com/q/49770671
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49871101
has comment: http://stackoverflow.com/comment/92217649
tagged with: python
upvote count: 7
favorite count: 0
tagged with: conditional-statements
tagged with: pandas
score: 7
has title: How to select range of rows in Pandas?
has answer: http://stackoverflow.com/a/49871201
has body: I have created a dataframe that has a bunch of characteristics. I want to create a new column that selects all rows between two specific rows (which are going to be inputs). Say that the dataframe is the following: data = {'currency': ['Euro', 'Euro', 'Euro', 'Dollar', 'Dollar', 'Yen', 'Yen', 'Yen', 'Pound', 'Pound', 'Pound, 'Pesos', 'Pesos'], 'cost': [34, 67, 32, 29, 48, 123, 23, 45, 78, 86, 23, 45, 67]} df = pd.DataFrame(data, columns = ['currency', 'cost']) df df table: I want to add a new column that assigns a 1 when a condition is met. In my case, the condition is all rows between two specific currencies. For example, say that I want all the currencies between 'Dollar' and 'Pound'. My guess is I have to create a mask and use it as a conditional, that will say select all rows between the first 'Dollar' row and the last 'Pound' row (i.e. rows 3-10). I have problems creating that mask though, as the currencies are selected alphabetically: mask = (df['currency'] &gt;= 'Dollar') &amp; (df['currency'] &lt;= 'Pound') The above creates a new column with T in all currencies, except 'Yen'. I can see why the above is failing, but cannot think of a way of doing what I want. Note: The same names of the currencies will come in groups, e.g. 'Pounds' cannot be in rows 4-5 and then 8-10.
type: Question
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86757515
has answer: http://stackoverflow.com/a/49871357
downvote count: 0

http://stackoverflow.com/q/49823526
downvote count: 1
has comment: http://stackoverflow.com/comment/86663747
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86663018
has answer: http://stackoverflow.com/a/49824030
has comment: http://stackoverflow.com/comment/86663608
tagged with: python
has comment: http://stackoverflow.com/comment/86663391
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 2
answer count: 3
has body: I'm trying to scrape the New York State directory of trial judges. The site checks whether javascript is enabled and renders the page with a short warning about needing python. So I've been trying Selenium. However, when I run the following line by line in ipython or python, it is able to access the page fine. Then, if I run this from the command line (python scraper.py), the site renders with the javascript warning - but only the first time I hit the site. This happens: regardless of what browser I use, whether I run it as a headless browser or not, regardless of what cookies I try to set My code: import string import csv from selenium import webdriver # Start the browser browser = webdriver.Firefox() browser.get( "https://iapps.courts.state.ny.us/judicialdirectory/JudicialDirectory") print(browser.title) # You can run the above 4 lines directly in ipython, # but if running from the command line, the previous try will not work browser.get( "https://iapps.courts.state.ny.us/judicialdirectory/JudicialDirectory") print(browser.title) In case it's of import: I'm running this on Windows 10. Does anyone have any suggestions for how to debug this?
has answer: http://stackoverflow.com/a/49823819
upvote count: 3
accepted answer: http://stackoverflow.com/a/49823819
has title: Selenium behaves differently between ipython and a file
tagged with: selenium
has answer: http://stackoverflow.com/a/49823813
possible better answer: http://stackoverflow.com/a/49823813

http://stackoverflow.com/comment/86579738
has text: @iam.Carrot The object returned from `zip.open` is a file-like object that you should be able to feed directly to `pandas.read_csv`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49782154
type: Comment

http://stackoverflow.com/comment/123869138
has text: The `--use-local` flag should also work just fine in this case.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/66921758

http://stackoverflow.com/comment/86625124
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49804670
score: 0
has text: Does `testpython.py` run when used as Python script? What is the resulting `y`? (shape, dtype). Depending on the MATLAB source, the loadmat dictionary can be quite complicated.

http://stackoverflow.com/a/50402381
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49831205
answers question: http://stackoverflow.com/q/49831205
type: Answer
score: 4
upvote count: 4
has body: I encountered the similar problem. I found that the new process created by multiprocessing calls setuptools.setup method when the test is executed via setup.py and this affects something. (I'm not clear about the root cause...) In my case, this setup.py resolved that. #!/usr/bin/env python import setuptools if __name__ == '__main__': setuptools.setup( name = "my_package", ...., )
type: AcceptedAnswer

http://stackoverflow.com/comment/86703976
type: Comment
has text: Is `depth = [0.5,1.0,1.5,2.0,2.5)` given or to be computed?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49844496

http://stackoverflow.com/q/49877422
downvote count: 0
tagged with: python
tagged with: keras
answer count: 1
tagged with: conv-neural-network
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49877684
has answer: http://stackoverflow.com/a/49877684
tagged with: tensorflow
favorite count: 0
has title: keras conv1d input data reshape
has body: I am trying to use 1-dimensional CNN for binary Classification in Keras. I have a machine which continuously performs an action and my goal is to classify if that action is normal or anomalous. To monitor the behaviour of each action, there are 4 sensors that collect 100 measurements. Thus, for each action, I have 4x100 = 400 data points. In a separate file, I have the label correspondig to each action. My dataset looks like this: measurement ID | action ID | sensor 1 | sensor 2 | sensor 3 | sensor 4 | ----------------------------------------------------------------- 1 | 1 | 42.3 | 42.3 | 42.3 | 42.3 | 2 | 1 | 42.3 | 42.3 | 42.3 | 42.3 | 3 | 1 | 42.3 | 42.3 | 42.3 | 42.3 | ... | .... | .... | .... | .... | .... | 100 | 1 | 42.3 | 42.3 | 42.3 | 42.3 | 1 | 2 | 42.3 | 42.3 | 42.3 | 42.3 | 2 | 2 | 42.3 | 42.3 | 42.3 | 42.3 | 3 | 2 | 42.3 | 42.3 | 42.3 | 42.3 | ... | .... | .... | .... | .... | .... | 100 | 2 | 42.3 | 42.3 | 42.3 | 42.3 | ... | .... | .... | .... | .... | .... | My problem is how can I reshape this dataset to apply a convd1 in Keras. Also how to assign a label to a bunch of vectors. Note that my dataset is composed of 10,000 actions. My assumption is that I have 4 channels (dimensions) and a vector of 100 values for each one, so my input shape should be (maxlen=100, dimension=4). Maybe I am totally wrong. The model should look like this: model = Sequential() model.add(Conv1D(filters=64, kernel_size=5 activation='relu',input_shape=(100,4))) model.add(MaxPooling1D(pool_size=2)) model.add(Flatten()) model.add(Dense(1, activation='sigmoid')) sgd = SGD(lr=0.1, momentum=0.9, decay=0, nesterov=False) model.compile(loss='binary_crossentropy', optimizer=sgd) model.fit(trainX, trainY, validation_data=(testX, testY), epochs=100, batch_size=100) Can anyone point me which is the correct way to achieve this?
type: Question
upvote count: 2
score: 2

http://stackoverflow.com/a/49840552
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49840417
downvote count: 0
has body: I will suggest you to open and close file within your threads. When you start a non blocking thread the procedural code moves to the next line and calls fp.close(). So you will see this exception. you can work around this by opening and closing the file within each runner.run . here is some example code to see how it works. https://arstechnica.com/civis/viewtopic.php?t=1234639 hope this helps
upvote count: 1

http://stackoverflow.com/a/49790662
has body: Have a look at multiprocessing module. Pool will do nicely with your task, so your code might look like that: from multiprocessing import Pool olx = OlxScraper() parallel_workers = 10 p = Pool(parallel_workers) p.map(olx.fetch_all_pages, list_of_urls)
has comment: http://stackoverflow.com/comment/86597133
answers question: http://stackoverflow.com/q/49790464
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/86597706
has comment: http://stackoverflow.com/comment/86597292
has comment: http://stackoverflow.com/comment/86606668
score: 1
downvote count: 0

http://stackoverflow.com/comment/86730274
score: 0
comment on: http://stackoverflow.com/q/49857856
type: Comment
type: QuestionComment
has text: generally: `d.get(k, 0)`. Google `python get dictionary method`

http://stackoverflow.com/q/49893932
has comment: http://stackoverflow.com/comment/87287480
has body: I am trying to install torch in windows to use with python. I have install torch and lua somehow. Then I tried using: conda install -c peterjc123 pytorch from this answer here. It seems to have succeeded and asks for a new package to be installed: The following NEW packages will be INSTALLED: pytorch: 0.3.1-py36_cuda80_cudnn6he774522_2 peterjc123 I don't have a GPU but thought it might use CPU (I am not sure about that but I proceeded anyway). The problem is that after the installation I cannot import it: import PyTorch ModuleNotFoundError: No module named 'pytorch' The code I tried was from here. Does this seem normal? I would expect an error regarding functionality or something not about importing the module. P.S. My initial intention is to run this code which uses torch. I am not sure how torch and pytorch are connected but I was hoping to make it work.
downvote count: 0
has comment: http://stackoverflow.com/comment/86814590
tagged with: pytorch
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86810014
linked to: http://stackoverflow.com/q/47943081
has comment: http://stackoverflow.com/comment/86811748
has comment: http://stackoverflow.com/comment/86808309
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/59965341
has comment: http://stackoverflow.com/comment/86814972
has title: Could not import pytorch in windows
type: UnansweredQuestion
tagged with: windows
tagged with: python

http://stackoverflow.com/comment/102443840
score: 0
has text: Possible duplicate of [How to exactly uninstall anaconda(python 3.6.4) from windows 7?](https://stackoverflow.com/questions/50031900/how-to-exactly-uninstall-anacondapython-3-6-4-from-windows-7)
comment on: http://stackoverflow.com/q/49847266
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49857124
type: Answer
has comment: http://stackoverflow.com/comment/86728706
answers question: http://stackoverflow.com/q/49857002
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has body: the problem is already described in this answer. a quick fix is to use itertools.product: from itertools import product a = range(0, 1001) b = range(1, 1001) c = range(2, 1001) d = [] for x,y,z in product(a,b,c): print(x, y, z) if (x*x) + (y*y) == (z*z): d.append((x,y,z)) print(d) ...this is higly inefficient! this will be more efficient (not well tested!): from math import sqrt d = [] for z in range(1, 1001): z2 = z**2 for x in range(1, z//2 + 1): x2 = x**2 y = round(sqrt(z2 - x2)) if x2 + y**2 == z2: d.append((x, y, z)) this will have one entry for each triplet only; i.e. only (3, 4, 5) will be in the resulting list; (4, 3, 5) will not be there - you may add those 'duplicates' separately if you need them...
accepted answer of: http://stackoverflow.com/q/49857002

http://stackoverflow.com/comment/86686227
has text: But isn't my return(infile) unnecessary then, because I never use it?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49835468
type: AnswerComment

http://stackoverflow.com/q/49849044
has comment: http://stackoverflow.com/comment/87173700
tagged with: pyqt
has answer: http://stackoverflow.com/a/49849086
upvote count: 1
tagged with: windows
possible better answer: http://stackoverflow.com/a/49849086
downvote count: 1
tagged with: pyqt5
has answer: http://stackoverflow.com/a/50121274
favorite count: 0
type: Question
answer count: 2
tagged with: pyinstaller
has title: Trouble Compiling PyQt5 Python app with PyInstaller
has comment: http://stackoverflow.com/comment/86712775
tagged with: python
has body: I've seen a few posts saying this issue is resolved in the, but I'm still not able to successfully compile with Python 3.6.4, PyQt 5.10.1, and Pyinstaller 3.3.1. Getting a ton of warnings (like the one below) and the resulting executable isn't working. WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of C:\users\justin\appdata\local\programs\python\python36-32\lib\site-packages\PyQt5\Qt\plugins\bearer\qgenericbearer.dll type errors. I tried including the python directory in my command, but no dice. Currently using this command: pyinstaller --paths "C:\Users\Justin\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\PyQt5\Qt\bin" "..\main.py" Anyone run into this issue?
accepted answer: http://stackoverflow.com/a/50121274
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/86827348
score: 0
has text: are you absolutely sure that the datetime is 1000% the same? consider testing this again with hardcoded datetime value
comment on: http://stackoverflow.com/q/49905732
type: Comment
type: QuestionComment

http://stackoverflow.com/a/79529188
answers question: http://stackoverflow.com/q/49845914
score: 0
has body: It's a shame no-one answered this question, as it is sometimes useful to be able to put something like this together without reaching for requests - fine though that library is. Below is a minimal example of the approach you might take. There are plenty of areas in which it could/should be made more rigorous, but this alters the OP's code as little as possible. import http.client def grab_url(host, path = '/'): class Data: pass result = Data() try: con = http.client.HTTPConnection(host) while True: con.request('GET', path) response = con.getresponse() if response.status not in (301, 302, 303, 307, 308): break path = response.getheader('Location') response.close() if response.status == 200: result.content = response.read().decode('utf-8') result.headers = response.getheaders() except Exception as e: print(e) return result Here are some areas you might want to elaborate on: Treat the different redirect codes separately where necessary. Because the existing code is only implementing GET requests, there is less urgency to change much. Rationalise how and where the raw response is read (e.g. in the Data class?) Note, for example, how you have to close the response before trying another request (unless it has been fully read, which closes it, or if is is used in a with statement). Limit the number of consecutive redirects in case of a weird server configuration. The webserver should prevent an infinite loop, but even so... I guess it is fair to say there is not an automatic way to follow redirects because there are multiple possibilites to think about, but it should still be possible to implement something lightweight that works.
type: Answer

http://stackoverflow.com/comment/138633486
score: 0
type: AnswerComment
has text: Running `get-pip.py` via `python3` encounters the same `timeout` issue. So it doesn't help with anything
comment on: http://stackoverflow.com/a/49769015
type: Comment

http://stackoverflow.com/comment/86566850
comment on: http://stackoverflow.com/q/49775515
type: Comment
type: QuestionComment
has text: maybe matplotlib ?
score: 0

http://stackoverflow.com/comment/86834759
has text: In file.save() function it seems that the second argument is the file's name, Why don't you change it?
comment on: http://stackoverflow.com/q/49900621
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86618383
score: 0
type: AnswerComment
has text: @BillKet Given columns that have constant widths, it is probably possible to write a function that detects the columns. Basically you would need two passes over the whole table. The first pass to detect the column widths. The second pass to do the splitting.
comment on: http://stackoverflow.com/a/49801602
type: Comment

http://stackoverflow.com/comment/86835991
comment on: http://stackoverflow.com/a/49907801
type: Comment
score: 0
type: AnswerComment
has text: Thanks for your answer. Perhaps I should have clarified that a team will play once per week. When I ran your code, it looks like foo is a 465 x 8 matrix. The 105 pairs are the possible sets of 4 pairings of 8 teams. There should be 4! permutations of each of these, thus having 2520 possible matchups for a specific week. Since there are 12 weeks, that means the number of possible schedules is 2520 choose 12 which is a number that is 33 digits long! However many of these include teams that play each other more than twice...

http://stackoverflow.com/comment/86708027
has text: It's not clear to me what you mean. What other elements? Can you [edit](https://stackoverflow.com/posts/49846461/edit) your question and specify all comparisons you want to make?
score: 0
comment on: http://stackoverflow.com/q/49846461
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86771350
score: 0
type: Comment
type: AnswerComment
has text: @Foon, see link in update on how this can be done better than O(n).
comment on: http://stackoverflow.com/a/49877797

http://stackoverflow.com/comment/86784667
score: 0
has text: So does every line have "x" at the beginning? Or just (C)?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49884307

http://stackoverflow.com/a/49848646
type: AcceptedAnswer
upvote count: 5
accepted answer of: http://stackoverflow.com/q/49848597
has body: You could use an efficient repeat-based solution followed by groupby: from itertools import chain # Step 1 - flatten your dataframe df = pd.DataFrame({ 'group' : df['group'].repeat(df.sequence.str.len()), 'char' : list(chain.from_iterable(df.sequence.tolist())) }) # Step 2 - filter out characters and groupby on `group` df[df.char.str.isalpha()].groupby(['group', 'char']).size().reset_index(name='freq') group char freq 0 A B 3 1 A X 3 2 B B 3 3 B C 1 4 B F 1 5 B S 5 6 B X 1
type: Answer
answers question: http://stackoverflow.com/q/49848597
score: 5
downvote count: 0

http://stackoverflow.com/comment/86681313
comment on: http://stackoverflow.com/q/49832548
score: 0
type: Comment
type: QuestionComment
has text: Then you first need to fix your CSV generation. Is that also generated using Python?

http://stackoverflow.com/comment/86832641
has text: Don't take the square root of negative numbers
type: QuestionComment
score: 8
type: Comment
comment on: http://stackoverflow.com/q/49908354

ngrok
tag name: ngrok
tags question: http://stackoverflow.com/q/49845585
tags question: http://stackoverflow.com/q/49769523
type: Tag

http://stackoverflow.com/comment/86537497
type: Comment
comment on: http://stackoverflow.com/a/49758277
has text: What is the sum(1) doing?
score: 0
type: AnswerComment

http://stackoverflow.com/a/49897278
has comment: http://stackoverflow.com/comment/86812557
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86827253
has body: view isn't an argument that is passed to the TextCommand's run method. Instead, it is a property on self. Changing it to the following should work: import sublime import sublime_plugin class ExampleCommand(sublime_plugin.TextCommand): def run(self, edit): view = self.view try: host = view.settings().get('remote_subl.host') print(host) if host == 'dsintmain': view.settings().set( 'color_scheme', 'Packages/Color Scheme - Default/Mariana.tmTheme') print(view.settings().get('color_scheme')) except: print("Not on remote_host") pass I would also recommend printing the exception that occurs to help debug things like this in future. Even better, rather than expecting an exception in normal usage, provide a default value to the get method on the settings (i.e. None) and remove the exception handling altogether. host = view.settings().get('remote_subl.host', None) That way, if something does really go wrong, you'll see the traceback in the ST console.
accepted answer of: http://stackoverflow.com/q/49897187
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49897187

http://stackoverflow.com/comment/86726469
type: QuestionComment
has text: I have added the source image here.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49854608

http://stackoverflow.com/q/49773964
accepted answer: http://stackoverflow.com/a/49774114
has answer: http://stackoverflow.com/a/49774114
type: Question
tagged with: firebird
answer count: 1
downvote count: 0
upvote count: 1
has body: I have a Firebird database in ISO-8859-1 encoding, but I can't seem to get the right way to set it in my connection. I have tried: conn = fdb.connect(dsn='mydatabase.fdb', user='***', password='***', charset='latin_1') Which gives me this error: Error while connecting to database: - SQLCODE: -924 - bad parameters on attach or create database - CHARACTER SET LATIN_1 is not defined', -924, 335544325 Trying iso-8859 gives unknown encoding: ISO-8859. How can I set my Firebird connection to ISO-8859-1 character encoding?
favorite count: 0
type: AnsweredQuestion
has title: Setting the character set
score: 1
tagged with: python

http://stackoverflow.com/q/49888416
tagged with: list
has answer: http://stackoverflow.com/a/49888447
has body: I want to store two values from JSON_file in new dict like this : {[1,2,5]:[0], [1,2,4]:[2]} my JSON-file looks like this : { "index": [ { "timestamp": "2018-04-17 17:56:25", "src": "src", "dst": [1,2,5], "value": [0], "datatype": "datatype" }, { "timestamp": "2018-04-17 18:00:43", "src": "src", "dst": [1,2,4], "value": [2], "datatype": "datatype" } ] } I wrote this code: with open(filename) as feedjson: json_data = json.load(feedjson) feedjson.close() list_dev = {} for i in json_data["index"]: key = i['value'] value = i['dst'] list_dev[key] = value print(list_dev) I get this error: list_dev.update({key: value}) TypeError: unhashable type: 'list' can someone help me to fix this problem please?
has comment: http://stackoverflow.com/comment/86793218
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/86793105
accepted answer: http://stackoverflow.com/a/49888447
linked to: http://stackoverflow.com/q/24217647
possible better answer: http://stackoverflow.com/a/49888886
tagged with: python
linked to: http://stackoverflow.com/q/13675296
tagged with: dictionary
has answer: http://stackoverflow.com/a/49888886
has title: Store two values from JSON_file in new dictionary with python
has comment: http://stackoverflow.com/comment/86793161
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49909841
tagged with: scikit-learn
downvote count: 1
has title: scikit-learn classification report - Precision and F-score are ill-defined and being set to 0.0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49910039
has body: I am using scikit-learn to compute classification record, when I try to print it, it gives a warning : print classification_report(original,predicted) Warning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. So I want to report precision and recall via micro averaging. How can I use classification report so that it results in not ill-defined precision and recall ? Thanks in advance.
score: 1
answer count: 1
tagged with: python
tagged with: precision-recall
accepted answer: http://stackoverflow.com/a/49910039
favorite count: 0
type: Question
upvote count: 2
tagged with: machine-learning

http://stackoverflow.com/comment/86544421
score: 0
comment on: http://stackoverflow.com/q/49764367
type: Comment
type: QuestionComment
has text: If you want to understand more about what's going on, see [here](https://stackoverflow.com/a/27826829/908494). (The details in that answer will not apply to you, but the way Steffen Ulrich gathered those details, and what they mean, are very similar.)

http://stackoverflow.com/a/49843529
has body: How about something like this? rdat[rdat==0]=np.nan np.nanmean(rdat, axis=1)
score: 0
answers question: http://stackoverflow.com/q/49843203
type: Answer

http://stackoverflow.com/comment/101685710
type: QuestionComment
has text: How about just `mypy .` to at least run it on packages?
comment on: http://stackoverflow.com/q/49862318
score: 4
type: Comment

http://stackoverflow.com/comment/86659818
comment on: http://stackoverflow.com/q/49821643
type: QuestionComment
type: Comment
score: 0
has text: I took your suggestion Mike but unfortunately it broke large portions of my code. I am open to any suggestions given. I am still learning and also new to this site. If I am submitting something incorrectly I will gladly go back and fix it.

http://stackoverflow.com/comment/86580387
type: AnswerComment
comment on: http://stackoverflow.com/a/49781350
type: Comment
has text: @tgrandje I have added the versions of my libraries, what versions do you have?
score: 0

http://stackoverflow.com/comment/86773463
comment on: http://stackoverflow.com/q/49878329
has text: @dirn I removed it from my requirements.txt but it doens't change a thing since I do an import in my code
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49894976
has body: It is not the bound vertex buffer object, which define an array of generic vertex attribute data, but it is the state which is stored in the default vertex array object. When you call glVertexAttribPointer the the array of generic vertex attribute data is defined. If at this point, an array buffer is bound, then the array definition refers to the buffer object. This means you have to switch the array definition, before you draw the object: # define an array of generic vertex attribute data which refers to "vbo" glBindBuffer(GL_ARRAY_BUFFER, vbo) glVertexAttribPointer(posAttrib, 3, GL_FLOAT, False, 0,ctypes.cast(0, ctypes.c_void_p)) glEnableVertexAttribArray(posAttrib) glDrawArrays(GL_TRIANGLES, 0, 3) # define an array of generic vertex attribute data which refers to "vbo2" glBindBuffer(GL_ARRAY_BUFFER, vbo2) glVertexAttribPointer(posAttrib, 3, GL_FLOAT, False, 0,ctypes.cast(0, ctypes.c_void_p)) glEnableVertexAttribArray(posAttrib) glDrawArrays(GL_TRIANGLES, 0, 3) As an alternative you can use 2 Vertex Array Objects: # vertex data 1 vertices=[1.5, -0.5, -4.0, 0.5, -0.5, -4.0, 0.5, 0.5, -4.0] nparray = np.array(vertices,dtype=np.dtype('&lt;f4')) vbo=glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, nparray, GL_STATIC_DRAW) # vertex data 2 vertices=[2., -0.5, -4.0, -0.5, -0.5, -2.0, 0.5, 0.5, -1.0] nparray = np.array(vertices,dtype=np.dtype('&lt;f4')) vbo2=glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo2) glBufferData(GL_ARRAY_BUFFER, nparray, GL_STATIC_DRAW) # vertex array object 1 vao=glGenVertexArrays(1) glBindVertexArray(vao) glBindBuffer(GL_ARRAY_BUFFER, vbo) glEnableVertexAttribArray(posAttrib) glVertexAttribPointer(posAttrib, 3, GL_FLOAT, False, 3*4,ctypes.cast(0, ctypes.c_void_p)) # vertex array object 2 vao2=glGenVertexArrays(1) glBindVertexArray(vao2) glBindBuffer(GL_ARRAY_BUFFER, vbo2) glEnableVertexAttribArray(posAttrib) glVertexAttribPointer(posAttrib, 3, GL_FLOAT, False, 3*4,ctypes.cast(0, ctypes.c_void_p)) glBindBuffer(GL…
accepted answer of: http://stackoverflow.com/q/49894819
has comment: http://stackoverflow.com/comment/86811343
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49894819
type: Answer

http://stackoverflow.com/q/49788330
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49788544
has answer: http://stackoverflow.com/a/57102176
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86617110
tagged with: python
score: 4
tagged with: escaping
upvote count: 4
answer count: 3
has comment: http://stackoverflow.com/comment/86616222
has comment: http://stackoverflow.com/comment/86591682
downvote count: 0
has title: how to escape semicolons when writing to csv in python
has body: I have a list of lists in python that represents data to be written in a csv file. My code for that is : for n, d, p in zip(names, dates, posts): writer.writerow([i, n, d, p]) However, some of the strings in posts contain semicolons, and this creates new cells in the csv. I've looked online and tried setting quoting=csv.QUOTE_ALL wrapping each post string inside double quotes wrapping the semicolons inside double quotes using normal python write instead of csv.writer Nothing's worked so far. Any help, every online answer to escaping comma's I've found involves (1) or (2) which doesn't work for me. Please help! Edit: Here's an example of what I mean When I write the row ['a', 'b', 'c', 'd;e'], the d and e get put into different cells, like: a | b | c | d | e As opposed to what I want, which is: a | b | c | d;e
has answer: http://stackoverflow.com/a/49788423

http://stackoverflow.com/comment/86598476
type: Comment
has text: Sure but neither of those do what I want for other inputs. If this is expected behavior of QUOTE_MINIMAL, then it's at least undocumented and uninuitive.
type: AnswerComment
comment on: http://stackoverflow.com/a/49791869
score: 0

http://stackoverflow.com/q/49903319
has title: Simple way to calculate padding based on modulo/remainder
has comment: http://stackoverflow.com/comment/86822571
has comment: http://stackoverflow.com/comment/86822681
has comment: http://stackoverflow.com/comment/86822643
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86823445
tagged with: padding
tagged with: modulo
has comment: http://stackoverflow.com/comment/86822334
has answer: http://stackoverflow.com/a/49903532
has answer: http://stackoverflow.com/a/49903779
linked to: http://stackoverflow.com/q/20309255
downvote count: 0
has answer: http://stackoverflow.com/a/49903431
linked to: http://stackoverflow.com/q/394809
has body: If I have a string of length L=77 that I want to pad to a length that is a multiple of N=10. I am interested in computing just the amount of padding required. This can be easily done with N - (L % N), except for cases where L % N is zero. I have been using the following for now: pad = (N - (L % N)) % N This does not seem particularly legible, so sometimes I use pad = N - (L % N) if pad == N: pad = 0 It seems overkill to use three lines of code for something so simple. Alternatively, I can find the k for which k * N &gt;= L, but using math.ceil seems like overkill as well. Is there a better alternative that I am missing? Perhaps a simple function somewhere?
has comment: http://stackoverflow.com/comment/86823320
possible better answer: http://stackoverflow.com/a/49903759
favorite count: 0
accepted answer: http://stackoverflow.com/a/49903694
type: Question
has answer: http://stackoverflow.com/a/49903759
score: 5
has comment: http://stackoverflow.com/comment/86822567
has answer: http://stackoverflow.com/a/49903694
answer count: 5
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/86823216

http://stackoverflow.com/comment/86666485
type: Comment
type: QuestionComment
score: 0
has text: It would be worth synopsising the new stack trace in the question, since relying on an external pasteboard would make the question off-topic. We have this guideline because external links break quite frequently, leaving the site with a question that cannot be understood by future readers, and leaving volunteers to clean it up. Would you extract the most useful messages from that log data and paste that into the question? I think it's OK to add the link in addition to that.
comment on: http://stackoverflow.com/q/49820329

http://stackoverflow.com/q/49901691
has body: I have dataframe and I use to_dict to convert it into a dictionary. Sample code here. data = data_raw.head(1000) start = time.time() model = data.set_index('modelid-a')['modelname-a'].to_dict() end = time.time() print('Finished model') print(end - start) For 1000 rows, the compute time is 0.002429 seconds. For 2000 rows, the compute time is 0.002743 seconds. For 5000 rows, the compute time is 0.004242 seconds. For 10,000 rows, the compute time is 0.008217 seconds. For 20,000 rows, the compute time is 0.571163 seconds. For 50,000 rows, the compute time is 19.83438 seconds. For 70,000 rows, the compute time is 47.33981 seconds. When I go up to 150,000, the compute time is 1789 seconds. This is painfully slow. What can I do to optimize this?
favorite count: 0
type: Question
has title: Python Pandas to_dict compute time slow and nonlinear
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86819138
has comment: http://stackoverflow.com/comment/86818783
answer count: 0
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1

http://stackoverflow.com/a/49832945
has body: Please change the following line sp.scatter(attributes[:, 0], attributes[:, 1], attributes[:, 2]) to sp.scatter(result[:, 0], result[:, 1], result[:, 2])
accepted answer of: http://stackoverflow.com/q/49832658
answers question: http://stackoverflow.com/q/49832658
type: Answer
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/49870129
accepted answer of: http://stackoverflow.com/q/49869207
answers question: http://stackoverflow.com/q/49869207
has comment: http://stackoverflow.com/comment/86762007
has comment: http://stackoverflow.com/comment/86761028
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86837969
score: 2
has body: I suggest create list of tuples first by append by tuples without [index] and then call DataFrame constructor like: count = 0 L = [] df2 = pd.DataFrame(); for index, row in df1.iterrows(): doc = nlp(unicode(row)) text_ext = textacy.extract.subject_verb_object_triples(doc) #remove join index mylist = list(text_ext) count+=1; #append to list L.append(mylist) df2 = pd.DataFrame(L, index=df1.index) print (df2) 0 1 1 (dwstweets gop, broadened, base people) None 2 (bushs campaign video, features, kat) None 3 None None 4 None None 5 None None 6 (president obama, wants, york) None 7 (jeb bush, talked, enforcement) (lets, see, plan)
type: Answer

http://stackoverflow.com/a/49805428
type: AcceptedAnswer
upvote count: 2
has comment: http://stackoverflow.com/comment/86667224
answers question: http://stackoverflow.com/q/49805375
downvote count: 0
has body: Your trying to load Tensorflow while your current working directory is where the sources are. Just launch python outside this directory. It is a known issue: https://github.com/tensorflow/tensorflow/issues/16264
type: Answer
accepted answer of: http://stackoverflow.com/q/49805375
score: 2

http://stackoverflow.com/comment/86840056
comment on: http://stackoverflow.com/a/49912088
has text: i have tired so and it gives: except PlxScriptingError: NameError: name 'PlxScriptingError' is not defined @Bennett Brown
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86899132
type: AnswerComment
has text: @max9111 The numba version is 0.35.0, and yes, I always make sure to warm the compiled version by calling it with different arguments of the same types (to generate the compiled version), before the timeit statement. I consistently see the speed I listed for my machine, but your results suggest it can be even faster with additional optimization. Really the only point is that `np.tile` should be avoided because of its significant extra memory overhead.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49929395

http://stackoverflow.com/comment/86813633
has text: Possible duplicate of [<Django object > is not JSON serializable](https://stackoverflow.com/questions/16790375/django-object-is-not-json-serializable)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49898084

http://stackoverflow.com/a/49905889
answers question: http://stackoverflow.com/q/49905484
has comment: http://stackoverflow.com/comment/86828649
has comment: http://stackoverflow.com/comment/86829018
has comment: http://stackoverflow.com/comment/86829541
has body: Your view doesn't receive a POST request because you didn't provide an action attribute to your form tag. So, your form passes your POST request nowhere. Try it like this: &lt;form action="" method="post"&gt; {% csrf_token %} {{ user_form.as_p }} &lt;input type="submit" name="btn btn-primary" value="Save"&gt; &lt;/form&gt; Also, you should definitely check django's built-in generic views: CreateView and UpdateView. They serve exactly for such purposes and makes almost everything for you.
score: 0
has comment: http://stackoverflow.com/comment/86829186
has comment: http://stackoverflow.com/comment/108920233
has comment: http://stackoverflow.com/comment/86827858
has comment: http://stackoverflow.com/comment/86828000
has comment: http://stackoverflow.com/comment/86828399
has comment: http://stackoverflow.com/comment/86829413
type: Answer

http://stackoverflow.com/comment/126785655
has text: @DeanO I don't understand the question, this is an rruleset, not an rrule.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49765385
score: 0

http://stackoverflow.com/comment/86812619
score: 0
type: AnswerComment
has text: Fixed, i have just realized about the dropout keep probability. It was set to 0.5 then the model activate different networks of the model in each cost run. If I set keep prob =1.0 the result outputs the same in the two consecutive runs. Thanks Peter for your help
type: Comment
comment on: http://stackoverflow.com/a/49826833

http://stackoverflow.com/a/78418526
has body: Also a simple reminder that the most generalised option is to just open search. For example, if OpenCV docs are placed at https://docs.opencv.org/4.x, then OpenCV via Google: https://www.google.com/search?q=&quot;{element.name}&quot; {element.qname} site:https://docs.opencv.org/4.x or via DuckDuckGo: https://duckduckgo.com/?q={element.qname} site:docs.opencv.org In the next list, it's also a search approach, but specifically over the official doc site. Different from the answer above: requires an additional click on the search page, but also a bit more robust and gives overview of documentation: matplotlib https://matplotlib.org/stable/search.html?q={element.qname} numpy https://numpy.org/doc/stable/search.html?q={element.qname} pandas https://pandas.pydata.org/pandas-docs/stable/search.html?q={element.qname} PIL https://pillow.readthedocs.io/en/stable/search.html?q={element.qname} PySide6 (Qt) https://doc.qt.io/qtforpython-6/search.html?q={element.qname} Tkinter (or any default lib) https://docs.python.org/3/search.html?q={element.qname} nltk https://www.nltk.org/search.html?q={element.qname}&amp;check_keywords=yes&amp;area=default rpy2 https://rpy2.github.io/doc/latest/html/search.html?q={element.qname}
type: Answer
answers question: http://stackoverflow.com/q/49777474
score: 1
downvote count: 0
upvote count: 1

intellij-idea
tags question: http://stackoverflow.com/q/49828755
type: Tag
tag name: intellij-idea

http://stackoverflow.com/comment/86917937
type: QuestionComment
comment on: http://stackoverflow.com/q/49912727
has text: what I mean is that you can use a big query query as the source/input for your dataflow pipeline. In general, that approach scales much further than dataflow reading in entirety of tables on its own.
score: 1
type: Comment

http://stackoverflow.com/comment/86842652
has text: Please post the source code as text, images are difficult to debug. Just paste the code and format it using Ctrl+K.
type: QuestionComment
comment on: http://stackoverflow.com/q/49913211
score: 0
type: Comment

http://stackoverflow.com/a/49768526
has comment: http://stackoverflow.com/comment/86553379
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86553058
has comment: http://stackoverflow.com/comment/86553126
upvote count: 1
answers question: http://stackoverflow.com/q/49768405
downvote count: 0
has comment: http://stackoverflow.com/comment/86554488
has comment: http://stackoverflow.com/comment/86553435
has body: first you have to initialise the variables like this : y1=[213,23,23,12,22,12,21,21] occurance1 = [] unaccured = [] for i in x: ..... You can do like this to pass : context = {'occurance1': occurance1,'unaccured': unaccured} return render(request,'web/base.html', context) and in your html it will be good if you do like this : {% if occurance1 %} {% for occurance in occurance1 %}

http://stackoverflow.com/comment/86829173
has text: @birsingh Well guess I better brush up on my regex then. I found a library called geograpy tho, struggling to install it since it appears to be an old one but if I do manage I'll edit my post.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49906454

http://stackoverflow.com/comment/86734201
type: QuestionComment
comment on: http://stackoverflow.com/q/49859528
has text: you can't do that in aws, please read here https://stackoverflow.com/questions/45433446/aws-elasticsearch-synonyms-using-file
score: 1
type: Comment

http://stackoverflow.com/a/49790872
score: 1
type: Answer
has body: Subprocess.call does not return stdout so you need to use Popen instead. Here is what you can do . import subprocess count = subprocess.Popen("ls -l | awk '{print $1}' | wc -l",stdout = subprocess.PIPE, shell=True) print(count.stdout.readlines())
downvote count: 0
answers question: http://stackoverflow.com/q/49790621
upvote count: 1

http://stackoverflow.com/q/49843864
accepted answer: http://stackoverflow.com/a/49843897
answer count: 2
has answer: http://stackoverflow.com/a/49844212
upvote count: 3
has answer: http://stackoverflow.com/a/49843897
has comment: http://stackoverflow.com/comment/86706121
downvote count: 0
linked to: http://stackoverflow.com/q/34835951
has body: I have a Pandas Dataframe with a column (ip) with certain values and another Pandas Series not in this DataFrame with a collection of these values. I want to create a column in the DataFrame that is 1 if a given line has its ipin my Pandas Series (black_ip). import pandas as pd dict = {'ip': {0: 103022, 1: 114221, 2: 47902, 3: 23550, 4: 84644}, 'os': {0: 23, 1: 19, 2: 17, 3: 13, 4: 19}} df = pd.DataFrame(dict) df ip os 0 103022 23 1 114221 19 2 47902 17 3 23550 13 4 84644 19 blacklist = pd.Series([103022, 23550]) blacklist 0 103022 1 23550 My question is: how can I create a new column in df such that it shows 1 when the given ip in the blacklist and zero otherwise? Sorry if this too dumb, I'm still new to programming. Thanks a lot in advance!
has comment: http://stackoverflow.com/comment/86703731
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49844212
type: AnsweredQuestion
score: 3
tagged with: pandas
tagged with: dataframe
tagged with: python
linked to: http://stackoverflow.com/q/12065885
tagged with: python-3.x
has title: How to create a dummy variable in Pandas Dataframe if a column matches certain values?

http://stackoverflow.com/q/49866207
type: Question
has answer: http://stackoverflow.com/a/49869394
tagged with: seaborn
tagged with: python
has title: Why is an intercept displayed incorrectly when plotting regression with Seaborn?
tagged with: plot
has comment: http://stackoverflow.com/comment/86748052
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: linear-regression
accepted answer: http://stackoverflow.com/a/49869394
tagged with: regression
has body: I've built a linear regression model to examine a relationship between two variables (chemical_1 and chemical_2) from this dataset. According to the results, intercept = 16.83488364225717. I've just started discovering the math basics of data science and my current understanding of an intercept is that it's the value where the regression line crosses the y-axis (and x=0). So now I'm confused with the resulting plot built with Seaborn. Why does it show the regression line crossing y-axis between 10 and 12, not at the actual value of an intercept (16.83488364225717) and x=0? What should I do to fix that? Here is my code: from scipy import stats X = df['chemical_1'] Y = df['chemical_2'] slope, intercept, r_value, p_value, slope_std_error = stats.linregress(X,Y) print ("slope = " + str(slope)) print ("intercept = " + str(intercept)) print ("r_squared = " + str(r_value**2)) print ("r_value = " + str(r_value)) print ("p_value = " +str(p_value)) slope = -0.9345759557752411 intercept = 16.83488364225717 r_squared = 0.04205938806347038 r_value = -0.20508385617466426 p_value = 0.00784469031490164 predict_y = slope * X + intercept fig, ax = plt.subplots() sns.set(color_codes=True) sns.set(rc={'figure.figsize':(10, 10)}) ax = sns.regplot(x=X, y=Y, line_kws={'label':'$y=%3.7s*x+%3.7s$'%(slope, intercept)}); sns.regplot(x=X, y=Y, fit_reg=False, ax=ax); sns.regplot(x=X, y=predict_y,scatter=False, ax=ax); ax.set_ylabel('chemical_2') ax.legend() plt.show() UPD: when I'm using the solution proposed by Simon - extending the limits of the axes, the intercept is still not shown and the plot looks like this: When I use set_ylim(0,20), the data on the plot looks squeezed. Actually any axis parameters that I set (other than defaults) result in the data and the confidence interval on the plot look squeezed.
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86748142
favorite count: 0

http://stackoverflow.com/comment/86635094
comment on: http://stackoverflow.com/q/49810268
score: 0
type: QuestionComment
has text: Give the sample content of the data file you are using.
type: Comment

http://stackoverflow.com/q/49914613
tagged with: cmd
has comment: http://stackoverflow.com/comment/86844737
favorite count: 0
type: Question
has body: basic scenario: building an interpreter for some basic scripting language, I need to specify the file to run, so that I could, in CMD type $ customlang /path/to/file/file.lang I've looked into argparse, but what i've seen is that it parses arguments in the form of --argument which isn't quite what I'm looking for. Any suggestions? thanks
score: 0
has comment: http://stackoverflow.com/comment/86844833
has comment: http://stackoverflow.com/comment/86845008
accepted answer: http://stackoverflow.com/a/49914716
upvote count: 1
linked to: http://stackoverflow.com/q/1009860
has answer: http://stackoverflow.com/a/49914716
downvote count: 1
has title: Pass CMD Arguments to python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86844823
tagged with: command-line-arguments
answer count: 1
tagged with: python

http://stackoverflow.com/a/49791637
type: Answer
has comment: http://stackoverflow.com/comment/86599250
has comment: http://stackoverflow.com/comment/86598842
answers question: http://stackoverflow.com/q/49791305
has comment: http://stackoverflow.com/comment/86599617
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86602344
has body: import math ... x = 0 for i in range(1,1001): x = x + (1 / (((2 * i - 1) ** 2) * ((2 * i + 1) ** 2))) z = math.sqrt((x * 16) + 8) error = abs(z - math.pi) if error &lt; 10 ** -8: print(i) break
accepted answer of: http://stackoverflow.com/q/49791305

http://stackoverflow.com/comment/86892072
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49870315
has text: but for my flask function im getting `An uncaught exception happened while servicing this request. You can investigate this with the `zappa tail` command` pls help
score: 0

http://stackoverflow.com/a/49865911
has comment: http://stackoverflow.com/comment/86747532
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49865741
has body: if u just need hex dump of PCAP tshark -x -r mydata.pcap | sed -n 's/^[0-9a-f]*\s\(\(\s[0-9a-f][0-9a-f]\)\{1,16\}\).*$/\1/p'

http://stackoverflow.com/q/49798099
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/86611301
has comment: http://stackoverflow.com/comment/86610866
tagged with: dataframe
tagged with: python
has title: How to resolve strange problems with combining 3 lists into 1 DataFrame?
linked to: http://stackoverflow.com/q/49620538
has body: I am trying to combine 3 lists, each of size 10 rows x 25 columns, into one list of size 10 x 75, and then write the result to a csv file. But all my attempts at using straightforward approaches fail, and I cannot figure out why - and how to fix it. The lists are produced by one and the same function. The column heads of the lists are identical, except for a number that has been added to the column name to distinguish them, as follows. def do_stuff(x): producing 10 x 25 list # Producing list 1 from document 1 df = pd.read_csv("file1.csv", encoding = "utf-8") # open file 1 df1 = do_stuff(df) # Producing list 2 from document 2 df = pd.read_csv("file2.csv", encoding = "utf-8") # open file 2 df2 = do_stuff(df) # Producing list 3 from document 3 df = pd.read_csv("file3.csv", encoding = "utf-8") # open file 3 df3 = do_stuff(df) The data in each of the lists df1, df2, df3 looks something like this: # List df1 # List df2 [col_A1 Col_B1 Col_C1 etc [col_A2 Col_B2 Col_C2 ... 0 0.96 0.13 0.63. 0 0.56 0.22 0.31 1 0.21 0.33 0.44. 1 0.37 0.92 0.77 .. .. 9 0.11 0.12 0.99] 9 0.34 0.54 0.42] Attempt 1 To combine these lists into one DataFrame, I have tried: df1 + df2 + df3 However, this leads to NaN's across the dataset: # List df1 # List df2 [col_A1 Col_B1 Col_C1 etc [col_A2 Col_B2 Col_C2 ... 0 NaN NaN NaN 0 NaN NaN NaN 1 NaN NaN NaN 1 NaN NaN NaN .. .. 9 NaN NaN NaN] 9 NaN NaN NaN] Attempt 2 I have also tried the following, but get an error: df_total.append(df1) # add result to list df_total.append(df2) # add result to list df_total.append(df3) # add result to list df_total.to_csv("result.csv", index=False) AttributeError: 'list' object has no attribute 'to_csv' Attempt 3 I have tried to make sure to get a DataFrame which can be written to a csv: df_total.append(df1) # add result to list df_total.append(df2) # add result to list df_total.append(df3) # add result to list df = pd.DataFrame([df_total]) df = pd.concat(df) But this gives NaN values across the dataset: col_A1 col_B1 col_…
has comment: http://stackoverflow.com/comment/86610929
type: Question
tagged with: python-3.x
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/86611256
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/49620538
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86611450
has comment: http://stackoverflow.com/comment/86611764
favorite count: 0
has comment: http://stackoverflow.com/comment/86611054
has comment: http://stackoverflow.com/comment/86611086

dictionary-attack
tag name: dictionary-attack
type: Tag
tags question: http://stackoverflow.com/q/49889088

http://stackoverflow.com/comment/86888360
type: Comment
type: QuestionComment
has text: I upload the St7API.py in dropbox https://www.dropbox.com/s/88plz2funjqy1vb/St7API.py?dl=0. I change the question in relation of what we discuss in this comments. Thank you for having tried to understand the problem.
score: 0
comment on: http://stackoverflow.com/q/49882728

http://stackoverflow.com/a/49759888
has comment: http://stackoverflow.com/comment/86536249
has comment: http://stackoverflow.com/comment/86536576
has comment: http://stackoverflow.com/comment/86536974
has comment: http://stackoverflow.com/comment/86537173
has comment: http://stackoverflow.com/comment/86535756
score: 0
has comment: http://stackoverflow.com/comment/86535418
has comment: http://stackoverflow.com/comment/86536632
has comment: http://stackoverflow.com/comment/86535914
answers question: http://stackoverflow.com/q/49759662
has comment: http://stackoverflow.com/comment/86536492
has body: This isnt really python related, but are you tagged as an owner of the bot? does the bot have permissions to type in the channel you are requesting it to type in? This is typically something you would ask the owner of the bot/help channel.
type: Answer
has comment: http://stackoverflow.com/comment/86537268

http://stackoverflow.com/comment/86742556
comment on: http://stackoverflow.com/a/49861947
type: AnswerComment
score: 0
has text: @CL. What do you mean by "belong in the first THEN", and why is it so? It seems to me that `myfunction` only appears in the *second* WHEN case, please correct me if I'm wrong. Thank you in advance.
type: Comment

http://stackoverflow.com/q/49819277
has comment: http://stackoverflow.com/comment/86653523
tagged with: python
tagged with: append
score: -1
has body: I have a csv file on world countries and their population over years. I am using .insert() method to insert a new column called "change" which I want to include the change (in precentage) in population, for each passing year. I am using for loop, pretty basically: n=0 delta=[] for i in range(0,11210): delta=df.population[n+1]/df.population[n] n+=1 delta.append(i) the output i receive is: AttributeError: 'numpy.float64' object has no attribute 'append' What am I doing wrong?
accepted answer: http://stackoverflow.com/a/49819490
tagged with: pandas
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/49819490
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has title: using for loop to set a new array

http://stackoverflow.com/comment/86823567
type: Comment
type: QuestionComment
has text: You can also use [broadcasting](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html) for your array multiplication `ss*sig`
comment on: http://stackoverflow.com/q/49903741
score: 0

databricks
tag name: databricks
type: Tag
tags question: http://stackoverflow.com/q/49761926

http://stackoverflow.com/a/49832875
answers question: http://stackoverflow.com/q/49831784
upvote count: 4
has body: Let's run some timings. df = pd.DataFrame({'A':np.random.randint(-10,10,1000000),'B':np.random.random(1000000)}) Test for see of both returns are equal df1 = df.groupby('A').filter(lambda x: x.name &gt;= 0) df2 = df[df.A &gt;= 0] all(df1 == df2) True Timings: %timeit df1 = df.groupby('A').filter(lambda x: x.name &gt;= 0) 607 ms ± 10.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit df2 = df[df.A &gt;= 0] 59.7 ms ± 724 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) @jacquot solutions sees to be 10x faster than grouping then filtering.
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/86682084
type: Answer

http://stackoverflow.com/comment/86772474
type: Comment
type: AnswerComment
score: 1
has text: Great answer, just one minor nit: `create_task()` should be used in preference to `ensure_future()` if you know you have a coroutine object - [rationale by Guido](https://github.com/python/asyncio/issues/477#issuecomment-268709555). And in this case neither is needed because `asyncio.gather` (and `asyncio.wait` etc.) will correctly handle being passed coroutine objects, or any other objects that can be converted to `Future`.
comment on: http://stackoverflow.com/a/49874816

http://stackoverflow.com/q/49853114
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has title: Reading from certain rows in python with csv module
tagged with: python
has body: So I have this information from a csv file in python, I am using the csv module. ALPHABETICAL ORDER Positions Classifications Company Booth Full-Time Full-Time Visa Sponsor Part-Time Internship Freshman Sophomore Junior Senior Post-Bacs MS PhD Alumni AIG 10 Yes Jr MS Baylorï¿½Collegeï¿½ofï¿½Medicine 19 Yes Yes Recent CGG 17 Yes Yes MS PhD Recent Citi 27/28 Yes Yes Jr Sr ExxonMobil 11 Yes Yes Fr Soph Jr Sr PB ... Flow-Calï¿½Inc. 16 Yes Yes Jr Sr All Globalï¿½Shopï¿½Solutions 18 Yes Yes Sr PB All Harrisï¿½Countyï¿½CTS 22 Yes Yes Jr Sr PB MS PhD All HCSS 29 Yes Yes Fr Soph Jr Sr PB MS Recent Hitachiï¿½Consulting 13 Yes Sr MS HPï¿½Inc. 1 Yes Yes Jr MS Recent INTï¿½Inc. 20 Yes Yes Yes Jr Sr MS PhD JPMorganï¿½Chaseï¿½&amp;ï¿½Co 3 Yes Yes Jr Sr Leidos 390 Yes Yes Fr Soph Jr Sr PB MS McKesson 26 Yes Sr MREï¿½Consultingï¿½Ltd. 2 Yes Sr PB MS All NetIQ 7 Yes Soph Jr Sr PB PROS 21 Yes Sr MS PhD All Sanï¿½Jacintoï¿½Collegeï¿½ï¿½ 14 Yes Soph Jr Sr PB MS SAS 4 Yes Yes Fr Soph Jr Sr PB MS Recent Smartbridge 8 Yes Sr PB MS Sogetiï¿½USA 15 Yes Sr PB MS Southwestï¿½Researchï¿½Institute 12 Yes Yes Jr Sr PB MS PhD All Theï¿½Reynoldsï¿½andï¿½Reynoldsï¿½Company 23 Yes Yes Yes Fr Soph Jr Sr PB All UHï¿½Enterpriseï¿½Systems 9 Yes Yes Yes Yes Fr Soph Jr Sr PB MS PhD All U.S.ï¿½Marineï¿½Corps 25 Yes Yes Fr Soph Jr Sr PB MS All ValuDï¿½Consutingï¿½LLC 5 Yes Sr PB All Wipro 24 Yes Sr PB BOOTH ORDER Booth Positions Classifications Company # Full-Time "Full-Time Visa Sponsor" Part-Time Internship Freshman Sophomore Junior Senior Post-Bacs MS PhD Alumni HPï¿½Inc. 1 Yes Yes Jr MS Recent MREï¿½Consulting,ï¿½Ltd. 2 Yes Sr PB MS All JPMorganï¿½Chaseï¿½&amp;ï¿½Co 3 Yes Yes Jr Sr SAS 4 Yes Yes Fr Soph Jr Sr PB MS Recent ValuDï¿½Consutingï¿½LLC 5 Yes Sr PB All NetIQ 7 Yes Soph Jr Sr PB Smartbridge 8 Yes Sr PB MS UHï¿½Enterpriseï¿½Systems 9 Yes Yes Yes Yes Fr Soph Jr Sr PB MS PhD All AIG 10 Yes Jr MS ExxonMobil 11 Yes Yes Fr Soph Jr Sr PB Southwestï¿½Researchï¿½Institute 12 Yes Yes Jr Sr PB MS PhD All Hi…
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49854047
type: Question

http://stackoverflow.com/q/49873842
has comment: http://stackoverflow.com/comment/86763307
linked to: http://stackoverflow.com/q/35516059
type: AnsweredQuestion
score: 0
has body: I have a library with the following setup.py: from setuptools import setup from mylib import __version__ requirements = ['paramiko'] tests_require = ['pytest'] def main(): setup( name='mypackage', description='A collection of utilities', url='http://example.net', version=__version__, author='Me Me', author_email='me@me.net', packages=['mylib'], zip_safe=False, install_requires=requirements, tests_require=tests_require, ) if __name__ == '__main__': main() I have released this package to an internal devpi server. Whenever I try to install it, I get: » pip install mypackage Looking in indexes: http://devpi.mine/myuser/dev/+simple/ Collecting mypackage Downloading http://devpi.mine/myuser/dev/+f/a8c/c05e3a49de4fe/mypackage-0.0.2.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 "/tmp/pip-install-ee238ja7/mypackage/setup.py", line 3, in &lt;module&gt; from mypackage import __version__ File "/tmp/pip-install-ee238ja7/mypackage/mylib/__init__.py", line 3, in &lt;module&gt; from .storage_host import StoraHostType File "/tmp/pip-install-ee238ja7/mypackage/mylib/storage_host.py", line 5, in &lt;module&gt; from .ssh import SSH File "/tmp/pip-install-ee238ja7/mypackage/mylib/ssh.py", line 5, in &lt;module&gt; import paramiko ModuleNotFoundError: No module named 'paramiko' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-ee238ja7/mypackage/ Why is pip not installing the requirements listed in install_requires, in setup.py?
tagged with: setuptools
has comment: http://stackoverflow.com/comment/86762982
accepted answer: http://stackoverflow.com/a/49873920
tagged with: devpi
type: Question
has title: Dependencies are not installed by pip
answer count: 1
tagged with: pip
has answer: http://stackoverflow.com/a/49873920
tagged with: python

http://stackoverflow.com/comment/86755438
has text: Thank you very much @WarrenWeckesser. If you add this as an answer, I'll be happy to accept it.
comment on: http://stackoverflow.com/q/49870061
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49858030
tagged with: gtk3
has title: Gtk+3 error: 'GLocalFile' is not defined
type: Question
has body: I am using following way to insert side bar in my file manager: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from gi.repository import Gio def on_open_location(placessidebar, location, flags): # import pdb; # pdb.set_trace() location = placessidebar.get_location() print("Opened URI: %s" % (GLocalFile.get_uri(location))) def create_side_bar(): # side bar placessidebar = Gtk.PlacesSidebar() placessidebar.set_open_flags(Gtk.PlacesOpenFlags.NORMAL) placessidebar.connect("open-location", on_open_location) return placessidebar But whenever I run this code: NameError: name 'GLocalFile' is not defined I tried debugging it and noticed following things: location &lt;__gi__.GLocalFile object at 0x7f3ea42b5cf0 (GLocalFile at 0x1aaae40)&gt; location is a parameter that is of type GLocalFile, so seeing this I also tried __gi__.GLocalFile and as expected it gave: NameError: name '__gi__' is not defined By searching online I saw everyone is using the same code for side bar, so what am I missing here?
tagged with: python
accepted answer: http://stackoverflow.com/a/50196309
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/50196309
tagged with: user-interface
answer count: 1

http://stackoverflow.com/q/49798207
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86620160
duplicate of: http://stackoverflow.com/q/1966073
has comment: http://stackoverflow.com/comment/86611489
score: 0
linked to: http://stackoverflow.com/q/3362600
linked to: http://stackoverflow.com/q/11921188
answer count: 0
tagged with: email
has body: This code puts files in email body-it works fine.How can i modify this code to attach multiple attachments ? I'm not familiar with python #!/usr/bin/python3 import smtplib from email.mime.text import MIMEText def read_files(file_list): data = '' for filename in file_list: with open(filename) as file: data += file.read() return data def send_mail(header, body): msg = MIMEText(body, 'html') # second parameter is MIME type msg['Subject'] = header['Subject'] msg['From'] = header['From'] msg['To'] = header['To'] s = smtplib.SMTP('localhost') s.send_message(msg) s.quit() def main(): file_list = ['1.html', '2.html'] data = read_files(file_list) header = {'To': 'user@company.com', 'Subject': ' AWS Reports' , 'From': 'user@company.com'} send_mail(header, data) main() in def send_mail i added part = MIMEBase('application', "octet-stream") part.set_payload(open("output.json", "rb").read()) Encoders.encode_base64(part) msg.attach(part) but got: 'Cannot attach additional subparts to non-multipart/*') email.errors.MultipartConversionError: Cannot attach additional subparts to non-multipart/* I found this solution but message is encoded:https://www.tutorialspoint.com/python3/python_sending_email.htm
has title: Sending email:Attach file-Python
type: Question
linked to: http://stackoverflow.com/q/1966073

http://stackoverflow.com/comment/86738494
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49861233
has text: There is the edit with the route.
score: 0

http://stackoverflow.com/a/49881685
answers question: http://stackoverflow.com/q/49881024
has comment: http://stackoverflow.com/comment/87488527
has comment: http://stackoverflow.com/comment/86815783
has comment: http://stackoverflow.com/comment/86784853
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86783748
has body: Chances are, this was a temporary issue with the cert. I just loaded it (using a 3.6.5 virtual environment with pip 10.0.0) and had no issues. I also loaded https://pypi.python.org/simple/scikit-learn/ into Opera and the cert is definitely valid now. I would also suggest using a virtualenv (https://virtualenv.pypa.io/en/stable/). It avoids some frustrating issues like pip pointing to the 2.7 version instead of pip3.

http://stackoverflow.com/q/49887524
has answer: http://stackoverflow.com/a/49887692
score: 7
has comment: http://stackoverflow.com/comment/86791131
has comment: http://stackoverflow.com/comment/86791083
has comment: http://stackoverflow.com/comment/86791485
downvote count: 1
duplicate of: http://stackoverflow.com/q/33541947
favorite count: 0
tagged with: python-3.x
has body: I'm using python 3.6. I came across the below way to flatten the nested list using sum: a = [[1, 2], [3, 4], [5, 6]] sum(a,[]) which returns: [1,2,3,4,5,6] What exactly is going on here? Sum takes an iterable, in this case a list, and a start value. I don't understand what python reads to flatten the list.
answer count: 4
accepted answer: http://stackoverflow.com/a/49887567
upvote count: 8
type: Question
has answer: http://stackoverflow.com/a/49887582
possible better answer: http://stackoverflow.com/a/49887692
has answer: http://stackoverflow.com/a/49887567
tagged with: python
has answer: http://stackoverflow.com/a/49887577
has comment: http://stackoverflow.com/comment/86791197
has title: How flattening a nested list using `sum(iterable,[])` works?
linked to: http://stackoverflow.com/q/952914
has comment: http://stackoverflow.com/comment/86791169
tagged with: list
linked to: http://stackoverflow.com/q/33541947
has comment: http://stackoverflow.com/comment/86792097
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86791123

http://stackoverflow.com/q/49807976
has body: I have a Pandas dataframe object. I want to create new columns from substrings of an existing column. My data looks like this: Date variable want1 want2 want3 0 02-01-08 Australia - Sydney - A Australia Sydney A 1 03-01-08 Australia - Sydney - A Australia Sydney A 2 04-01-08 Australia - Sydney - A Australia Sydney A 3 05-01-08 Canada - Toronto - B Canada Toronto B 4 06-01-08 Canada - Toronto - B Canada Toronto B where want1 to want3 are what I need.
has answer: http://stackoverflow.com/a/49807992
score: 2
type: AnsweredQuestion
answer count: 2
has title: Create column from a substring of another column
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49808056
downvote count: 0
accepted answer: http://stackoverflow.com/a/49807992
tagged with: string
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/49808056
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/86582063
type: Comment
comment on: http://stackoverflow.com/a/49783218
score: 0
has text: @SwagZ then .....The name is different right ? name + otherstuff1 + otherstuff2 will be unique combination , Luke 1.08 1.08. no equal to Zack 1.08 1.08, so it will not belong to one group ...I will recommend check the official document for groupby .
type: AnswerComment

http://stackoverflow.com/q/49760531
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86536212
has comment: http://stackoverflow.com/comment/86536465
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49760810
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86536183
tagged with: pandas
tagged with: dataframe
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86536358
has body: import pandas as pd A=pd.read_csv("C:/Users/amulya/Desktop/graves lab/Mani/HIDDEN WORDS/Hidden_word_4.csv") df1=pd.DataFrame(A) B=pd.read_csv("C:/Users/amulya/Desktop/graves lab/words.csv") df2=pd.DataFrame(B) C=df1[df1.col1.isin(df2.col1)]`` df3=pd.DataFrame(C) df3.to_csv("C:/Users/amulya/Desktop/graves lab/Mani/HIDDEN WORDS/out4.csv", encoding='utf-8', index=False) insteaad of naming the file each time, i want to iterate 20 files
has title: how to iterate 20 .csv files and do some computation[the computation part,shown in code] on each and create sepaerate .scv output files in python?

http://stackoverflow.com/comment/86578077
comment on: http://stackoverflow.com/q/49781303
has text: Have you installed the module?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49804605
has comment: http://stackoverflow.com/comment/86627931
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/86624565
has body: Here is use of exec to do as asked in comments: n=1 for item in Weapons: exec('x'+str(n)+'= Radiobutton(equipped, text=item['name'], variable=player['weapon'], value=item)' exec('x'+str(n)+'.pack()' n+=1
downvote count: 1
upvote count: 3
answers question: http://stackoverflow.com/q/49804510

http://stackoverflow.com/comment/86698365
comment on: http://stackoverflow.com/q/49841674
has text: @jpp Added some minimal data examples and desired output
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/86725615
type: QuestionComment
comment on: http://stackoverflow.com/q/49843335
has text: Whats the type of data in Score column. please post some samples.
type: Comment
score: 0

http://stackoverflow.com/q/49798372
has body: i am reading some data from splunk and i want to convert that format to pandas dataframe. Splunk blog question result = results.ResultsReader(service.jobs.export(SEARCH_COMMAND)) for rr in result: print(rr) OrderedDict([('H', '123'), ('U', 'aaa@global-bilgi.entp'), ('S', 'motv:SMP_SESSION_ID/1523537360524/-86840158')]) OrderedDict([('H', '456'), ('U', 'sss@global-bilgi.entp'), ('S', 'motv:SMP_SESSION_ID/1523537367876/-765151654')]) OrderedDict([('H', '145'), ('U', 'ddd@global-bilgi.entp'), ('S', 'motv:SMP_SESSION_ID/1523537367571/540003017')]) OrderedDict([('H', '111'), ('U', 'asd@global-bilgi.entp'), ('S', 'motv:SMP_SESSION_ID/1523537376045/540216322')]) OrderedDict([('H', '222'), ('U', 'asd@global-bilgi.entp'), ('S', 'motv:SMP_SESSION_ID/1523537383484/-86104258')])
favorite count: 0
type: Question
score: 1
duplicate of: http://stackoverflow.com/q/44365209
has title: Python 2.7 special splunk object to dataframe conversion
tagged with: dataframe
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49798782
type: AnsweredQuestion
tagged with: python-2.7
tagged with: pandas
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49798782

http://stackoverflow.com/a/49836698
type: Answer
has body: You format your output accordingly: n = 2.83415e+07 print(f'{n:f}') print(f'{n:e}') Output: 28341500.000000 2.834150e+07 See string format mini language Pandas works the same: import pandas as pd df = pd.DataFrame ( [{"tata": 2.325568e9}]) # print with default float settings print (df) pd.options.display.float_format = '{:,.4f}'.format # set other global format # print with changed float settings print(df) # really convert the type: df["tata"] = df["tata"].astype(int) # print with default int settings print(df) Credit to: unutbu's answer here Output: tata 0 2.325568e+09 # before format change tata 0 2.325.568.000,0000 # after format change tata # after int conversion 0 -2147483648 There are other ways to do formatting - see How to display pandas DataFrame of floats using a format string for columns?
downvote count: 0
has comment: http://stackoverflow.com/comment/132695487
answers question: http://stackoverflow.com/q/49836620
score: 5
upvote count: 5

http://stackoverflow.com/comment/86590366
type: Comment
comment on: http://stackoverflow.com/a/49786765
score: 0
type: AnswerComment
has text: It's working quite well, @joefromct. After installing tabulate, the print command returned the output that is needed. Rather than printing the output, is there any way to assign the printed data to a type (with rows and columns) that can be exported to a CSV file?

http://stackoverflow.com/comment/86737139
comment on: http://stackoverflow.com/q/49860987
score: 2
type: QuestionComment
has text: `df = pd.get_dummies(df['A'])` should working perfectly.
type: Comment

http://stackoverflow.com/comment/86751993
type: AnswerComment
has text: The latency is fine for my purposes. But when I try to get input from two mics now one works and the other doesn't.
type: Comment
comment on: http://stackoverflow.com/a/49867837
score: 0

http://stackoverflow.com/a/49846950
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49846860
answers question: http://stackoverflow.com/q/49846860
type: Answer
has body: You could move get_unique_slug into the model's clean method. That way the slug will be validated before the instance is saved. def clean(): if not self.slug: self.slug = self.get_unique_slug() if self.slug == '': raise forms.ValidationError("Invalid slug")
downvote count: 0

http://stackoverflow.com/q/49841324
has answer: http://stackoverflow.com/a/73826515
type: Question
has body: After I instantiate a scikit model (e.g. LinearRegression), if I call its fit() method multiple times (with different X and y data), what happens? Does it fit the model on the data like if I just re-instantiated the model (i.e. from scratch), or does it keep into accounts data already fitted from the previous call to fit()? Trying with LinearRegression (also looking at its source code) it seems to me that every time I call fit(), it fits from scratch, ignoring the result of any previous call to the same method. I wonder if this true in general, and I can rely on this behavior for all models/pipelines of scikit learn.
upvote count: 83
score: 83
tagged with: python
possible better answer: http://stackoverflow.com/a/49841568
has answer: http://stackoverflow.com/a/49841366
has answer: http://stackoverflow.com/a/49841568
type: AnsweredQuestion
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/49841366
tagged with: machine-learning
tagged with: scikit-learn
favorite count: 0
has title: What does calling fit() multiple times on the same model do?

http://stackoverflow.com/comment/86764455
comment on: http://stackoverflow.com/q/49874492
has text: Do you have enough ram?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49809512
tagged with: regex
score: 1
has comment: http://stackoverflow.com/comment/86633718
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86634176
has answer: http://stackoverflow.com/a/49810145
answer count: 2
upvote count: 3
type: UnansweredQuestion
downvote count: 2
linked to: http://stackoverflow.com/q/1322464
has comment: http://stackoverflow.com/comment/86636162
has answer: http://stackoverflow.com/a/49809552
tagged with: python
has title: Check format of string in python
has body: How do I check if a string coming into a function has the correct format? The correct format is "8:30:00" or "16:00:00" Something like: string_format = "%h%m%s" if input_data == string_format: do this else: error

http://stackoverflow.com/comment/86753335
comment on: http://stackoverflow.com/a/49868948
type: AnswerComment
has text: Cool, I've try to do that but failed. Nice to see it done !
score: 0
type: Comment

google-calendar-api
tags question: http://stackoverflow.com/q/49887198
tags question: http://stackoverflow.com/q/49889379
type: Tag
tag name: google-calendar-api

http://stackoverflow.com/comment/86832683
has text: @AlexHall we have random number, some of them lead to negative value under sqrt, How should I tell python to pass them.
comment on: http://stackoverflow.com/q/49908354
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49776586
answer count: 1
has comment: http://stackoverflow.com/comment/86569642
accepted answer: http://stackoverflow.com/a/49778992
has answer: http://stackoverflow.com/a/49778992
type: Question
has comment: http://stackoverflow.com/comment/86572882
has comment: http://stackoverflow.com/comment/86569888
has comment: http://stackoverflow.com/comment/86569572
has comment: http://stackoverflow.com/comment/86569897
has comment: http://stackoverflow.com/comment/86569787
has comment: http://stackoverflow.com/comment/86569193
has comment: http://stackoverflow.com/comment/86573328
tagged with: python
has body: I am severely confused by this error. I have made migrations as I have seen that has been a running solution with a lot of other problems similar to mine. Here is the error. Traceback (most recent call last): File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: polls_band The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ethan\Envs\OnNote\mysite\polls\views.py", line 117, in bandlist print(query) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\models\query.py", line 226, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\models\query.py", line 250, in __iter__ self._fetch_all() File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\models\query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\models\query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\db\models\sql\compiler.py", line 900, in execute_sql raise original_exception File "C:\Users\Ethan\Envs\OnNote\…
has title: OperationalError at /bandlist/, no such table: polls_band
has comment: http://stackoverflow.com/comment/86570377
type: AnsweredQuestion
score: 0
tagged with: django

http://stackoverflow.com/comment/86682057
comment on: http://stackoverflow.com/a/49828084
score: 0
type: AnswerComment
has text: @ÉvaristeGalois L1 is not part of Ridge regression. You do need to determine L2, but it has a default value. I suggest you check out [`ElasticNetCV`](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.ElasticNetCV.html). Based on your comment, it might be what you're after.
type: Comment

http://stackoverflow.com/comment/86571787
type: QuestionComment
comment on: http://stackoverflow.com/q/49777249
score: 0
has text: So what you need to do is: for each start point, get a set of the end points. And then when you produce a path, you check if its end point is in that set, if so it is reported.
type: Comment

http://stackoverflow.com/a/49888600
type: Answer
has comment: http://stackoverflow.com/comment/87144355
has comment: http://stackoverflow.com/comment/87032575
answers question: http://stackoverflow.com/q/49799109
has comment: http://stackoverflow.com/comment/87061795
score: 8
has comment: http://stackoverflow.com/comment/87144393
type: AcceptedAnswer
has body: [ActiveState.Docs]: win32file.ReadDirectoryChangesW (this is the best documentation that I could find for [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions) is a wrapper over [MS.Docs]: ReadDirectoryChangesW function. Here's what it states (about the buffer): 1. General When you first call ReadDirectoryChangesW, the system allocates a buffer to store change information. This buffer is associated with the directory handle until it is closed and its size does not change during its lifetime. Directory changes that occur between calls to this function are added to the buffer and then returned with the next call. If the buffer overflows, the entire contents of the buffer are discarded, the lpBytesReturned parameter contains zero, and the ReadDirectoryChangesW function fails with the error code ERROR_NOTIFY_ENUM_DIR. My understanding is that this is a different buffer than the one passed as an argument (lpBuffer): The former is passed to every call of ReadDirectoryChangesW (could be different buffers (with different sizes) passed for each call) The latter is allocated by the system, when the former clearly is allocated (by the user) before the function call and that is the one that stores data (probably in some raw format) between function calls, and when the function is called, the buffer contents is copied (and formatted) to lpBuffer (if not overflew (and discarded) in the meantime) 2. Synchronous Upon successful synchronous completion, the lpBuffer parameter is a formatted buffer and the number of bytes written to the buffer is available in lpBytesReturned. If the number of bytes transferred is zero, the buffer was either too large for the system to allocate or too small to provide detailed information on all the changes that occurred in the directory or subtree. In this case, you should compute the changes by enumerating the directory or subtree. This somewhat confirms my previous assumption "the buffer was either too large for the system to allocat…
has comment: http://stackoverflow.com/comment/87062269
downvote count: 0
has comment: http://stackoverflow.com/comment/87074777
has comment: http://stackoverflow.com/comment/87061383
has comment: http://stackoverflow.com/comment/87144182
upvote count: 8
has comment: http://stackoverflow.com/comment/130779348
accepted answer of: http://stackoverflow.com/q/49799109

http://stackoverflow.com/q/49758988
has body: The below python script executes a command. The command returns an output. Output is listed below. I need to parse the following from the output. 1) HTTP response code 2) Contents of points array. Array could be empty, or non empty array (last line of the output) OUTPUT : Matched line for host akaa-wcb54zu2flskjhx4-szsapxzmalbot2fr.luna-dev.akamaiapis.net {'access_token': 'akaa-r6gnip3mmql3evrj-mgiex4eajadrjltu', 'max-body': 131072, 'secret': 'yBc1LSGKBd6+sSP5tTR2o+YxlNYvlYNjWGdCFDl6Xt0=', 'signed-header': [], 'host': 'akaa-wcb54zu2flskjhx4-szsapxzmalbot2fr.luna-dev.akamaiapis.net', 'client_token': 'akaa-eyaa6fvcfngdlrb6-uxvn3hkpzxx33oxc'} [] Canonicalized header: Auth data: EG1-HMAC-SHA256 client_token=akaa-eyaa6fvcfngdlrb6-uxvn3hkpzxx33oxc;access_token=akaa-r6gnip3mmql3evrj-mgiex4eajadrjltu;timestamp=20180410T16:38:24+0000;nonce=265e61d8-813c-4c3a-9edb-91caaa027420; String-to-sign: POST https akaa-wcb54zu2flskjhx4-szsapxzmalbot2fr.luna-dev.akamaiapis.net /prolexic-analytics/v2/metrics YSycIdG2e9nY8KVLrPvMfzrBNMZEI8ncRxtcUP4h1J0= EG1-HMAC-SHA256 client_token=akaa-eyaa6fvcfngdlrb6-uxvn3hkpzxx33oxc;access_token=akaa-r6gnip3mmql3evrj-mgiex4eajadrjltu;timestamp=20180410T16:38:24+0000;nonce=265e61d8-813c-4c3a-9edb-91caaa027420; args = ['curl', '-H', 'Authorization: EG1-HMAC-SHA256 client_token=akaa-eyaa6fvcfngdlrb6-uxvn3hkpzxx33oxc;access_token=akaa-r6gnip3mmql3evrj-mgiex4eajadrjltu;timestamp=20180410T16:38:24+0000;nonce=265e61d8-813c-4c3a-9edb-91caaa027420;signature=p6y+oDzaTfh3nj32R8jveDx8EGmjpHGybL7LJ0L+Adk=', '-S', '-i', '-k', '-X', 'POST', '-H', 'Host:akaa-wcb54zu2flskjhx4-szsapxzmalbot2fr.luna-dev.akamaiapis.net', '-H', 'Content-Type: application/json', '-H', 'Accept: application/json', '-d', '{"contract": "amade", "start": 1522420500, "end": 1522424147, "samples": 20, "type": {"connect": ["bandwidthIn"]}}', 'https://akaa-wcb54zu2flskjhx4-szsapxzmalbot2fr.luna-dev.akamaiapis.net/prolexic-analytics/v2/metrics', '-H', 'Expect:'] HTTP/1.1 200 OK Server: Apache-Coyote…
has comment: http://stackoverflow.com/comment/86533557
has answer: http://stackoverflow.com/a/49759328
has comment: http://stackoverflow.com/comment/86533778
type: Question
downvote count: 3
tagged with: python
tagged with: regex
score: -3
favorite count: 0
linked to: http://stackoverflow.com/q/6657690
upvote count: 0
has comment: http://stackoverflow.com/comment/86533550
has answer: http://stackoverflow.com/a/49759348
answer count: 2
has title: python regex to parse the output of a command
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/49570132

http://stackoverflow.com/comment/86647466
has text: ^^ thats not a valid dictionary either
type: QuestionComment
comment on: http://stackoverflow.com/q/49816258
score: 1
type: Comment

http://stackoverflow.com/comment/86534422
comment on: http://stackoverflow.com/q/49758382
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [Change data type of columns in Pandas](https://stackoverflow.com/questions/15891038/change-data-type-of-columns-in-pandas)

http://stackoverflow.com/q/49862368
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49864220
tagged with: pyspark
tagged with: python
has title: How to merge files contains in different folders using pyspark
tagged with: rdd
has body: Got different files in different folders. need to merge them using pyspark. merging can happen using below code but needs to read the files present in different folders sc.textFile(&lt;path&gt;).coalesce(1).saveAsTextFile(&lt;path&gt;) example /user/home/m_f012345/part0000, part0001, part0002 /user/home/m_f00120/part0000, part0001, part0002 /user/home/m_f123120/part0000, part0001, part0002 after merging files present in each folder /user/home/m_f012345/part0000 /user/home/m_f00120/part0000 /user/home/m_f123120/part0000 Note: i might be having folders more than 50 and we are not using any format for folders. these are random folders
type: AnsweredQuestion
score: 0
tagged with: apache-spark
upvote count: 1
accepted answer: http://stackoverflow.com/a/49864220
downvote count: 1
answer count: 1

http://stackoverflow.com/a/49881592
answers question: http://stackoverflow.com/q/49881446
has comment: http://stackoverflow.com/comment/86779467
accepted answer of: http://stackoverflow.com/q/49881446
type: Answer
has body: When you type my_var in your code, Python needs to know what that represents. First it checks in locals and if it doesn't find a reference it checks in globals. Now Python can evaluate your code when you write 'string' == my_var. Similarly, when you write the name of a function in your code, Python needs to know what that represents. Since the output of a function can change based on the input, Python can't store a simple value like a string to represent a function in globals. Instead it stores the memory reference so that when you type my_func(), it can go to that memory store and use the function to compute the output.
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86692630
comment on: http://stackoverflow.com/a/49838589
has text: Yes. I just created an empty folder in C:\ and set it as the location, " Error: Standard Python 'venv' module not found" is still popping up.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86815020
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49898084
has text: @E.Mohammed You really need to show your troubleshooting steps *after* incorporating that information.

http://stackoverflow.com/comment/86777114
comment on: http://stackoverflow.com/q/49880575
has text: All the nested list must have the same length. Otherwise numpy can't infer the shape. Try it yourself: what would be the shape of your matrix?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/49851934
has comment: http://stackoverflow.com/comment/86723908
has comment: http://stackoverflow.com/comment/86723216
has comment: http://stackoverflow.com/comment/86718923
has title: elasticsearch.exceptions.TransportError: TransportError 503: Data too large
has comment: http://stackoverflow.com/comment/86718601
has comment: http://stackoverflow.com/comment/86722905
has comment: http://stackoverflow.com/comment/86723461
tagged with: elasticsearch
has comment: http://stackoverflow.com/comment/86718509
has body: I'm trying to get the response from ES hitting it from python code but it is showing the below error: elasticsearch.exceptions.TransportError: TransportError(503, u'search_phase_execution_exception', u'[request] Data too large, data for [&lt;agg [POSCodeModifier]&gt;] would be [623327280/594.4mb], which is larger than the limit of [623326003/594.4mb]') If i hit the same code from kibana i get the results but using python i'm getting this error. I'm using aggregation in my code. if someone can explain if i need to set some properties or how to optimise it?? Below is the structure for request i'm sending and if i set start and end date greater than 5 days it gives me the error, otherwise i'm getting the results unmtchd_ESdata= es.search(index='cstore_new',body={'size' : 0, "aggs": { "filtered": { "filter": { "bool": { "must_not": [ { "match": { "CSPAccountNo": store_id } } ], "must": [ { "range": { "ReportDate": { "gte": start_dt, "lte": end_dt } } } ] } } , "aggs": { "POSCode": { "terms": { "field": "POSCode", "size": 10000 }, "aggs": { "POSCodeModifier": { "terms": { "field": "POSCodeModifier", "size": 10000 }, "aggs": { "CSP": { "terms": { "field": "CSPAccountNo", "size": 10000 }, "aggs": { "per_stock": { "date_histogram": { "field": "ReportDate", "interval": "week", "format": "yyyy-MM-dd", "min_doc_count": 0, "extended_bounds": { "min": start_dt, "max": end_dt } }, "aggs": { "avg_week_qty_sales": { "sum": { "field": "TotalCount" } } } }, "market_week_metrics": { "extended_stats_bucket": { "buckets_path": "per_stock&gt;avg_week_qty_sales" } } } } } } } } } } }},request_timeout=1000) Edit1: Result variables needed from elastic search response for i in range(len(unmtchd_ESdata['aggregations']['filtered']['POSCode']['buckets'])): list6.append(unmtchd_ESdata['aggregations']['filtered']['POSCode']['buckets'][i]['POSCodeModifier']['buckets'][0]['CSP']['buckets'][0]['market_week_metrics']['avg']) list7.append(unmtchd_ESdata['aggregations']['filtered']['POSCode']['buckets'…
has comment: http://stackoverflow.com/comment/86721499
type: Question
has comment: http://stackoverflow.com/comment/86721766
answer count: 0
has comment: http://stackoverflow.com/comment/86722935
has comment: http://stackoverflow.com/comment/86721742
score: 0
has comment: http://stackoverflow.com/comment/86722144
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86721422
tagged with: python

http://stackoverflow.com/a/50011532
type: Answer
score: 0
has body: Thanks to both of you guys. I used a combination of both to obtain what I needed. from datetime import timedelta from django.utils import timezone from django.db.models import Avg, Max from temp.models import * import temp.views import django def update_avg(self, start, end): entries_for_period = Entry.objects.filter(time__gte=start, time__lte=end) avg_values = ['inside', 'outside', 'gavg'] average_value = entries_for_period.aggregate(*[Avg(x) for x in avg_values]) return {x:average_value['%s__avg' % x] for x in avg_values} def update_high(self, start, end): entries_for_period2 = Entry.objects.filter(time__gte=start, time__lte=end) high_values = ['inside', 'outside', 'ghigh'] high_value = entries_for_period2.aggregate(*[Max(x) for x in high_values]) return {x:high_value['%s__max' % x] for x in high_values} current_day = timezone.now() previous_day = current_day - timedelta(hours=24) date_entry = previous_day.date() avg_choice = update_avg(date_entry,previous_day,current_day) high_choice = update_high(date_entry,previous_day,current_day) history = History(date=date_entry, avginside=round(avg_choice['inside'],2),highinside=round(high_choice['inside'],2),avgoutside=round(avg_choice['outside'],2),highoutside=high_choice['outside'],avgg=avg_choice['gavg'],highg=high_choice['ghigh'],starttime=previous_day,endtime=current_day) history.save() Now I can get a daily snapshot of the average and high values of my model's input. Thanks!
answers question: http://stackoverflow.com/q/49768588

http://stackoverflow.com/comment/86780515
type: Comment
type: QuestionComment
score: 0
has text: You can use the `actual` method of a font object to see what the actual font is, and you can use the `families` method of the tkinter font class to get a list of available font families.
comment on: http://stackoverflow.com/q/49874973

http://stackoverflow.com/a/49765347
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49765310
has body: Replace your final line with super(ChildSerializer, self).cleanse() You don't need self, super call refers to your parent class and acts as it.
score: 1

http://stackoverflow.com/comment/87130557
has text: Yes, there are no spaces between those words in your string, however this is insignificant. The top answer on that question removes spaces and punctuation from the string to give only the words, no matter how many of each there is in-between. Using the answer from that question on your string, `re.findall(r"[\w']+", original)` gives `['This', 'is', 'my', 'resting', 'place']`.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49892743

http://stackoverflow.com/comment/86674876
type: QuestionComment
has text: i tried formatting but i want to get the value stored in variable s to be printed in summary in payload but it is taking only s as character
score: 0
comment on: http://stackoverflow.com/q/49829322
type: Comment

http://stackoverflow.com/q/49891625
has comment: http://stackoverflow.com/comment/86828716
linked to: http://stackoverflow.com/q/49748063
favorite count: 0
has comment: http://stackoverflow.com/comment/86813354
has comment: http://stackoverflow.com/comment/86829062
type: Question
has comment: http://stackoverflow.com/comment/86799369
has answer: http://stackoverflow.com/a/49908062
has body: I've installed python 2.7.14 on my 1and1 shared hosting server using the following tutorial: http://geeksta.net/geeklog/python-shared-hosting/ it works and has a bunch of the modules that I use. However, i'd like to have numpy and pandas on this installation as well. I'm having all sorts of issues, but the most basic one is when typing: pip install numpy which leads to the following error: Could not fetch URL https://pypi.python.org/simple/numpy/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping Could not find a version that satisfies the requirement numpy (from versions: ) No matching distribution found for numpy So it looks like maybe it's failing because I don't have SSL installed, but all the suggestions for installing SSL seems to require sudo (which I can't access root on a shared host). A second question is that I'm wondering about is if I need to use a virtualenv or not. I'm new to this but it seems like it will allow me to install things, but again I tried to install virtualenv (as stated in the tutorial): pip install virtualenvwrapper but I get the same sort of SSL error: Could not fetch URL https://pypi.python.org/simple/virtualenvwrapper/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping Could not find a version that satisfies the requirement virtualenvwrapper (from versions: ) No matching distribution found for virtualenvwrapper any help that can direct me in the right direction to get these modules installed would be greatly appreciated. Thanks. Updated to ask additional approach Given the issue seems to be not being able to download a python package on a https site (b/c SSL isn't available), is it possible for me to download the package manually using my webbrowser then FTPing the file into my server filesystem and then using SSH commands to install the modules? If so, any tips would be muc…
tagged with: ssl
tagged with: python
accepted answer: http://stackoverflow.com/a/49908062
type: AnsweredQuestion
tagged with: shared-hosting
tagged with: installation
has comment: http://stackoverflow.com/comment/86835357
has title: install numpy and pandas on 1and1 shared hosting python
score: 1
answer count: 1
downvote count: 0
tagged with: pip
upvote count: 1

http://stackoverflow.com/q/49800438
has answer: http://stackoverflow.com/a/49819114
type: AnsweredQuestion
answer count: 2
tagged with: lxml
score: 1
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
upvote count: 1
favorite count: 0
has body: print(type(players[1])) for player in players: player = str(player) print(type(players[1])) the output is: &lt;class 'lxml.etree._ElementUnicodeResult'&gt; &lt;class 'lxml.etree._ElementUnicodeResult'&gt; I need to convert this ElementUnicode object into a string so that I can call substring on it, but this for loop isn't doing it. And when I cast it to a string and call substring at the same time, the console reads: str object has no object substring, which makes no sense. str(players[i]).substring() Any thoughts on why that may be the case and how I could get around to calling substring on this object?
type: Question
tagged with: xpath
has title: Why can't I cast an lxml.etree._ElementUnicodeResult to a string?
accepted answer: http://stackoverflow.com/a/57465761
has answer: http://stackoverflow.com/a/57465761
possible better answer: http://stackoverflow.com/a/49819114
tagged with: python

http://stackoverflow.com/q/49771406
type: Question
has body: self.filename = d.get('filename', '/var/www/html/data/reading.txt') syslog.syslog(syslog.LOG_INFO, "pond: using %s" % self.filename) self.bind(weewx.NEW_ARCHIVE_RECORD, self.read_file) def read_file(self, event): try: with open(self.filename) as f: #value = f.read() f.seek(-8, os.SEEK_END) line = f.readlines()[-1] value = line.split(',') syslog.syslog(syslog.LOG_DEBUG, "pond: found value of %s" % value) event.record['ccwatt'] = float(value[0]) event.record['cctemp'] = float(value[1]) except Exception, e: syslog.syslog(syslog.LOG_ERR, "pond: cannot read value: %s" % e) The above python will read the last line in txt file and add a new archive record for example: 123,54 How do I alter it to add an archive record when there is only one value available to record. Obviously the split(',') will not work on one value 123
type: UnansweredQuestion
tagged with: python
score: 0
tagged with: linux
has answer: http://stackoverflow.com/a/49771407
answer count: 1
has title: parsing line python

http://stackoverflow.com/comment/86621518
comment on: http://stackoverflow.com/q/49803462
score: 1
type: Comment
type: QuestionComment
has text: No, something mutable.

http://stackoverflow.com/comment/86756190
score: 0
type: AnswerComment
has text: One more thing. In main function you dont need to call server.initiate_connection inside a while loop. You just need to call it once. That might solve your error.
type: Comment
comment on: http://stackoverflow.com/a/49855687

http://stackoverflow.com/comment/116492334
has text: For what it's worth, the reason you were seeing ERROR tags in GCP may be that any output sent to stderr that the fluent logger doesn't understand, such as the text formatted echoes of your formatted messages, gets tagged as ERROR.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/57612814

http://stackoverflow.com/comment/86759676
type: Comment
comment on: http://stackoverflow.com/a/49870601
type: AnswerComment
has text: I found that df.boxplot(column='Sleep Amount (min)', by='#') is working for my data but violinplot instead of boxplot does now work. do you have any idea of it? And how can I implant seaborn style in here? thanks!
score: 0

http://stackoverflow.com/comment/86554527
comment on: http://stackoverflow.com/a/49767831
has text: case 3 and case 4 can not be searched by re.findall(re.sub(r' ', r'[\$\@ ]+', 'key words', flags=re.IGNORECASE), row1, re.DOTALL), how to do to consider case 3 and case 4 too?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49906307
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49906205
downvote count: 0
has body: To add to a dict named stdrecs, you would store a new key/value pair, i.e stdrecs[name] = courses. This would look like: stdrecs = {} while True: name = input('Student Name: ') courses = [] while True: course = input('Course Name: ') courses.append(course) print('You have entered', len(courses), 'course(s)') ch_course = input('Would you like to add a new course [Y]or[N]: ') if ch_course.upper() == 'Y': continue else: stdrecs[name] = courses break ch_name = input('Would you like to add a new record [Y]or[N]: ') if ch_name.upper() == 'N': print(stdrecs) break
type: Answer
accepted answer of: http://stackoverflow.com/q/49906205
upvote count: 2

http://stackoverflow.com/comment/86574349
has text: The value error is from unpacking an epoch time stamp. It says the year is out of range.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49778805
type: QuestionComment

http://stackoverflow.com/a/74778920
answers question: http://stackoverflow.com/q/49770344
has body: The default behaviour of the Decimal field is string in REST_FRAMEWORK to override for the whole app we can use REST_FRAMEWORK = { 'COERCE_DECIMAL_TO_STRING': False, # Your other settings ... } but if You want to override it for one field You can do as following field = serializers.DecimalField(coerce_to_string=False) by default coerce_to_string is True. checkout this out
type: Answer
downvote count: 0
score: 10
upvote count: 10

http://stackoverflow.com/q/49806893
tagged with: raspberry-pi2
tagged with: python
has body: I am trying to run the bradtraversy simple todo list django code on my raspberry pi and have run into the following error. I have run into the following traceback: Environment: Request Method: GET Request URL: HIDDEN Django Version: 1.11.11 Python Version: 2.7.13 Installed Applications: ['todos.apps.TodosConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/utils/deprecation.py" in __call__ 138. response = self.process_request(request) File "/usr/local/lib/python2.7/dist-packages/django/middleware/common.py" in process_request 57. host = request.get_host() File "/usr/local/lib/python2.7/dist-packages/django/http/request.py" in get_host 105. if domain and validate_host(domain, allowed_hosts): File "/usr/local/lib/python2.7/dist-packages/django/http/request.py" in validate_host 579. if pattern == '*' or is_same_domain(host, pattern): File "/usr/local/lib/python2.7/dist-packages/django/utils/http.py" in is_same_domain 291. pattern = pattern.lower() Exception Type: AttributeError at / Exception Value: 'list' object has no attribute 'lower' I am fairly new to Django but thought I made all the correct adjustments to match my system specifics. I updated the settings file to match my allowed hosts and database setting and used the "python manage.py migrate" command to bring over migrations.…
has comment: http://stackoverflow.com/comment/86633279
type: Question
has title: Simple todolist Bradtraversy lower limit error
answer count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/86681881
tagged with: raspbian
score: 0
tagged with: linux

http://stackoverflow.com/comment/86627729
type: Comment
type: QuestionComment
has text: Those `b` are python's way of displaying a `bytes` array and are not part of the data.
comment on: http://stackoverflow.com/q/49806439
score: 1

http://stackoverflow.com/a/49911729
has comment: http://stackoverflow.com/comment/87041088
has comment: http://stackoverflow.com/comment/86873435
score: 0
has comment: http://stackoverflow.com/comment/86998013
answers question: http://stackoverflow.com/q/49889421
has comment: http://stackoverflow.com/comment/86874604
has comment: http://stackoverflow.com/comment/86875187
has comment: http://stackoverflow.com/comment/86846409
type: Answer
has body: This is more of a comment that did not fit into the comment limit. As I said before, I can't see anything obviously wrong. You might have to do some debugging. If the pre-softmax outputs are exactly the same, it is probably a bug somewhere and you can find it by finding the exact place where your presumably different inputs lead to the same layer outputs. If pre-softmax outputs are close, but not exactly the same, most likely you have a classic issue of over-fitting. You mentioned that you have just 300 training examples - that is extremely few to train the whole net on (without using some pre-trained weights). Your net just "memorized" 300 training examples and does not generalize to validation set at all. EDIT 04/23/18: So, the issue is not just in validation? I interpreted your "if i do the same for trainning set I get a conventional prediction." to mean that training images are classified just fine. If you get the same prediction for your training images, most likely the data or loss or prediction calculation is wrong. I did not spot anything and guess you will need to debug. You might find "eager execution" useful for this - https://www.tensorflow.org/get_started/eager. If you organize your model as in examples (https://github.com/tensorflow/tensorflow/tree/3f4662e7ca8724f760db4a5ea6e241c99e66e588/tensorflow/contrib/eager/python/examples), you should be able to use the same code with regular tensorflow graph execution.
has comment: http://stackoverflow.com/comment/87041165
has comment: http://stackoverflow.com/comment/87041789
has comment: http://stackoverflow.com/comment/87042516
has comment: http://stackoverflow.com/comment/86937701

http://stackoverflow.com/comment/86837924
type: QuestionComment
has text: @rainydayss it's in a string!
comment on: http://stackoverflow.com/q/49910979
score: 2
type: Comment

http://stackoverflow.com/q/49760402
has answer: http://stackoverflow.com/a/49760485
downvote count: 0
favorite count: 0
type: Question
has title: Function squaring 2-d array python
has answer: http://stackoverflow.com/a/49760550
has answer: http://stackoverflow.com/a/49760476
has comment: http://stackoverflow.com/comment/86535877
tagged with: python
has body: I have a function that takes in any 2-d array and return a 2-d array (the same format as the array being implemented) but the values are squared. i.e [[1,2],[3,4]] -----> [[1,4],[9,16]] my code so far: m0 = [[1,2],[3,4]] empty_list = [] for x in m0: for i in x: empyt_list.append(x**2) This gives me a 1-d array but how would i return a 2-d array as the imputed value?
tagged with: list
answer count: 3
upvote count: 3
type: UnansweredQuestion
score: 3

http://stackoverflow.com/q/49913350
tagged with: atom-editor
answer count: 0
tagged with: google-translation-api
score: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86855292
type: UnansweredQuestion
has body: So I have recently installed Atom text editor on my UNIX machine and tried to run this simple Google API's translator program but it's giving me an "ImportError: No module named googletrans". I have already installed googletrans in bash console through pip and this same program is giving me a desired output in IDLE but I want to make to it work in ATOM as well. Do I have to install any kind of package or something in ATOM in order for this to work? Any help would be appreciated. #!/usr/bin/env python # -*- coding: utf-8 -*- from googletrans import Translator translator = Translator() translator.translate('안녕하세요.') translations = translator.translate(['The quick brown fox', 'jumps over', 'the lazy dog'], dest='hi') for translation in translations: print(translation.origin, ' -&gt; ', translation.text)
tagged with: python
has comment: http://stackoverflow.com/comment/86867846
has title: Why "from googletrans import Translator" is not working in Atom text editor
upvote count: 2

http://stackoverflow.com/a/49785512
answers question: http://stackoverflow.com/q/49785298
type: Answer
score: 0
has body: Just for the record (new to Python) I had named my py file name as uff

http://stackoverflow.com/comment/86658639
score: 1
comment on: http://stackoverflow.com/q/49821663
type: Comment
has text: If you know how many lines to expect, you can skip the first N-M lines and print the remaining M lines. If you do not know, collect all lines into a list and then print the last M lines from the list. It is as easy as `print("\n".join(list(stdout)[-M:]))`.
type: QuestionComment

http://stackoverflow.com/comment/86541944
score: 3
comment on: http://stackoverflow.com/q/49763005
type: QuestionComment
type: Comment
has text: df['NewText'] = np.where((df['Text1'] =="abc" )& ((pd.to_datetime('today') -df['Date1'] ).dt.days< 90), "New", np.nan)

http://stackoverflow.com/q/49831943
has title: what are the parameters of configure method of tkinter/tk()
has body: Code: root = Tk() root.configure(background="red") Which parameters (args) are present in the .configure method. Is it just background and if not how do I view them?
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/49832277
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67552809
tagged with: python

http://stackoverflow.com/a/53982724
answers question: http://stackoverflow.com/q/49899973
type: Answer
has body: your cold should be right expect for '0'should be 0. I have tried.
score: 0

http://stackoverflow.com/a/49847346
type: Answer
answers question: http://stackoverflow.com/q/49846726
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86711961
has body: You could compute the cosine similarity by yourself. from scipy import lingalg cosineSim1 = 1 - np.sum(a * b, axis=-1)/(linalg.norm(a,axis=-1) * linalg.norm(b,axis=-1)) Test whether you get correct values: from scipy import spatial cosineSim2 = [] for row_a, row_b in zip(a,b): cosineSim2.append(spatial.distance.cosine(row_a, row_b)) np.allclose(cosineSim1, cosineSim2). # Should output True Timing tests: timeit.timeit(func1, number=100) # computes cosineSim1 0.006364107131958008 timeit.timeit(func2, number=100) # computes cosineSim2 0.34532594680786133
accepted answer of: http://stackoverflow.com/q/49846726

http://stackoverflow.com/a/56444043
has body: This is how I succeeded: You need a fortran compiler. If you're a student (like me), you can get it from intel for free: https://software.intel.com/en-us/qualify-for-free-software/student Clone the repo for https://pypi.org/project/glmnet/ from https://github.com/civisanalytics/python-glmnet. Launch the fortran compiler environment in a command prompt Navigate to the folder where you cloned the repo Activate the conda environment you want to install glmnet into Run python setup.py install The package will now be available as glmnet_python
answers question: http://stackoverflow.com/q/49803270
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/49762388
tagged with: python-3.x
linked to: http://stackoverflow.com/q/1035340
has body: SIFT keypoints in opencv have been saved in a .bin file. I want to load the file into Python and use them. The total number of keypoints is 6022451 from 7865 images. I followed the link, however, there are many solutions and I do not know which one should I follow to read keypoints for each image. I am really confused and a beginner. Could someone please help?
answer count: 0
type: UnansweredQuestion
score: 1
has title: I want to open bin files that have been saved in opencv into python?
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: opencv
tagged with: python-2.7
tagged with: opencv3.0
tagged with: python

http://stackoverflow.com/comment/86543324
type: QuestionComment
comment on: http://stackoverflow.com/q/49763716
score: 0
has text: See [here](https://gist.github.com/abarnert/d1ed16846b6dcf280ac28cf679970177) for an example.
type: Comment

http://stackoverflow.com/a/56678167
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49839610
score: 1
type: Answer
has body: Try this command. python -m pip install --user pip==9.0.1

http://stackoverflow.com/comment/86787841
has text: I get the following error `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 self._setitem_with_indexer(indexer, value) __main__:1: 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`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49885777

http://stackoverflow.com/comment/86696896
type: QuestionComment
comment on: http://stackoverflow.com/q/49841133
score: 3
has text: `typing` is the wrong tool for that. You're trying to check the _value_ of the string, not the _type_. If you want type safety, use an enum.
type: Comment

http://stackoverflow.com/comment/86706223
has text: I chose to use the absolute path directly and it works like a charm!
score: 0
comment on: http://stackoverflow.com/a/49845421
type: AnswerComment
type: Comment

multithreading
tags question: http://stackoverflow.com/q/49843439
tags question: http://stackoverflow.com/q/49786514
tags question: http://stackoverflow.com/q/49850472
tags question: http://stackoverflow.com/q/49823312
tags question: http://stackoverflow.com/q/49788400
tags question: http://stackoverflow.com/q/49840296
tags question: http://stackoverflow.com/q/49834815
tags question: http://stackoverflow.com/q/49859287
type: Tag
tags question: http://stackoverflow.com/q/49784953
tags question: http://stackoverflow.com/q/49842120
tags question: http://stackoverflow.com/q/49822090
tags question: http://stackoverflow.com/q/49792733
tags question: http://stackoverflow.com/q/49779402
tags question: http://stackoverflow.com/q/49910741
tags question: http://stackoverflow.com/q/49905087
tags question: http://stackoverflow.com/q/49790464
tags question: http://stackoverflow.com/q/49850047
tags question: http://stackoverflow.com/q/49775762
tags question: http://stackoverflow.com/q/49907785
tags question: http://stackoverflow.com/q/49775547
tags question: http://stackoverflow.com/q/49857892
tags question: http://stackoverflow.com/q/49912013
tag name: multithreading
tags question: http://stackoverflow.com/q/49779340
tags question: http://stackoverflow.com/q/49836591
tags question: http://stackoverflow.com/q/49764606
tags question: http://stackoverflow.com/q/49886684
tags question: http://stackoverflow.com/q/49907262
tags question: http://stackoverflow.com/q/49861594

http://stackoverflow.com/comment/86835595
score: 0
has text: I expect that the first value should be exactly 0.(as it was defined in theory)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49909773

http://stackoverflow.com/a/49762093
has comment: http://stackoverflow.com/comment/86540030
has comment: http://stackoverflow.com/comment/86539797
has comment: http://stackoverflow.com/comment/86541375
score: 2
has body: If you're ok with using regular expressions, you can do it in the following way: re.sub(r'Lat:\s+(.*)\s+Lon:\s+(.*)\s+[A-Z]\w+:\s+(.*)\s+[A-Z]\w+:\s+(.*)', '(\1, \2, \3, \4)', string) <a href="https://pythex.org/?regex=Lat%3A%5Cs%2B(.*)%5Cs%2BLon%3A%5Cs%2B(.*)%5Cs%2B%5BA-Z%5D%5Cw%2B%3A%5Cs%2B(.*)%5Cs%2B%5BA-Z%5D%5Cw%2B%3A%5Cs%2B(.*)&amp;test_string=Lat%3A%20-30.0864%2030%C2%B052%E2%80%B257%E2%80%B3S%20Lon%3A%20-51.2245%2051%C2%B018%E2%80%B204%E2%80%B3W%20Distance%3A%204.8959%20km%20Meters%3A%204895.9&amp;ignorecase=0&amp;multiline=0&amp;dotall=0&amp;verbose=0" rel="nofollow noreferrer">Check it out! It's not clear from your question whether you've already got this in a pandas dataframe, but if you're just looking at the file, you can operate on each line in your file, either by using map() or an iteration.
answers question: http://stackoverflow.com/q/49761753
has comment: http://stackoverflow.com/comment/86540820
upvote count: 2
has comment: http://stackoverflow.com/comment/86539849
downvote count: 0
type: Answer

http://stackoverflow.com/a/49854337
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49854221
has body: we can convert it to a mutable QueryDict instance by copying it: request.GET = request.GET.copy() # update querydict like request.GET['hi'] = 'hello'

http://stackoverflow.com/comment/86790735
comment on: http://stackoverflow.com/q/49886263
type: QuestionComment
has text: The abbreviated strings form a prefix-free language.
type: Comment
score: 0

http://stackoverflow.com/comment/86810684
type: QuestionComment
has text: Looking at the code you pasted here I was expecting python to throw up a different error!
score: 0
comment on: http://stackoverflow.com/q/49897492
type: Comment

http://stackoverflow.com/comment/126213339
score: 0
has text: Please mention your working environment or Operating System, so it would help others who view your answer.
comment on: http://stackoverflow.com/a/71373563
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49916268
type: Question
tagged with: numpy
has body: I don't understand when it is sum operation or just connect two arrays x = np.arange(10) x #array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) x[4]=44 x #array([ 0, 1, 2, 3, 44, 5, 6, 7, 8, 9]) xs=np.split(x,5) xs #[array([0, 1]), array([2, 3]), array([44, 5]), array([6, 7]), array([8, 9])] what is this shape ? xs=np.split(x,5) xs #[array([0, 1]), array([2, 3]), array([44, 5]), array([6, 7]), array([8, 9])] i=2 xscn = np.concatenate((xs[:i]+xs[i+1:])) xscn #array([0, 1, 2, 3, 6, 7, 8, 9]) "so why it no summing the array just put them side side (not ariane grande ha ha ha" f=(xs[:i]+xs[i+1:]) f #[array([0, 1]), array([2, 3]), array([6, 7]), array([8, 9])] so it just put one array after other. cc=np.concatenate(f) cc #array([0, 1, 2, 3, 6, 7, 8, 9]) ff=xs[:i]+xs[i+1:] ff #[array([0, 1]), array([2, 3]), array([6, 7]), array([8, 9])] so when it adds and when it just sets one list after other also I can't type the shapes.
tagged with: numpy-ndarray
answer count: 1
accepted answer: http://stackoverflow.com/a/49928599
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: list
tagged with: concatenation
has title: How to connect Python arrays
has answer: http://stackoverflow.com/a/49928599

http://stackoverflow.com/comment/86740638
comment on: http://stackoverflow.com/a/49861970
has text: It is, in this case, where the colored pixels are inside the rectangle. That's why the workaround works.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49782397
upvote count: 1
has title: Transpose DataFrame based on Column Name Defined Range
has body: So I have some server logs that i'm trying to parse into a tabular format. Imagine the logs are structured like this a = "value1" b = "value2" c = "value3" a = "value4" c = "value5" a = "value2" b = "value12" c = "value8" Where my definition of a 'record' (or row in my final DataFrame) are all of the columns from A to C. In reality there are 30 or so columns, by the starting column name and ending column name are always the same. I can very easily read this file into a list (using the split("=") function) and arrive at something like this: index value 1 ['a , 'value1'] 2 ['b , 'value2'] 3 ['c , 'value3'] 4 ['a , 'value4'] 5 ['c , 'value5'] 6 ['a , 'value2'] 7 ['b , 'value12'] 8 ['c , 'value8'] I can even convert that to a 1 record dataframe with something like: df = pd.DataFrame(List).transpose() but I arrive at a DataFrame where Columns are repeated like a b c a1 c2 a3 b1 c3 value1, value2, value3, value4, value5, value2, value12, value8 What I really want is something that looks like this: A B C Value1 Value2 Value3 Value4 NULL Value5 Value2 Value12 Value8 Any thoughts how to perform that transpose step to tell it to insert a new record in the DataFrame every time it sees "c" and keep writing until the next time it sees a C, placing a NULL value where no record exists for a particular column? Am i going about this entirely incorrectly?
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
favorite count: 0
type: Question
tagged with: transform
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49782484
answer count: 1
downvote count: 0

http://stackoverflow.com/a/50067683
has body: As Akhilesh suggested, a morphology OPEN operation will remove the line connecting the two rectangles. An excellent Python tutorial is here: https://docs.opencv.org/3.0.0/d9/d61/tutorial_py_morphological_ops.html. Use the smallest kernel size that will work for your application to prevent too much distortion. For your test image, I used a kernel size of 5. detect_shapes.py: import cv2 from shapedetector import ShapeDetector image = cv2.imread('rectangles.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1] ksize = 5 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (ksize,ksize)) thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel) cnts = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # ~ cnts = cnts[0] if imutils.is_cv2() else cnts[1] cnts = cnts[1] sd = ShapeDetector() for c in cnts: M = cv2.moments(c) if M["m00"] != 0: # prevent divide by zero cX = int((M["m10"] / M["m00"])) cY = int((M["m01"] / M["m00"])) shape = sd.detect(c) c = c.astype("float") #c *= ratio c = c.astype("int") cv2.drawContours(image, [c], -1, (0, 255, 0), 2) cv2.putText(image, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2) cv2.imshow("Image", image) cv2.waitKey(0) shapedetector.py: import cv2 class ShapeDetector: def __init__(self): pass def detect(self, c): shape = "unidentified" peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.04 * peri, True) if len(approx) == 3: shape = "triangle" elif len(approx) == 4: print("value of approx", approx) (x, y, w, h) = cv2.boundingRect(approx) ar = w / float(h) print("value of ar",ar) if (ar &gt;= 0.95 and ar &lt;= 1.05): shape = "Square" elif (ar &lt;= 5 and ar &gt;= 3): shape = "Obround" else: shape = "rectangle" elif len(approx) == 5: shape = "pentagon" elif len(approx) == 2: shape = "line" print("value of approx", approx) else: shape = "circle" print("value of approx", approx) return shape …
answers question: http://stackoverflow.com/q/49792226
score: 3
upvote count: 3
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86639519
comment on: http://stackoverflow.com/q/49812284
has text: See Robert Kern's response here: https://stackoverflow.com/questions/5836335/consistenly-create-same-random-numpy-array/5837352#5837352although and here: https://stackoverflow.com/questions/37224116/difference-between-randomstate-and-seed-in-numpy
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86840669
comment on: http://stackoverflow.com/q/49912438
type: Comment
type: QuestionComment
score: 0
has text: You should learn how to debug your Python code.

http://stackoverflow.com/q/49877021
tagged with: class
has title: NameError in class - calling a previously defined variable
tagged with: oop
upvote count: 1
score: 1
linked to: http://stackoverflow.com/q/38318370
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/38318370
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86769592
tagged with: python
has body: I'm new to OOP, and I'm trying to write a simple class below, but I keep getting a NameError class rng(object): _rand_nums = [6,3,2,1] _p = [0.1,2,0.7,0.4] if any(i &gt;= 1 for i in _p): _norm = sum(_p) _p = [i/_norm for i in _p] When I try to run this, I get: &lt;ipython-input-116-097f599a4ce0&gt; in &lt;listcomp&gt;(.0) 15 if any(i &gt;= 1 for i in _p): 16 _norm = sum(_p) ---&gt; 17 _p = [i/_norm for i in _p] NameError: name '_norm' is not defined What's wrong with my code? I thought I defined _norm fine.
has comment: http://stackoverflow.com/comment/86769635

http://stackoverflow.com/q/49766927
score: 0
type: UnansweredQuestion
answer count: 1
has title: Python Django Celery doesn't pick the task from the RabbitMQ
type: Question
has answer: http://stackoverflow.com/a/49767106
tagged with: django-celery
tagged with: python
tagged with: rabbitmq
has body: I am working in a Python Django project. One of its functionality is when someone send some data from a web application, foreward them to a mobile device. For this functionality, application uses third party services as GCM &amp; Amazon SNS. Following is the data flow of the application. Web Application ------> Amazon SNS -------> GCM -------> Android Device Due to the possible network delays, operational delays and failures in Amazon SNS side, web application uses celery as the scheduler application to achieve behaviors like asynchronous, retrying etc. Celery stores SNS sending task in a queue and process them asynchronously. Celery as the scheduler uses RabbitMQ as its broker application. All together following is the data flow. Web App --> Celery --> RabbitMQ --> Amazon SNS --> GCM --> Android Device An issue is identified related to the Celery and RabbitMQ components. We can see when celery sends a task to RabbitMQ, particular RabbitMQ queue count grows which means celery successfully created a task object and sent to the queue. But particular task is exist in the queue forever(queue count doesn't reduced) and doesn't proceed to send the message to the Amazon SNS, which means Celery doesn't pick the stored task again from the queue. (I could successfully push a message to the SNS bypassing the Celery which means there is no connection issue to the SNS.) Which may cause celery not to pick the stored task from the RabbitMQ ?

http://stackoverflow.com/a/49912981
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/86842357
type: Answer
has body: Using regex import re s = "dssdfsdfsdfsdf 10/01/18 ssdfsfsf dsfsdfsdfsd" print(re.findall("\d{2}/\d{2}/\d{2}", s)) Output: ['10/01/18'] In your case: for line in f: date = re.search("\d{2}/\d{2}/\d{2}", line): if date: print(line, date.group())
has comment: http://stackoverflow.com/comment/86841987
has comment: http://stackoverflow.com/comment/86843090
answers question: http://stackoverflow.com/q/49912875
has comment: http://stackoverflow.com/comment/86841914
upvote count: 1

http://stackoverflow.com/comment/86543748
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49763957
score: 0
has text: @Aran-Fey Thanks, solved my issue. Should I delete this post?

http://stackoverflow.com/a/49819414
score: 2
has comment: http://stackoverflow.com/comment/86658062
has body: This is happening because the backslashes in your file path string our being treated as special characters. To fix this issue you need to let python know they are part of the path you can do this by converting the string into a raw string by putting a r before the start of the string or by escaping the backslashes by putting another backslash before them so all backslashes become double backslashes.
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49819273
has comment: http://stackoverflow.com/comment/86654686

web-crawler
tags question: http://stackoverflow.com/q/49832797
tags question: http://stackoverflow.com/q/49797957
tags question: http://stackoverflow.com/q/49764405
tags question: http://stackoverflow.com/q/49899506
tags question: http://stackoverflow.com/q/49794946
tags question: http://stackoverflow.com/q/49902438
tags question: http://stackoverflow.com/q/49844084
tags question: http://stackoverflow.com/q/49881728
tags question: http://stackoverflow.com/q/49826440
tags question: http://stackoverflow.com/q/49890686
tags question: http://stackoverflow.com/q/49912025
tags question: http://stackoverflow.com/q/49808607
tag name: web-crawler
tags question: http://stackoverflow.com/q/49836555
tags question: http://stackoverflow.com/q/49765898
type: Tag

http://stackoverflow.com/comment/86816487
type: QuestionComment
has text: Alfe: I did .Can you just suggest if not code :)
score: 0
comment on: http://stackoverflow.com/q/49879865
type: Comment

http://stackoverflow.com/comment/86636470
has text: Is it possible to share the URL?
score: 0
comment on: http://stackoverflow.com/q/49809492
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86552720
has text: You can try like `len(list(sensor))`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49768750

http://stackoverflow.com/comment/86647970
type: Comment
has text: I added. See question
comment on: http://stackoverflow.com/a/49816506
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86753677
score: 0
has text: @HolyCrack Done.
comment on: http://stackoverflow.com/a/49868943
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86579653
score: 0
has text: @iam.Carrot Updated my answer to show how to read files directly out of the zip archive, no need to extract the data to disk.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49782154

http://stackoverflow.com/q/49796534
type: Question
has comment: http://stackoverflow.com/comment/86607476
has body: I'm trying to read a file (reading every line in this file, with letters, numbers and characters). The script needs to work generally and the files will be similar but with some changes. Now it reads when it finds a line looks like this: "**HWCOLOR COMP 1066 30". I need that the script read all lines until it finds " **HW ". The script below is working for first problem explained. How can the script be written to read the file until it finds "**HW" and stops there? I tried to replace '**HWCOLOR COMP 1066 30" with **HW" but it won't work, because all characters don't match. data = [] with open('valvebody_nodes_rec.txt') as f: # Skips text before the beginning of the interesting block: for line in f: if line.strip() == '*NODE, SYSTEM=R': break # Reads text until the end of the block: for line in f: if line.strip() == '**HWCOLOR COMP 1066 30': break data.append([x.strip() for x in line.split(',')]) #intersect text
has comment: http://stackoverflow.com/comment/86607473
tagged with: python
tagged with: filereader
type: AnsweredQuestion
has title: Read lines until find specific characters
has comment: http://stackoverflow.com/comment/86607629
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/86607667
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/49796708
accepted answer: http://stackoverflow.com/a/49796708
favorite count: 0

http://stackoverflow.com/a/49873639
has body: SQLite will happily reorder AND-connected expressions whenever it feels like it. So while rewriting the query to check column2 first appears to work in the current version, there is no guarantee. The query optimizer assumes that speed is determined mainly by disk I/O, so it estimates the cost of both conditions to be the same. Cost estimates are influenced by indexes, and by ANALYZE statistics (which work only for indexed data). So the easiest way to speed up this query (and probably most other queries you will use) is to create an index on column2: CREATE INDEX my_little_index ON mytable(column2); If you do not want to use an index for some reason, you have to use a construct that the query optimizer cannot optimize away. A CASE expression as shown in Gordon's answer would work just fine. In the general case, move the first condition into a subquery and prevent subquery flattening by breaking one of the listed rules; adding a dummy LIMIT clause to both queries usually is easiest: SELECT * FROM (SELECT * FROM mytable WHERE column2 &lt; 1000 LIMIT -1) WHERE myfunction(description) &lt; 500 LIMIT -1;
has comment: http://stackoverflow.com/comment/86773955
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49861513
downvote count: 0
has comment: http://stackoverflow.com/comment/86764853

http://stackoverflow.com/q/49762347
has title: Mouse remote control
tagged with: python
has body: Trying to implement some kind of synergy on python using PyAutoGui and socket communication. The idea is to control mouse and keyboard of another computer on LAN by using mouse/keyboard of a server computer. By now it's only mouse movement implementaion. Here are some classes: Server part: class Server: def __init__(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.ip = get_ip() self.port = 3000 self.transfer_mod = False self.client_address = "" def start(self): print("Started server with ip: {}".format(self.ip)) self.s.bind((self.ip, self.port)) self.get_connection() def get_connection(self): print("Waiting for connection...") while True: request, self.client_address = self.s.recvfrom(4096) if request: self.s.sendto(request, self.client_address) print("{} connected!".format(self.client_address)) break def enable_transfer(self): print("Transfer to {} enabled".format(self.client_address)) self.transfer_mod = True transfer_thread = threading.Thread(target=self.transfer_mouse) transfer_thread.start() def disable_transfer(self): print("Transfer to {} disabled".format(self.client_address)) self.transfer_mod = False def transfer_mouse(self): previous_pos = (-1, -1) while self.transfer_mod: pos = pyautogui.position() if pos != previous_pos: data = pickle.dumps(pos) self.s.sendto(data, self.client_address) sleep(0.1) previous_pos = pos def close(self): self.disable_transfer() self.s.close() Client part: class Client: def __init__(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.port = 3000 self.connection = False def connect(self, server_ip): request = bytes("Request","utf-8") self.s.sendto(request, (server_ip, self.port)) received, address = self.s.recvfrom(4096) if received == request: print("Connected to {}".format(server_ip)) self.connection = True threading.Thread(target=self.receive_data).start() def receive_data(self): while self.connection: data, server = self.s.recvfrom(4096) pos = pickle.loads(data) self.control_mouse(pos) …
tagged with: mouse
downvote count: 1
tagged with: udp
has comment: http://stackoverflow.com/comment/86551769
upvote count: 3
has comment: http://stackoverflow.com/comment/124536862
tagged with: pyautogui
favorite count: 0
has comment: http://stackoverflow.com/comment/86541009
type: Question
score: 2
answer count: 0
type: UnansweredQuestion
tagged with: sockets

http://stackoverflow.com/comment/86844934
type: AnswerComment
comment on: http://stackoverflow.com/a/49904145
has text: This doesn't work. repr() just seems to add quotes around df['filename'] + '.xml'. I still get the same error.
type: Comment
score: 0

http://stackoverflow.com/q/49910419
score: 0
tagged with: filenames
has body: I'm importing images to Keras from a directory. The code looks something like this: gen = datagen.flow_from_directory ( DIRECTORY, target_size = (IMAGE_WIDTH, IMAGE_HEIGHT), batch_size = BATCH_SIZE, class_mode = "binary" ) However, my data is organized not by folders, but by filenames. If I couldn't change this structure, is there any way to flow while separating by a regex (say, ending with ".jpg" vs. ".png", or starting with "numeral_7" vs "numeral_8")?
answer count: 1
has title: Keras: flow_from_directory() or flow() using filenames instead of directories
type: Question
has answer: http://stackoverflow.com/a/50163094
type: UnansweredQuestion
tagged with: python
tagged with: keras
tagged with: regex

http://stackoverflow.com/a/49867468
score: 2
accepted answer of: http://stackoverflow.com/q/49867435
upvote count: 2
has comment: http://stackoverflow.com/comment/86750539
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86751014
has comment: http://stackoverflow.com/comment/86750440
has comment: http://stackoverflow.com/comment/86750497
has comment: http://stackoverflow.com/comment/86750453
answers question: http://stackoverflow.com/q/49867435
has comment: http://stackoverflow.com/comment/86750462
type: Answer
has body: Maybe using a class variable? class Foo: a = None def __init__(self): if not Foo.a: Foo.a = A() b = B(Foo.a.var) And function B needs to check whether a is None.

http://stackoverflow.com/comment/86755451
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49865057
has text: What are the elements of x? Are they strings or time/date objects? Note that the rectangle rule is actually more accurate than the trapezoid rule, and very simple, so why not just form dx = (x[k + 1] minus x[k] for k = 1, ... n - 1) and multiply that times y and add it up.

http://stackoverflow.com/q/49772151
has answer: http://stackoverflow.com/a/66469837
linked to: http://stackoverflow.com/q/64226700
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/95476729
score: 67
tagged with: python
tagged with: boto3
has answer: http://stackoverflow.com/a/54672690
has answer: http://stackoverflow.com/a/72405960
possible better answer: http://stackoverflow.com/a/62945526
has title: Download a folder from S3 using Boto3
has answer: http://stackoverflow.com/a/74872172
answer count: 11
has answer: http://stackoverflow.com/a/77657872
upvote count: 67
has answer: http://stackoverflow.com/a/71797381
has answer: http://stackoverflow.com/a/62945526
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65938923
has answer: http://stackoverflow.com/a/61187665
accepted answer: http://stackoverflow.com/a/54672690
has comment: http://stackoverflow.com/comment/86559492
linked to: http://stackoverflow.com/q/31918960
downvote count: 0
has body: Using Boto3 Python SDK, I was able to download files using the method bucket.download_file() Is there a way to download an entire folder?
has answer: http://stackoverflow.com/a/68297406
tagged with: amazon-web-services
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/66513705
tagged with: download

http://stackoverflow.com/q/49878632
has body: I am getting the following error: "werkzeug.routing.BuildError: Could not build url for endpoint 'setpassword'. Did you forget to specify values ['token']?" main.py: @app.route('/setpassword/&lt;token&gt;',methods=['GET','POST']) def setpassword(token): form = PasswordForm() return render_template('setpassword.html',form=form, token=token) setpassword.html: {% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% from '_macros.html' import hello %} {% block title %}SetPassword{% endblock %} {% block content %} {% for i in form.password.validators %} {{ i.message }} {% endfor %} &lt;form class="form form-horizontal " action="{{ url_for('setpassword') }}" method=post role="form"&gt; {{ form.hidden_tag() }} {{ wtf.form_field(form.password, hiddens='True',placeholder='Enter Password') }} {% for e in form.password.errors %} &lt;span class="label label-danger" id="labelerror"&gt;{{ e }}&lt;/span&gt; {% endfor %} {{ wtf.form_field(form.confirm, class='form-control' , placeholder='Confirm Password') }} {{ wtf.form_field(form.submit , class='btn btn-primary btn-block' ) }} &lt;/form&gt; {% endblock %} Why is this error occurring and how do I stop it occurring?
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: flask
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49878730
has title: flask url parameters gives error
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: -1

http://stackoverflow.com/comment/86674805
has text: Your requirement is that you only want the lines that contain one of the keywords to be printed out and skip others?
score: 0
comment on: http://stackoverflow.com/q/49829614
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86588803
score: 0
has text: If you want to do it yourself, you can create a C extension library, or a regular C library that you access via `ctypes` or `cffi`. [This answer](https://stackoverflow.com/a/32545972/908494) shows how to write a C function with inline assembly that I think will work on Mac and Linux with clang and gcc; you'll probably need to find another source for how to do it on Windows with MSVC. (Or maybe just look at the source of those packages on PyPI.) [Wikipedia](https://en.wikipedia.org/wiki/CPUID) has a pretty good explanation of the basics of using `cpuid`.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49786441

http://stackoverflow.com/a/49841308
answers question: http://stackoverflow.com/q/49840723
has comment: http://stackoverflow.com/comment/86701027
has body: It sounds like you're wanting to dynamically create variables. That's almost always a foolish thing to do. Instead, you should be using a data structure like a list or dictionary, indexed by the parts of the variable name you wanted to generate dynamically. So instead of creating a list named filetype000, start with a list named filetypes, and append an inner list, so you can do filetypes[0] to get at it. Or if string names make more sense for your specific application, let filetypes be a dictionary, and access the inner lists with something like filetypes['pdf']. I'm being a little vague here because I don't really understand all of your pseudocode. It's not at all obvious what the purpose of the [automatically incrementing number] parts of your example are, so I'm more or less ignoring those bits. You probably just want to start with an empty list and append values to it, rather than somehow initializing it to a specific size and magically indexing it.
has comment: http://stackoverflow.com/comment/86700932
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49840723
score: 0
type: Answer

http://stackoverflow.com/a/49783136
downvote count: 0
answers question: http://stackoverflow.com/q/49782180
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/49782180
upvote count: 2
has body: This is an important point to note and a common confusion in TF. That function will NOT be called by tensorflow in a session, no python function will, with the exception of tf.py_func, which could be a workaround to your problem. Tensorflow calls your function Q only to get the symbolic operations and then adds those operations to the dependency graph. During a session, the dependency graph is all that is relied upon to perform computations. Even if you are using a tf.while, tf.cond, or other control flow operation. None of these call python during a session, they just loop over elements in the dependency graph as you defined. In general there's no good way to stop the execution of tensorflow mid-graph execution short of using the Tensorflow Debugger (which is not hard to configure at all). But as a workaround you might get away with defining a tf.py_func python function. This function marshals a tensor into a python object and calls python during session execution (it's not efficient or anything, but it's handy in certain cases). You may need to use with tf.control_dependencies(...): to force your tf.py_func operation to run (since it wouldn't have any dependency if it had nothing but a print statement inside of it). Disclamer: I haven't used tf.py_func this way nor was it built with this intention.
type: AcceptedAnswer

http://stackoverflow.com/comment/86539421
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49761020
score: 0
has text: As I recall, this happens when no improvement to the initial parameters can be found. When I saw this long ago, I had not written my program correctly. I will review the code you posted and see if I can find anything.

http://stackoverflow.com/comment/86777216
comment on: http://stackoverflow.com/q/49880700
type: QuestionComment
score: 0
has text: Try to read the error message, both of your questions are answered there.
type: Comment

http://stackoverflow.com/a/49863309
score: 0
answers question: http://stackoverflow.com/q/49863192
type: Answer
has body: This should work to deal with most cases. Remove the dollar sign with replace and then pandas.to_numeric() will convert it to a float. Anything that isn't a number is coerced to np.NaN, giving you a column with dtype: float64 import pandas as pd import numpy as np df = pd.DataFrame({'Land Value': ['$10.31', '$17.81', np.NaN, 'NaN', None, '$ 102.13']}) pd.to_numeric(df['Land Value'].str.replace('$', ''), errors='coerce') #0 10.31 #1 17.81 #2 NaN #3 NaN #4 NaN #5 102.13 #Name: Land Value, dtype: float64 Just make sure to assign it back in the end. col_list = ['Land Value', 'Improvement Value', 'Total Value', 'Sale Price'] for item in col_list: props[item] = pd.to_numeric(props[item].str.replace('$', ''), errors='coerce')

python-social-auth
tags question: http://stackoverflow.com/q/49863981
tag name: python-social-auth
type: Tag

http://stackoverflow.com/comment/87818175
type: Comment
type: QuestionComment
has text: Did you figure out an answer to this?
score: 0
comment on: http://stackoverflow.com/q/49782579

http://stackoverflow.com/a/50284449
type: Answer
answers question: http://stackoverflow.com/q/49834648
score: 0
has body: I have the exact same problem. And, yes, it happens every time that I open IDLE. I have Python 3.6.5 in a folder in Program Files, while the files that I have written are in a folder labeled Python under C:\Users\John\Documents. I have a hunch that Python wants the files that I have written in a different location, perhaps under C:\Users\John.idlerc? What do folks think? JohnR PS ~ I didn't see on this web page where to find the answers that others wrote to the original inquiry.

http://stackoverflow.com/comment/86602956
comment on: http://stackoverflow.com/a/49789068
has text: in short, yes: https://github.com/python/cpython/blob/4ae06c5337e01bdde28bce57b6b9166ad50947e3/Python/thread.c and https://github.com/python/cpython/blob/aa0735f597b072c0eb00404c4d7df359ddc26755/Modules/_threadmodule.c
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/51573381
accepted answer of: http://stackoverflow.com/q/49817409
score: 77
downvote count: 0
has body: I'd suggest running the foo function from the new notebook. In other words: %run ./called_notebook.ipynb foo() In my opinion, this is best practices for using the %run magic command. Store your high level APIs in a separate notebook (such as foo), but keep your function calls visible in the master notebook.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/98006767
has comment: http://stackoverflow.com/comment/123445131
has comment: http://stackoverflow.com/comment/130990591
has comment: http://stackoverflow.com/comment/112762606
has comment: http://stackoverflow.com/comment/114563168
type: Answer
answers question: http://stackoverflow.com/q/49817409
upvote count: 77

http://stackoverflow.com/q/49840543
has comment: http://stackoverflow.com/comment/86695805
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/60618685
downvote count: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/86695771
favorite count: 0
type: Question
has title: Changing which Python version pip points to
has body: I am using python2.7 and python3.5 on Ubuntu 16.04. After upgrading pip to v10 I am no longer able to install packages for python2.7 using pip. How can I change pip to point to python2.7? $ pip -V pip 10.0.0 from /home/username/.local/lib/python3.5/site-packages/pip (python 3.5) $ pip3 -V pip 10.0.0 from /home/username/.local/lib/python3.5/site-packages/pip (python 3.5) $ which python /usr/bin/python $ which python3 /usr/bin/python3 $ python -V Python 2.7.12 $ python3 -V Python 3.5.2 $ which pip /usr/local/bin/pip $ which pip3 /usr/local/bin/pip3 $ python3 -m pip install some_module $ python -m pip install some_module python/python3 -m pip install some_module both installs to python 3.5. Using Anaconda is not an option.
upvote count: 8
has answer: http://stackoverflow.com/a/55270355
has comment: http://stackoverflow.com/comment/86695685
has comment: http://stackoverflow.com/comment/86695714
linked to: http://stackoverflow.com/q/45871761
has comment: http://stackoverflow.com/comment/86700724
tagged with: python
answer count: 4
score: 8
has answer: http://stackoverflow.com/a/60681389
has answer: http://stackoverflow.com/a/49842073

http://stackoverflow.com/q/49846902
answer count: 1
has comment: http://stackoverflow.com/comment/86710954
downvote count: 0
has title: Integration with piecewise functions
has comment: http://stackoverflow.com/comment/86708827
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49847046
has comment: http://stackoverflow.com/comment/86709097
score: 2
upvote count: 2
type: UnansweredQuestion
has body: In my computation, I need the following numerically in Python. z has a range [0, 4]. From the help of Andrey Tyukin, I wrote the codes. However, I can't determine the following codes.

http://stackoverflow.com/a/49859858
downvote count: 0
score: 3
upvote count: 3
type: Answer
has body: The first one is not a list but a string, so you might get along with: from ast import literal_eval status = "[['0', '2', '3', '5']]" status = literal_eval(status) status = status[0] print(status) This yields ['0', '2', '3', '5'] But please consider correcting the string in the first place (where does it come from?).
answers question: http://stackoverflow.com/q/49859825

http://stackoverflow.com/comment/86539155
type: Comment
type: QuestionComment
has text: @bgse check() doesn't return anything, except loading another html page. but reason() has to load reason.html, that's where I grab user input and send it to check(). check() checks certain thing and if true returns a control.html page. thanks
comment on: http://stackoverflow.com/q/49761512
score: 0

http://stackoverflow.com/a/49837594
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86796745
accepted answer of: http://stackoverflow.com/q/49837426
has body: No, you need not do loss masking. I assume you want a fixed length vector output for each sequence. Since you are giving the sequence length as input, dynamic RNN automatically makes sure that the state is copied through for the sequence outside the sequence length. Reference: https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn. Look at the information about the sequence_length argument.
score: 2
has comment: http://stackoverflow.com/comment/86797008
upvote count: 2
answers question: http://stackoverflow.com/q/49837426
type: AcceptedAnswer

openmdao
tag name: openmdao
type: Tag
tags question: http://stackoverflow.com/q/49834299

http://stackoverflow.com/comment/86750242
score: 0
type: AnswerComment
has text: Iterating over a dict and looking up strings in lists is abuse of data structures (read: it's slow and arguably ugly code). A much better solution is to invert the dict like jonrsharpe did in his answer, which makes looking up the correct spelling trivial and O(1).
type: Comment
comment on: http://stackoverflow.com/a/49867000

http://stackoverflow.com/comment/86836090
comment on: http://stackoverflow.com/a/49896145
has text: Yes indeed. I didn't realise that key wasn't unique. I like your solution below.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49786743
type: Question
has answer: http://stackoverflow.com/a/49786788
has answer: http://stackoverflow.com/a/49786781
score: 3
has comment: http://stackoverflow.com/comment/86588851
tagged with: stdout
has answer: http://stackoverflow.com/a/49786958
tagged with: python
has answer: http://stackoverflow.com/a/49786780
accepted answer: http://stackoverflow.com/a/49786780
has comment: http://stackoverflow.com/comment/86588942
answer count: 4
has comment: http://stackoverflow.com/comment/86588971
type: AnsweredQuestion
has title: Why can I not redirect STDOUT using "from sys import stdout"?
upvote count: 3
tagged with: python-import
has body: I'm trying to redirect the STDOUT of a python script to a file. If STDOUT is imported from sys, the script's output does not get redirected to a file: from sys import stdout stdout = open("text", "w") print("Hello") However, if I import only sys and use sys.stdout, the script's output is successfully redirected: import sys sys.stdout = open("text", "w") print("Hello") Why is this? According to this answer the only difference between "import X" and "from X import Y" is the name that is bound. How does this manage to affect stdout?
downvote count: 0
tagged with: sys
possible better answer: http://stackoverflow.com/a/49786781
favorite count: 0

http://stackoverflow.com/comment/86734378
has text: Ah, okay, I thought the version with two results was the "default" and the one with one the special case. Then it makes sense. Still, I think having a second function would be much cleaner.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49859340

http://stackoverflow.com/comment/86664150
type: Comment
has text: Won't work on string values, likely. Convert it first `X[:,1:3].astype(str)` and try it again
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49824027

http://stackoverflow.com/q/49763919
has comment: http://stackoverflow.com/comment/86544949
tagged with: python
has title: Why does my first element in readlines() of a CSV have additional characters?
duplicate of: http://stackoverflow.com/q/13590749
has comment: http://stackoverflow.com/comment/86543490
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/86543584
answer count: 1
has answer: http://stackoverflow.com/a/49763994
has body: I ran the following python code to open a CSV, and the first element had some extra characters in it that aren't present when I view the CSV in a text editor, say Notepad++. priorities_file = open('priorities.txt', 'r') print('Name of the file: ', priorities_file.name) p = priorities_file.readlines() print('Read Line: %s' % (p)) The output looked like this: Name of the file: priorities.txt Read Line: ['ï»¿Autonomy\n', 'Travel\n',... I understand the '\n' and how to remove that from each element, but I don't understand why there are the additional characters in front of the element ' Autonomy'. Can anyone tell me why this is? Bonus points for a way to remove those characters which I honestly couldn't find how to reproduce.
has comment: http://stackoverflow.com/comment/86543696
type: Question
tagged with: readlines
has comment: http://stackoverflow.com/comment/86543636
linked to: http://stackoverflow.com/q/13590749
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/20848761

http://stackoverflow.com/comment/87112213
comment on: http://stackoverflow.com/a/49953725
type: Comment
has text: @capser, if you don't share more details it would difficult to sort your problem out and also the bounty is about to expire
type: AnswerComment
score: 0

http://stackoverflow.com/a/49890291
downvote count: 0
has body: This should work: pip install git+https://github.com/ericmjl/autograd.git@cupy see VCS support.
type: Answer
answers question: http://stackoverflow.com/q/49890196
accepted answer of: http://stackoverflow.com/q/49890196
score: 2
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/49763220
linked to: http://stackoverflow.com/q/65445131
linked to: http://stackoverflow.com/q/24193174
favorite count: 0
type: Question
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49763412
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49763334
has body: Suppose I have the following two dataframes: df1 = pd.DataFrame(np.random.randn(100, 3),columns=['A','B','C']).cumsum() df2 = pd.DataFrame(np.random.randn(100, 3),columns=['A','B','C']).cumsum() My question is that, how can I plot them in one graph such that: The three series of df1 and df2 are still in the same blue, orange and green lines as above. The three series of df1 are in solid lines The three series of df1 are in dashed lines Currently the closest thing I can get is the following: ax = df1.plot(style=['b','y','g']) df2.plot(ax=ax, style=['b','y','g'], linestyle='--') Is there any way to get the color codes used by default by DataFrame.plot()? Or is there any other better approach to achieve what I want? Ideally I don't want to specify any color codes with the style parameter but always use the default colors.
has title: How do I plot two pandas DataFrames in one graph with the same colors but different line styles?
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49772274
upvote count: 6
has answer: http://stackoverflow.com/a/49772274
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/49763412
downvote count: 0
score: 6

http://stackoverflow.com/q/49813003
has comment: http://stackoverflow.com/comment/86644838
has comment: http://stackoverflow.com/comment/86641588
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86644440
tagged with: raspberry-pi
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: raspberry-pi3
tagged with: python
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/86644460
has body: As I said I'm getting error while installing Open cv on Raspberry pi3 I'm following instruction from pyimagesearch. I get error as follow pi@raspberrypi:~ $ sudo python get-pip.py Collecting pip Downloading pip-9.0.3-py2.py3-none-any.whl (1.4MB) 100% |████████████████████████████████| 1.4MB 72kB/s Installing collected packages: pip Found existing installation: pip 9.0.1 Uninstalling pip-9.0.1: Successfully uninstalled pip-9.0.1 Successfully installed pip-9.0.3 pi@raspberrypi:~ $ sudo python3 get-pip.py Collecting pip Using cached pip-9.0.3-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 9.0.1 Uninstalling pip-9.0.1: Successfully uninstalled pip-9.0.1 Successfully installed pip-9.0.3 pi@raspberrypi:~ $ sudo pip install virtualenv virtualenvwrapper Collecting virtualenv Downloading virtualenv-15.2.0-py2.py3-none-any.whl (2.6MB) 100% |████████████████████████████████| 2.6MB 47kB/s Collecting virtualenvwrapper Downloading virtualenvwrapper-4.8.2-py2.py3-none-any.whl Collecting stevedore (from virtualenvwrapper) Downloading stevedore-1.28.0-py2.py3-none-any.whl Collecting virtualenv-clone (from virtualenvwrapper) Downloading virtualenv_clone-0.3.0-py2.py3-none-any.whl Collecting pbr!=2.1.0,&gt;=2.0.0 (from stevedore-&gt;virtualenvwrapper) Downloading pbr-4.0.2-py2.py3-none-any.whl (98kB) 100% |████████████████████████████████| 102kB 278kB/s Requirement already satisfied: six&gt;=1.10.0 in /usr/lib/python3/dist-packages (from stevedore-&gt;virtualenvwrapper) Installing collected packages: virtualenv, pbr, stevedore, virtualenv-clone, virtualenvwrapper Successfully installed pbr-4.0.2 stevedore-1.28.0 virtualenv-15.2.0 virtualenv-clone-0.3.0 virtualenvwrapper-4.8.2 pi@raspberrypi:~ $ sudo rm -rf ~/.cache/pip pi@raspberrypi:~ $ export WORKON_HOME=$HOME/.virtualenvs pi@raspberrypi:~ $ source /usr/local/bin/virtualenvwrapper.sh /usr/bin/python: No module named virtualenvwrapper virtualenvwrapper.sh: There was a problem running the init…
score: 2
tagged with: linux
answer count: 0
has title: Why am I getting error while installing opencv on Raspberrypi3

http://stackoverflow.com/comment/86742598
type: Comment
comment on: http://stackoverflow.com/a/49863696
type: AnswerComment
has text: @user4815162342 fair enough, I'll reword that part.
score: 1

http://stackoverflow.com/comment/86741742
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49863266
score: 1
has text: "iterate over the rows of two numpy arrays" is ambiguous. Do you want to iterate over the rows of two numpy arrays at the same time in one loop or do you want to iterate once over each row in Y for every row in X?

http://stackoverflow.com/comment/86764388
type: Comment
type: QuestionComment
score: 0
has text: Did one of the below solutions help? If so, please consider accepting (green tick on left), so other users know.
comment on: http://stackoverflow.com/q/49835155

http://stackoverflow.com/comment/86617788
has text: @Jimbo you're right, that didn't seem to be doing anything. It's still just listing the default. I'll update that, and show how you could set and get the colors for the old version.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49763334

http://stackoverflow.com/q/49815346
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86645000
has comment: http://stackoverflow.com/comment/86644910
tagged with: python
has title: LabelEncoder won't encode strings?
has body: I'm trying to encode the non-numeric columns of a pandas df to numeric values. I'm using df = df.fillna('0') msk = np.random.rand(len(df)) &lt; 0.8 df_train = df[msk] df_test = df[~msk] columns_to_encode = df.select_dtypes(exclude=[np.number]).columns encoder_dict = {col: LabelEncoder() for col in columns_to_encode } df_train_enc = df_train df_test_enc = df_test for col in columns_to_encode: encoder_dict[col].fit_transform(df_train_enc[col]) This, however, throws an error TypeError: '&lt;' not supported between instances of 'str' and 'float'. What am I missing here? I thought LabelEncoder should be able to transform strings to numerics...
accepted answer: http://stackoverflow.com/a/49815425
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/43956705
has answer: http://stackoverflow.com/a/49815425
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/59798644
upvote count: 1
tagged with: scikit-learn
downvote count: 1

http://stackoverflow.com/q/49859441
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49861501
tagged with: django
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/49860107
score: 0
answer count: 2
has body: I am trying to submit values via ajax to django backend,but I'm keep getting this error Advice matching query does not exist , But it does exist in the database. I dont know what I am doing wrong. Here is my code snippet for AJAX Request: $.ajax({ type: 'POST', url: '{% url "recsystem:saveData" %}', data: { 'csrfmiddlewaretoken' : "{{ csrf_token }}", 'ansId' : data.ansId, 'queTitle': data.queTitle, 'queText' : data.queText, 'desc': data.desc, 'optionType': data.optionType, 'anstextArray': data.anstextArray, 'ansAdvicesArray': data.ansAdvicesArray }, success: function(data){ console.log(data); }, error: function(error){ console.log(error); } }); Here is my function in Django view to save this data. def saveData(request): if request.method =='POST' and request.is_ajax(): q = Question() q.question_title = request.POST['queTitle'] q.question_text = request.POST['queText'] q.description = request.POST['desc'] q.options_type = request.POST['optionType'] q.save() if not request.POST['ansId'] is None: followup = FollowUp() followup.description = "" followup.answer = Answer.objects.get(pk=request.POST['ansId']) followup.question = q followup.save() if not request.POST.get('anstextArray', False) is None: answers = [] advices = [] answers = request.POST.get('anstextArray', False) advices = request.POST.get('ansAdvicesArray', False) for an, ad in zip(itertools.repeat(answers), itertools.repeat(advices)): adviceList = [] adviceList = ad answer = Answer() answer.question = q answer.answer_text = an for id in itertools.repeat(adviceList): answer.advice = Advice.objects.get(pk=id) answer.save() return JsonResponse({'result':'ok'}) else: return JsonResponse({'result':'nok'}) Here is my Database model: class Question(models.Model): question_title = models.CharField(max_length = 250) question_text = models.TextField(max_length = 3000) description = models.TextField(max_length = 3000) options_type = models.CharField(max_length = 250) def __str__(self): return self.question_title class …
has title: Django POST request Via ajax?
tagged with: django-forms
type: Question
tagged with: ajax
has comment: http://stackoverflow.com/comment/86734744

mypy
tags question: http://stackoverflow.com/q/49862318
tags question: http://stackoverflow.com/q/49869848
tags question: http://stackoverflow.com/q/49795830
tags question: http://stackoverflow.com/q/49888155
type: Tag
tags question: http://stackoverflow.com/q/49886726
tags question: http://stackoverflow.com/q/49774397
tag name: mypy
tags question: http://stackoverflow.com/q/49908265

http://stackoverflow.com/comment/86621942
has text: Well python can work with them
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49803673
score: 0

http://stackoverflow.com/q/49774446
type: UnansweredQuestion
answer count: 1
has title: Attribute Error in PyDev
has answer: http://stackoverflow.com/a/49774732
type: Question
has body: Recently installed PyDev for Eclipse Oxygen 3 on WIndows 10. As a new programmer I am writing basic programs as I work through a "learn to code" book. The example I am working on uses a module called "snaps", which is in "pygame". The program below works fine in the Python Shell IDE. import snaps temp = snaps.get_weather_temp(latitude=47.61, longitude=-122.33) print('The temperature in Seattle is:', temp) Output: The temperature in Seattle is: 60 But when I run this in PyDev I get: Traceback (most recent call last): File "C:\Users\mando\eclipse- workspace\BeginToCodeWithPython\Chapter4\ActualTemp.py", line 9, in &lt;module&gt; temp = snaps.get_weather_temp(latitude=47.61, longitude=-122.33) AttributeError: module 'snaps' has no attribute 'get_weather_temp' I've confirmed the Python Path is set correctly in windows and the PyDev Interpreter is set correctly as well. I've added every lib, script folder etc. I can under project and perspective preferences. I've even added the pygame folder to my workspace. But I still am getting the errors. I've confirmed that "get_weather_temp" is in the snaps module via the help() function, and it works in the IDE, just not in PyDev. Any assistance would be appreciated.
tagged with: python
score: 0
linked to: http://stackoverflow.com/q/4524973
tagged with: pydev

http://stackoverflow.com/comment/86840863
type: Comment
has text: I am using python 3.7 and pip 2.7.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49911823

http://stackoverflow.com/comment/86617563
score: 0
has text: I finally used alns = pairwise2.align.globalds(prot1 , prot2, matrix, gap_open, gap_extend) and now it work thanks you
comment on: http://stackoverflow.com/q/49797171
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86589882
has text: Using `src` attribute pointing to complete URI (as shown here - https://stackoverflow.com/a/31905972/919480) helped. Thanks!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49783892
score: 1

http://stackoverflow.com/q/49871342
type: Question
tagged with: python
score: 4
has body: I'd like to make UI that's basically an image that a user can trace out a path on with points connected by lines. I'd like it to be cross platform so I'm considering trying out enaml. I'm not sure how to accomplish this though. I've looked through the documentation and examples and I can't find anything like a canvas widget. Is it possible to do arbitrary drawing (points, lines, etc) on a surface with enaml?
upvote count: 4
type: AnsweredQuestion
has title: Is there a drawing/canvas widget in enaml?
tagged with: enaml
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/50381668
has answer: http://stackoverflow.com/a/50381668
favorite count: 0

http://stackoverflow.com/a/49882772
has body: Adding the argument positive = True to the symbols function mitigates this issue. α, t, x = symbols('α t x', positive = True) func = integrate(α*x*exp(-α*x), (x, 0, t), conds='none') (limit(func, t, oo)) Yielding 1/α
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/49880817
type: Answer
accepted answer of: http://stackoverflow.com/q/49880817

http://stackoverflow.com/comment/86565629
comment on: http://stackoverflow.com/a/49775218
score: 0
type: AnswerComment
has text: @Ricardo I've opened an issue, let's see what the devs say.
type: Comment

http://stackoverflow.com/comment/86576948
type: Comment
has text: @ErikCederstrand Fixed - the indentation issues aren't in my original code, they were introduced by copy-paste. I thought you only need to use super() when your class is inheriting from multiple other classes?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49779647

http://stackoverflow.com/a/58784658
upvote count: 2
has comment: http://stackoverflow.com/comment/103852831
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49889404
has body: So after I did conda install -c conda-forge fbprophet I got at the end: EnvironmentNotWritableError: The current user does not have write permissions to the target environment. environment location: C:\ProgramData\Anaconda3 ProgramData is system folder, so changed r-w permissions(took few minutes), and I also did this for C:\Program Files\Python37 path with Lib folder.
has comment: http://stackoverflow.com/comment/103852574

http://stackoverflow.com/q/49809095
has title: Installing NETCDF4 in windows using python 3.4
has answer: http://stackoverflow.com/a/64919054
tagged with: python-2.7
tagged with: netcdf4
score: 0
answer count: 2
has body: I have downloaded NETCDF4 module from https://pypi.python.org/pypi/netCDF4 e.g. netCDF4-1.3.1-cp34-cp34m-win_amd64.whl I have installed it using pip install netCDF4-1.3.1-cp34-cp34m-win_amd64.whl through command prompt in spyder. It has successfully installed. But when I am trying to import, it is giving an error: import netCDF4 as nc4 Traceback (most recent call last): File "", line 1, in import netCDF4 as nc4 File "C:\python3\WinPython-64bit-3.4.4.5Qt5\python-3.4.4.amd64\lib\site-packages\netCDF4__init__.py", line 3, in from ._netCDF4 import * File "netCDF4_netCDF4.pyx", line 2988, in init netCDF4._netCDF4 AttributeError: type object 'netCDF4._netCDF4.Dimension' has no attribute 'reduce_cython' How can I fix it? Suggestions would be appreciated.
has answer: http://stackoverflow.com/a/49810421
type: Question
tagged with: numpy
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49906335
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49907364
answer count: 3
has comment: http://stackoverflow.com/comment/86829289
has title: Find the maximum values of a column in multiindex dataframe and return all its values
upvote count: 6
accepted answer: http://stackoverflow.com/a/49906814
tagged with: python
has answer: http://stackoverflow.com/a/49907061
tagged with: multi-index
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86828656
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49907364
has answer: http://stackoverflow.com/a/49906814
score: 6
has comment: http://stackoverflow.com/comment/86828487
favorite count: 0
has body: Reproducible code for the dataset: df = {'player' : ['a','a','a','a','a','a','a','a','a','b','b','b','b','b','b','b','b','b','c','c','c','c','c','c','c','c','c'], 'week' : ['1','1','1','2','2','2','3','3','3','1','1','1','2','2','2','3','3','3','1','1','1','2','2','2','3','3','3'], 'category': ['RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH','RES','VIT','MATCH'], 'energy' : [75,54,87,65,24,82,65,42,35,25,45,87,98,54,82,75,54,87,65,24,82,65,42,35,25,45,98] } df = pd.DataFrame(data= df) df = df'player', 'week', 'category','energy' I need to find "For each player, Find the week where his energy was maximum and display all the categories, energy values for that week" So what I did was: 1.Set Player and Week as Index 2.Iterate over the index to find the max value of energy and return its value df = df.set_index(['player', 'week']) for index, row in df1.iterrows(): group = df1.ix[df1['energy'].idxmax()] Output Obtained: category energy player week b 2 RES 98 2 VIT 54 2 MATCH 82 This obtained output is for the maximum energy in the entire dataset, I would want the maximum for each player with the all other categories and its energy for that week. Expected Output: I have tried using groupby method as suggested in the comments, df.groupby(['player','week'])['energy'].max().groupby(level=['player','week']) The output obtained is: energy category player week a 1 87 VIT 2 82 VIT 3 65 VIT b 1 87 VIT 2 98 VIT 3 87 VIT c 1 82 VIT 2 65 VIT 3 98 VIT

http://stackoverflow.com/comment/86703068
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49842970
has text: Possible duplicate of ["SyntaxError: unexpected EOF while parsing" on simple python print() method](https://stackoverflow.com/questions/10313742/syntaxerror-unexpected-eof-while-parsing-on-simple-python-print-method)

http://stackoverflow.com/q/49833920
has comment: http://stackoverflow.com/comment/86684917
answer count: 0
tagged with: vba
has title: How to auto update a read-only workbook/sheet, only when the original file is updated?
has comment: http://stackoverflow.com/comment/86683525
tagged with: excel
type: Question
has body: Hi I am a newbie to programming. I am currently learning python. We have a excel spreadsheet that is on a network drive that is updated from time to time by any of our users. A copy of the spreadsheet is open as read only and displayed on a big screen for everyone to see. I want the read only spreadsheet to auto update itself anytime anyone makes changes to original copy. I have try to do this as a macro but i find it very limiting and of course I am a newbie so my knowledge is limited. I am currently learning python and I find they have the libraries that can make this happen. Can anyone please give me some pointers to lead me on the right track? I am thinking I will need to poll the original file to see if it was modified. And if it is, find a way to refresh the read only copy if that is possible, or worst case just close and reopen the spreadsheet. Another way perhaps is to extract the worksheet from the original file (including the formatting) and display it on a webpage. And of course I am open to any macro vb solutions if anyone has them. Thanks in advance.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86683285
tagged with: python
score: 0

http://stackoverflow.com/a/49782929
score: 9
accepted answer of: http://stackoverflow.com/q/49782852
upvote count: 9
has comment: http://stackoverflow.com/comment/86581119
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49782852
type: Answer
has body: You could create an object that basically maintains the state after each step and use pickle to serialize that object to a file. Then it's up to your python script to unpickle that file and then decide which step it needs to start from based on the state. https://wiki.python.org/moin/UsingPickle

http://stackoverflow.com/q/49869898
score: 0
has answer: http://stackoverflow.com/a/49871029
has title: Rarfile python module keeps throwing an error when trying to extract contents from a *.rar file
answer count: 1
has comment: http://stackoverflow.com/comment/86755881
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86755015
upvote count: 1
tagged with: python
has body: So im trying to simply extract the contents of a rar file into another location- import rarfile epath='C:\\Users\\sidharth.m\\Desktop\\Rar\\xyz.rar' def unrar(file): rf = rarfile.RarFile(file) rf.extractall() unrar(epath) But im getting the following error - Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\rarfile.py", line 2816, in custom_popen raise RarCannotExec("Unrar not installed? (rarfile.UNRAR_TOOL=%r)" % UNRAR_TOOL) rarfile.RarCannotExec: Unrar not installed? (rarfile.UNRAR_TOOL='unrar') Ive already tried adding and installing the rarfile and unrar packages through anaconda prompt and cmd, ive also added their respective paths into the environmental path variables and if that wasnt enough i even imported them into the project folder. Any idea why this problem could be happening?
accepted answer: http://stackoverflow.com/a/49871029
type: AnsweredQuestion

http://stackoverflow.com/comment/86554395
comment on: http://stackoverflow.com/q/49765956
score: 0
type: Comment
type: QuestionComment
has text: I Struggled with your code for more then a hour but until didn't solve the problem.

marker
tag name: marker
tags question: http://stackoverflow.com/q/49791084
type: Tag

http://stackoverflow.com/a/49911723
score: 2
has body: This code will iterate through the lines of the file and print any line with "April" in it. When you are iterating through the lines of a file, you do not need to call next() in the loop body. for line in open("fruits.txt"): if "April" in line: print(line)
answers question: http://stackoverflow.com/q/49911588
type: Answer
has comment: http://stackoverflow.com/comment/86839320
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/52532191
accepted answer of: http://stackoverflow.com/q/49915894
has comment: http://stackoverflow.com/comment/114048900
has comment: http://stackoverflow.com/comment/94043206
upvote count: 3
answers question: http://stackoverflow.com/q/49915894
downvote count: 0
has comment: http://stackoverflow.com/comment/114135295
has comment: http://stackoverflow.com/comment/114142618
has body: Is this what you mean by border points of a contour? The white lines you see are points that I have marked out in white against the blue drawn contours. There's a little spot at the bottom right because I think its most likely that your black background isn't really black and so when I did thresholding and a floodfill to get this, there was a tiny white speck at the same spot. But if you play around with the parameters and do a more proper thresholding and floodfill it shouldn't be an issue. In openCV's drawContours function, the cnts would contain lists of contours and each contour will contain an array of points. Each point is also of type numpy.ndarray. If you want to place all points of each contour in one place so it returns you a set of points of boundary points (like the white dots outline in the image above), you might want to append them all into a list. You can try this: #rgb is brg instead contoured=cv2.drawContours(black, cnts, -1, (255,0,0), 3) #list of ALL points of ALL contours all_pixels=[] for i in range(0, len(cnts)): for j in range(0,len(cnts[i])): all_pixels.append(cnts[i][j]) When I tried to print(len(all_pixels)) it returned me 2139 points. Do this if you want to mark out the points for visualization purposes (e.g. like my white points): #contouredC is a copy of the contoured image above contouredC[x_val, y_val]=[255,255,255] If you want less points, just use a step function when iterating through to draw the white points out. Something like this: In python, for loops are slow so I think there's better ways of replacing the nested for loops with a np.where() function or something instead. Will update this if/when I figure it out. Also, this needs better thresholding and binarization techniques. Floodfill technique referenced from: Python 2.7: Area opening and closing binary image in Python not so accurate. Hope it helps.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/114087044
score: 3
has comment: http://stackoverflow.com/comment/94986858
has comment: http://stackoverflow.com/comment/94986899
type: Answer

http://stackoverflow.com/comment/86752104
type: Comment
type: AnswerComment
has text: It's not clear to me on what you are actually trying to do. Is there another example you can provide?
score: 0
comment on: http://stackoverflow.com/a/49867661

http://stackoverflow.com/q/49870991
has comment: http://stackoverflow.com/comment/86757906
has comment: http://stackoverflow.com/comment/86765464
has answer: http://stackoverflow.com/a/51315479
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/86765545
upvote count: 6
tagged with: excel
has comment: http://stackoverflow.com/comment/86765622
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86765515
accepted answer: http://stackoverflow.com/a/51315479
tagged with: pandas
has comment: http://stackoverflow.com/comment/86758444
has body: I have a long-running python pipeline that generates a pandas dataframe. Briefly, I want to: Display the pandas dataframe in excel Add &amp; run VBA macro Remove VBA macro and save the (newly formatted) output as .xslx The challenge is that I can't figure out how to do this without an intermediate save-as-xlsm-file step, which is apparently required when adding a VBA macro to an .xlsx file. Since this is inefficient, I want to get rid of this intermediate step. Here is the code: 1. Display the pandas dataframe in excel: with pd.ExcelWriter('output.xlsx') as writer: df_results.to_excel(writer, index = False, sheet_name = "Sheet1") #...see below 2A. Add macro and assign .xlsm-filename so that writer can hold macro #... see above writer.book.filename = 'output.xlsm' # Add .xlsm filename writer.book.add_vba_project('VBA_script.bin') # This adds my macro writer.save() # How to get rid of this step? 2B. Run macro xl = win32com.client.Dispatch("Excel.Application") # Set up excel xl.Workbooks.Open(Filename = 'output.xlsm') # Open .xlsm file from step 2A xl.Application.Run("Module1.Main") # Run VBA_macro.bin 3. Remove macro and save to .xlsx wb = xl.ActiveWorkbook xl.DisplayAlerts = False wb.DoNotPromptForConvert = True wb.CheckCompatibility = False wb.SaveAs('final_outfile.xlsx', FileFormat=51, ConflictResolution=2) # Macro disapears here xl.Application.Quit() del xl xl = None Is it possible to do this without intermediate .xlsm step &amp; with shorter code? How to add, run &amp; remove a VBA macro in an excel context without intermediate saving steps using python?
answer count: 1
has title: Can python add, run & remove a VBA macro to excel without intermediate saving steps?
downvote count: 0
tagged with: vba
favorite count: 0
type: Question

http://stackoverflow.com/a/49917265
type: Answer
has body: Take care of string and the approach you choose to reach expected task. You may go with searching for: "(?&lt;![[ :]u.)(?=[a-zA-Z\d]) and replacing with '. Live demo If you consider _ as a word character above regex could be shorter: "(?&lt;![[ :]u.)(?=\w) Breakdown: " Match a double quotation mark (?&lt;![[ :]u.) That's not preceded by delimiters :, space or [ (?=\w) And is followed by a word character Python code: re.sub(r'"(?&lt;![[ :]u.)(?=\w)', "'", my_string)
upvote count: 1
answers question: http://stackoverflow.com/q/49916694
downvote count: 0
score: 1

http://stackoverflow.com/comment/86740341
score: 0
has text: Sure! I know the feeling when one finds out about a new function that does _exactly_ what one needs! :D
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49862579

http://stackoverflow.com/q/49806443
accepted answer: http://stackoverflow.com/a/49815967
has title: Video Intelligence API - Label Segment time
favorite count: 0
type: Question
tagged with: video-intelligence-api
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49815967
type: AnsweredQuestion
tagged with: google-cloud-platform
score: 1
has body: I am following this LABEL DETECTION TUTORIAL. The code below does the following(after getting the response back) Our response will contain result within an AnnotateVideoResponse, which consists of a list of annotationResults, one for each video sent in the request. Because we sent only one video in the request, we take the first segmentLabelAnnotations of the results. We then loop through all the labels in segmentLabelAnnotations. For the purpose of this tutorial, we only display video-level annotations. To identify video-level annotations, we pull segment_label_annotations data from the results. Each segment label annotation includes a description (segment_label.description), a list of entity categories (category_entity.description) and where they occur in segments by start and end time offsets from the beginning of the video. segment_labels = result.annotation_results[0].segment_label_annotations for i, segment_label in enumerate(segment_labels): print('Video label description: {}'.format( segment_label.entity.description)) for category_entity in segment_label.category_entities: print('\tLabel category description: {}'.format( category_entity.description)) for i, segment in enumerate(segment_label.segments): start_time = (segment.segment.start_time_offset.seconds + segment.segment.start_time_offset.nanos / 1e9) end_time = (segment.segment.end_time_offset.seconds + segment.segment.end_time_offset.nanos / 1e9) positions = '{}s to {}s'.format(start_time, end_time) confidence = segment.confidence print('\tSegment {}: {}'.format(i, positions)) print('\tConfidence: {}'.format(confidence)) print('\n') So, it says "Each segment label annotation includes a description (segment_label.description), a list of entity categories (category_entity.description) and where they occur in segments by start and end time offsets from the beginning of the video." But, in the output, all the labels urban area, traffic, vehicle.. have the same start and end time offsets which are basically…
answer count: 1
downvote count: 0

http://stackoverflow.com/a/49860808
has body: There are use cases for having a local function - either in a class method or other method, say if you want a closure capturing something local. In you case you want something like a colasecing null: e.g. &gt;&gt;&gt; s = None &gt;&gt;&gt; s or "None" 'None' So, you can use item['latitude'] = response.xpath('//input[@id="latitude"]@value').extract_first() or "null"
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49860649

http://stackoverflow.com/comment/86772280
score: 0
type: AnswerComment
has text: Thank you for your answer, but could you further explain how can I use 1 convolution per sensor? I understand the input should be `(100, 1)` but how could I model it? Replicating this model 4 times or how. Sorry, I am a little bit confused...
comment on: http://stackoverflow.com/a/49877684
type: Comment

http://stackoverflow.com/comment/86638259
has text: you can read complete files and can split by `set`.
type: QuestionComment
comment on: http://stackoverflow.com/q/49811842
type: Comment
score: 0

http://stackoverflow.com/q/49893766
duplicate of: http://stackoverflow.com/q/48944267
has title: Python boolean comparison and is
upvote count: 3
linked to: http://stackoverflow.com/q/6074018
answer count: 1
accepted answer: http://stackoverflow.com/a/49893832
has comment: http://stackoverflow.com/comment/86803016
has comment: http://stackoverflow.com/comment/86803204
has answer: http://stackoverflow.com/a/49893832
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/6074018
downvote count: 0
tagged with: python
has body: Python 3.6.2 console: &gt;&gt;&gt; 11 &gt; 0 is True False but &gt;&gt;&gt; 0 is True False &gt;&gt;&gt; 11 &gt; False True So, why 11 &gt; 0 is True is False?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86803067
score: 3
tagged with: boolean
has comment: http://stackoverflow.com/comment/86803272
has comment: http://stackoverflow.com/comment/86803352

http://stackoverflow.com/q/49906351
type: Question
tagged with: numpy
has body: I've been exploring HDF5 and its python interface (h5py) so I tried to read a HDF5 file (one dimensional array of 100 million integers) into: a normal list and another time to a numpy array. Converting the dataset to a numpy was very fast comparing to when I tried to convert it to a normal python list (actually doing it with a list took a very long time that I had to kill it before it finished). Can any one help me understand what happens internally that makes converting HDF5 dataset to a numpy array extremely faster than doing it with a normal list? Does it has to do with h5py compatibility with numpy? import numpy as np import hdf5 def readtolist(dataset): return "normal list count = {0}".format(len(list(dataset['1']))) def readtonp(dataset): n1 = np.array(dataset) return "numpy count = {0}".format(len(n1)) f = h5py.File(path, 'r') readtolist(f['1']) readtonp(f['1']) Thanks for the help!
tagged with: h5py
accepted answer: http://stackoverflow.com/a/49907197
has answer: http://stackoverflow.com/a/49907197
tagged with: python
has answer: http://stackoverflow.com/a/49907573
type: AnsweredQuestion
tagged with: list
answer count: 3
score: 1
possible better answer: http://stackoverflow.com/a/49906578
downvote count: 0
tagged with: hdf5
has title: Python - Reading HDF5 dataset into a list vs numpy array
upvote count: 1
has answer: http://stackoverflow.com/a/49906578
favorite count: 0

http://stackoverflow.com/q/49791279
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/49795070
tagged with: pandas
has body: i used this example to get started with pandas: http://pandas-xlsxwriter-charts.readthedocs.io/chart_grouped_column.html#chart-grouped-column i also want to save the chart in excel just like in the example i would like to know how e.g. in the example above i can add a description or a table under the graph chart the only thing related i found was this : Add graph description under graph in pylab but this is done with pylab, is the same possible with pandas and an excel chart?
has answer: http://stackoverflow.com/a/49795070
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11143619
score: 1
upvote count: 1
favorite count: 0
has title: Insert description under graph in pandas
tagged with: graph
tagged with: charts
type: Question
downvote count: 0

http://stackoverflow.com/q/49771746
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86559912
downvote count: 0
has body: I have a 2D numpy Array filled with integer-values from 0 to N, how can i get the indices of all entries that are directly connected and share the same value. Addition: Most of the entries are zero and can be ignored! Example Input array: [ 0 0 0 0 0 ] [ 1 1 0 1 1 ] [ 0 1 0 1 1 ] [ 1 0 0 0 0 ] [ 2 2 2 2 2 ] Wished output indices: 1: [ [1 0] [1 1] [2 1] [3 0] ] # first 1 cluster [ [1 3] [1 4] [2 3] [2 4] ] # second 1 cluster 2: [ [4 0] [4 1] [4 2] [4 3] [4 4] ] # only 2 cluster the formating of the output arrays is not important, i just need separated value clusters where it is possible to address the single indices What i was first thinking of is: N = numberClusters x = myArray for c in range(N): for i in np.where(x==c): # fill output array with i but this misses the separation of clusters that have the same value
answer count: 1
has comment: http://stackoverflow.com/comment/86559772
has comment: http://stackoverflow.com/comment/86559488
accepted answer: http://stackoverflow.com/a/49772535
favorite count: 0
type: Question
tagged with: numpy
tagged with: arrays
tagged with: python
has title: numpy 2D array: get indices of all entries that are connected and share the same value
has answer: http://stackoverflow.com/a/49772535
tagged with: indices

http://stackoverflow.com/a/49864717
has body: From my understanding of your question you would like something like this: Note how the sequence is build over multiple iteration steps of the loop, as you wish to combine multiple lines. with open(ref) as f: sequence = "" # reset sequence header = None for line in f: if line.startswith('&gt;'): if header: print(header) # print last header print(len(sequence)) # print last sequence sequence = "" # reset sequence header = line[1:] # store header else: sequence += line.rstrip() # append line to sequence
downvote count: 0
has comment: http://stackoverflow.com/comment/86745325
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49864385

http://stackoverflow.com/q/49889524
linked to: http://stackoverflow.com/q/47770473
tagged with: importerror
has answer: http://stackoverflow.com/a/56408318
answer count: 5
score: 10
tagged with: python
has answer: http://stackoverflow.com/a/67383100
has comment: http://stackoverflow.com/comment/86795846
upvote count: 10
tagged with: mlxtend
has answer: http://stackoverflow.com/a/58758122
tagged with: python-import
type: UnansweredQuestion
has body: I'm new to python, so apologies if this is a silly question. I'm trying to use mlxtend, and have installed it using pip. Pip confirms that it is installed (when I type "pip install mlxtend" it notes that the requirement is already satisfied). However, when I try and import mlxtend in python using "import mlxtend as ml", I get the error: "ModuleNotFoundError: No module named 'mlxtend'". I used the same process for installing and importing pandas and numpy, and they both worked. Any advice? I should note that I have resorted to dropping in the specific code I need from mlxtend (apriori and association rules), which is working, but hardly a good long term strategy! I'm using python version 3.6.5. Thanks!
has title: Issues importing mlxtend python
has comment: http://stackoverflow.com/comment/86795122
downvote count: 0
has answer: http://stackoverflow.com/a/54057894
has answer: http://stackoverflow.com/a/64196727
has comment: http://stackoverflow.com/comment/86795871
favorite count: 0
has comment: http://stackoverflow.com/comment/86795649
type: Question

http://stackoverflow.com/q/49813126
has title: Networkx: Inverted index on node attributes
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49815818
answer count: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/86640782
downvote count: 0
has comment: http://stackoverflow.com/comment/86641285
has comment: http://stackoverflow.com/comment/86645520
possible better answer: http://stackoverflow.com/a/49815818
favorite count: 0
tagged with: networkx
type: Question
has body: I have a graph like the following: P=nx.Graph() P.add_node('node1',at=5) P.add_node('node2',at=5) P.add_node('node3',at=6) I would like to access all nodes with at=5, without having to run across all nodes (so without list comprehension or for). IE, I would like an inverted index on attribute values. I could add a dictionary, and fill it every time I create a new node (that's currently how I solve this problem) but I am wondering if there is a less artisanal and error-prone (and more efficient) way to do this at_dict = collections.defaultdict(set) at_dict[5].add('node1') at_dict[5].add('node2') at_dict[6].add('node3') Note that I need to use a graph because I have to do some clustering on the nodes (so I cannot completely change my data structure)
accepted answer: http://stackoverflow.com/a/49816420
tagged with: python
has answer: http://stackoverflow.com/a/49816420

http://stackoverflow.com/comment/86653369
type: QuestionComment
comment on: http://stackoverflow.com/q/49818553
score: 0
has text: Thank you. But `['mypackage/vendor/dependencies/StreamingDataReader.zip']` is still a pattern
type: Comment

http://stackoverflow.com/comment/86552438
comment on: http://stackoverflow.com/q/49768523
has text: I want to trigger another method when selected string positions are equal to specific values.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/86824381
has text: Thanks, that was it. My structure was 12 bytes instead of the padded 16 bytes that the C code was using.
type: Comment
comment on: http://stackoverflow.com/a/49903502
score: 0
type: AnswerComment

http://stackoverflow.com/q/49885117
type: UnansweredQuestion
downvote count: 0
favorite count: 0
has body: I am a noob when it comes to Python but definitely want to learn more. My project essentially entails importing a column from CSV1 and then using get_close_matches to compare it to the Master column in CSV2 and output anything that is greater than .6 to a new column in CSV1. Everything I have read regarding difflib.get_close matches leads me to believe that I have to specify my string inside the code itself. Here is what I have written so far but it is far from perfect and before I keep going, I figured I might as well figure out if it is even possible. Any help would be appreciated! https://pastebin.com/8v1hvMbP import sys import csv import difflib infile = open(sys.argv[1], "rb") reader = csv.reader(infile) infile2 = open(CSV2.csv, "rb") reader2 = csv.reader(infile2) diff = difflib.get_close_matches(open(infile).readlines(),open(infile2).readlines()) best_match = difflib.get_close_matches(my_str,str_list,1)[0] score = difflib.SequenceMatcher(None, my_str, best_match).ratio() for word in str_list: print "score for: " + my_str + " vs. " + word + " = " + str(difflib.SequenceMatcher(None, my_str, word).ratio()) infile.close() infile2.close() EDIT:I am doing it with pandas now as it seems a lot easier. I have succesfully imported certain columns into my script and I am now trying to run get_close_matches to compare one column to the other. I get the following error: IndexError: list index out of range. Here is my new code: import sys import csv import difflib import pandas as pd df = pd.read_csv(sys.argv[1]) OrgID = df.OrganizationID MappedID = df.MappedID best_match = difflib.get_close_matches(OrgID, MappedID, 1)[0] score = difflib.SequenceMatcher(None, OrgID, best_match).ratio() for word in MappedID: print "score for: " + OrgID + " vs. " + word + " = " + str(difflib.SequenceMatcher(None, OrgID, word).ratio())
tagged with: difflib
tagged with: python
type: Question
has title: Using imported CSV column as string in difflib.get_close_matches
score: 2
answer count: 0
upvote count: 2

http://stackoverflow.com/comment/91861918
type: Comment
has text: @mgrollins always :)
comment on: http://stackoverflow.com/a/49894338
type: AnswerComment
score: 4

http://stackoverflow.com/comment/86764870
comment on: http://stackoverflow.com/q/49874711
type: Comment
type: QuestionComment
has text: Line 6 `ptint` should be `print`!
score: 0

python-curses
tag name: python-curses
type: Tag
tags question: http://stackoverflow.com/q/49806102

http://stackoverflow.com/comment/86833385
has text: @eagle, I tried the parallel command also, but still slower.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49908444

http://stackoverflow.com/a/49858825
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/49858037
has body: Here is an example when you want to use both Pandas and SQL Alchemy: Imagine that you need to update a DB table (let's say it has 100.000.000 rows and doesn't fit in memory) from the DataFrame (that has 100.000 rows). I.e. there is a column ID in your DF and you want to update a column in the DB table for those ID's using data from the DF. In this case you can dump your DF into a DB as a table and execute UPDATE ... statement using SQL Alchemy. Here is a small demo: df.to_sql('tmp', conn, if_exists='replace') sql = """ UPDATE table_name set last_seen = (SELECT t.last_seen FROM tmp t WHERE t.id = table_name.id) WHERE EXISTS( SELECT * FROM tmp WHERE tmp.id = table_name.id ) """ cursor.execute(sql)
score: 5
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49858037

http://stackoverflow.com/comment/86789047
has text: show your urls please
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49886388
score: 0

http://stackoverflow.com/comment/86559934
score: 0
comment on: http://stackoverflow.com/q/49770885
has text: Do you know why the vowels and constants wont work. they keep outputting 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49805020
has comment: http://stackoverflow.com/comment/86624866
has comment: http://stackoverflow.com/comment/86625078
answers question: http://stackoverflow.com/q/49804744
has body: If your programs don't require a large amount of processing power, I'd go with a bootable copy of Linux on a USB stick. Note that unless you make the memory persistent (see link) then every time you boot the usb it will start without any of your programs installed and you would have to install them again. In my experience, getting your computer to dual-boot just so you can work on Linux for a few weeks is not a good idea because once you partition the hard drive and do you work, the computer stays partitioned unless you go through the work of undoing the partition which is a pain. Try reading this: https://www.howtogeek.com/howto/14912/create-a-persistent-bootable-ubuntu-usb-flash-drive/
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/86627029
type: QuestionComment
has text: I'm still not clear what you're asking about. Is your goal to learn how to do layout (which is related to the use of pack, place, or grid) or is your goal to learn how to run a function "constantly"?
type: Comment
comment on: http://stackoverflow.com/q/49805389
score: 1

http://stackoverflow.com/comment/86926915
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49775125
type: AnswerComment
has text: I have edited my original answer the section named Note2

http://stackoverflow.com/q/49887526
has title: Rescaling quiver arrows in physical units consistent to the aspect ratio of the axes
has answer: http://stackoverflow.com/a/49891134
score: 9
type: AnsweredQuestion
has body: I've been spending the past couple of hours trying to customize matplotlib.quiver without much luck. The documentation is quite confusing and I haven't been able to parse out how to set each parameter. In my axes, one vertical pixel is much less physical distance than one horizontal pixel, and I want quiver to autoscale the arrows to this aspect ratio. What I'm currently getting are horizontal arrows with the following code: Tlevs = np.arange(-1.,8.5,.5) + 0. yy, zz = np.meshgrid(ds.YC, ds.Z) fig, ax = plt.subplots(figsize=(8,5)) fig.set_tight_layout(True) im = ax.contourf(T_clim.YC, T_clim.Z, T_clim, levels=Tlevs) ax.quiver(yy[::3,::10], zz[::3,::10], vpFep_b[::3,::10], wpFep_b[::3,::10], pivot='mid', angles='xy', units='xy') ax.set_xlabel('Y [m]', fontsize=13) ax.set_ylabel('Depth [m]', fontsize=13) cbar = fig.colorbar(im, ax=ax) cbar.set_label(r"[$^\circ$C]") Setting the quiver options to the following only gives dots for what the arrows should be: ax.quiver(yy[::3,::10], zz[::3,::10], vpFep_b[::3,::10], wpFep_b[::3,::10], pivot='mid', angles='xy', scale_units='xy', scales=1.) and: ax.quiver(yy[::3,::10], zz[::3,::10], vpFep_b[::3,::10], wpFep_b[::3,::10], pivot='mid', angles='xy', scale_units='xy') gives the following error: /home/takaya/miniconda3/envs/uptodate/lib/python3.6/site-packages/matplotlib/quiver.py:666: RuntimeWarning: divide by zero encountered in double_scalars length = a * (widthu_per_lenu / (self.scale * self.width)) /home/takaya/miniconda3/envs/uptodate/lib/python3.6/site-packages/matplotlib/quiver.py:666: RuntimeWarning: invalid value encountered in multiply length = a * (widthu_per_lenu / (self.scale * self.width)) /home/takaya/miniconda3/envs/uptodate/lib/python3.6/site-packages/matplotlib/quiver.py:719: RuntimeWarning: invalid value encountered in less short = np.repeat(length &lt; minsh, 8, axis=1) /home/takaya/miniconda3/envs/uptodate/lib/python3.6/site-packages/matplotlib/quiver.py:733: RuntimeWarning: invalid value encountered in less to…
tagged with: vector
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86796708
upvote count: 9
has comment: http://stackoverflow.com/comment/86797440
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/49891134

http://stackoverflow.com/a/49889623
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49889130
has body: Consider the sample data cols = ['Cycle (seconds)', 'Run (seconds)', 'Swim (seconds)'] np.random.seed([3, 1415]) DataTD = pd.DataFrame( np.random.randint(10, size=(10, 3)), list('ABCDEFGHIJ'), cols ) Cycle (seconds) Run (seconds) Swim (seconds) A 0 2 7 B 3 8 7 C 0 6 8 D 6 0 2 E 0 4 9 F 7 3 2 G 4 3 3 H 6 7 7 I 4 5 3 J 7 5 9 IIUC: Use mean with argument axis=1 followed with an idxmax to find the index for the maximal value. DataTD.loc[[DataTD[cols].mean(1).idxmax()]] Cycle (seconds) Run (seconds) Swim (seconds) J 7 5 9 Otherwise, try means = DataTD.mean() meansmeans.idxmax() Swim (seconds) 5.7 dtype: float64
downvote count: 0
upvote count: 1

eval
tag name: eval
tags question: http://stackoverflow.com/q/49785181
type: Tag

http://stackoverflow.com/comment/86717717
type: QuestionComment
has text: I think it has to do with the fact that the function to maximize is itself unknown. Bayesian optimization is just probing the function at different points and exploring/exploiting the function to find the minima. Since you set `kappa=10`, your algorithm is good at exploring (I think). However, I don't have a good answer for you as to why it cannot find the global maxima. The only problem maybe is it finishes exploring before it finds the maxima.
score: 0
comment on: http://stackoverflow.com/q/49851333
type: Comment

http://stackoverflow.com/comment/86544133
type: QuestionComment
comment on: http://stackoverflow.com/q/49764199
has text: Ctrl-Shift-F10 activates the new file. Thanks Aran-Fey
score: 0
type: Comment

http://stackoverflow.com/comment/86546384
type: Comment
has text: haha I'm a high school student so that isn't an option :)
type: AnswerComment
comment on: http://stackoverflow.com/a/49765404
score: 0

http://stackoverflow.com/a/49817947
upvote count: 5
score: 5
type: Answer
has body: Here is one way using pandas.melt. d = {'1':{'a':10, 'b':30}, '2':{'a':20, 'b':60}} res = pd.melt(pd.DataFrame.from_dict(d, orient='index'), value_vars=['a', 'b'], var_name='y', value_name='z') print(res) # y z # 0 a 10 # 1 a 20 # 2 b 30 # 3 b 60 Performance benchmarking I expected pandas.melt to be inefficient, but applying pandas.concat on a large number of dictionaries can be even more expensive. data = {str(k): {'a': 10, 'b': 30} for k in range(10000)} def jp(data): return pd.melt(pd.DataFrame.from_dict(data, orient='index').reset_index().rename(columns={'index': 'x'}), id_vars=['x'], value_vars=['a', 'b'], var_name='y', value_name='z')\ .sort_values(['x', 'y']).reset_index(drop=True) def jez(data): df = pd.concat({k: pd.Series(v) for k, v in data.items()}).reset_index() df.columns = list('xyz') return df assert (jp(data).values == jez(data).values).all() %timeit jp(data) # 51.8 ms per loop %timeit jez(data) # 2.62 s per loop
downvote count: 0
answers question: http://stackoverflow.com/q/49817811

http://stackoverflow.com/comment/86735750
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49860184
has text: Yes, it does exist

http://stackoverflow.com/q/49802172
has comment: http://stackoverflow.com/comment/86618972
answer count: 1
has answer: http://stackoverflow.com/a/49802444
has body: I'm trying to make one plot with multiple y-axis with this example: https://matplotlib.org/faq/howto_faq-1.pdf Here is the link with the source code https://matplotlib.org/faq/howto_faq.html I'm a little dissatisfied about the alignment of the right y-axis. 1.00 0.50 0.00 -0.50 -1.00 Is it possible to change the alignment and get the numbers in line, like: 1.00 0.50 0.00 -0.50 -1.00 Is there any way to add leading spaces to tick marks?
type: Question
has comment: http://stackoverflow.com/comment/86619747
type: UnansweredQuestion
tagged with: matplotlib
linked to: http://stackoverflow.com/q/19219963
tagged with: python
linked to: http://stackoverflow.com/q/11244514
duplicate of: http://stackoverflow.com/q/19219963
has title: Matplotlib right y-axis numbers in line
score: 0

http://stackoverflow.com/comment/88309918
type: Comment
has text: The answer to this question is _wildly_ dependent on what it is you're trying to do. The moment you're forced to iterate over a DataFrame, you've lost all the reasons to use one. You may as well store a list and then use a for loop. Of course, the answer to this question is `pd.DataFrame((f(v) for v in s.tolist()), columns=['len', 'slice'])` and it works perfectly, but I don't think it is going to solve your actual problem. The answer to your real problem will depend on the problem.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49906526

http://stackoverflow.com/a/49863286
upvote count: 3
answers question: http://stackoverflow.com/q/49863212
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86755478
score: 3
has body: you can use string casting str(result1)

http://stackoverflow.com/q/49797941
favorite count: 0
type: Question
tagged with: serialization
accepted answer: http://stackoverflow.com/a/49798291
has answer: http://stackoverflow.com/a/49798291
tagged with: django
upvote count: 1
tagged with: python
tagged with: django-rest-framework
has body: In short, I want to have a global default serializer per model. My use case here is to create dynamic serializer- i.e creating ModelSerializer classes on the fly. class Customer(models.Model): name = models.CharField(max_length=200) code = models.CharField(max_length=200) # many more fields.. class CustomerTicket(models.Model): customer = models.ForeignKey(Customer) date = models.DateTimeField(auto_now_add=True) # more fields.. Customer will be referenced by many other models, and hence it will be serialized as a nested object. I don't want the 'code' field to appear in the output - no matter what it should always be excluded. Now I'd like to create a function: def serialize_default(model, fields, queryset): class S(serializers.ModelSerializer): class Meta: model = model fields = fields depth = 1 return S(queryset, many=True) if I serialize CustomerTicket queryset using this function, I will get all the customer fields as a nested object. I know I can override it locally, but I want to define a CustomerSerializer that will be used by default (for the nested Customer here) unless other serializer is specified as a field. How to achieve this?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86610848
has comment: http://stackoverflow.com/comment/86610693
score: 1
downvote count: 0
answer count: 1
has title: django rest framework - global default model serializer

http://stackoverflow.com/q/49840302
has body: I have a n*n correlation matrix in python dataframe. I want to assign cluster value based on this matrix, say( a correlation>0.08) goes into one cluster and so on: import pandas as pd import numpy as np # data # ============================== np.random.seed(0) df = pd.DataFrame(np.random.randn(100,5), columns=list('ABCDE')) df1=df.corr() A B C D E A 1 -0.052234579 -0.098678285 0.063338014 -0.097187103 B -0.052234579 1 -0.015077115 0.058672786 0.140833111 C -0.098678285 -0.105077115 1 0.008695575 0.048329744 D 0.063338014 0.058672786 0.008695575 1 0.120529455 E -0.097187103 0.140833111 0.048329744 0.120529455 1 d={} i=1 while df1.shape[0]&gt;0: x=(abs(df1.head(1))&gt;0.08).T x1=list(x[x[x.columns[0]]==True].index) d[i]=x1 df1=df1[~df1.index.isin(x1)][list(df1.columns-x1)] i+=1 d&gt;&gt; {1: ['A', 'C', 'E'], 2: ['B'], 3: ['D']} Now my challenge here is, say a variable has correlation value>0.08, but has stronger correlation with another variable which is not in current cluster, then ideally it should be in different cluster. e.g. 'E' has correlation of -0.09 with A so it is in cluster 1, but it has stronger correl(0.14) with B, so ideally, it should be in cluster 2. so Ideal cluster assignment would have been: {1: ['A', 'C'], 2: ['B','D','E']} How can i address this iterative problem?
upvote count: 0
tagged with: correlation
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/38070478
answer count: 1
downvote count: 1
favorite count: 0
tagged with: iteration
type: Question
has title: Assigning cluster values based on correlation matrix
has comment: http://stackoverflow.com/comment/86706904
tagged with: cluster-analysis
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49845596

http://stackoverflow.com/comment/86762130
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49868267
type: QuestionComment
has text: @ekhumoro I use Qt 4.8.7 and Qt 5.10.1

http://stackoverflow.com/comment/86763448
comment on: http://stackoverflow.com/q/49870499
score: 0
has text: @eyllanesc please check the update.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86735994
comment on: http://stackoverflow.com/q/49860162
has text: you want to remove the speaker identifiers and achieve a text file that only contains the spoken lines?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86832352
type: Comment
has text: Are you trying to find the total number, or get a list of all solutions?
type: QuestionComment
comment on: http://stackoverflow.com/q/49907285
score: 0

http://stackoverflow.com/q/49867434
tagged with: ipython
has comment: http://stackoverflow.com/comment/86750521
tagged with: python-2.7
answer count: 0
has title: deciphering "This could mean that an intermediate result is being cached" when profiling
tagged with: profiling
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86907409
linked to: http://stackoverflow.com/q/48733545
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86750493
has body: I got 2 functions which essentially do the same thing, and I want to compare their runtime performance. def calculate_bonus_by_table(data, value): cdf = data["cdf"] # CAUTION: the following loop doesn't do bound checking i = 0 while (value &gt; cdf[i]): i += 1 return data['bonus'][i] def calculate_bonus_by_regression(data, value): max_slope = len(data['bonus']) - 1 slope = int((value - 1) / 6) if slope &gt; max_slope: slope = max_slope slope += 1 return (0.205078125 * slope**2) + (0.68359375 * slope) - 70.888671875 data = json.load(open('bonus.json')) A snippet of the JSON file used above { "cdf": [6, 12, 18, 24, 30, 36, ...], "bonus": [-70, -68, -66, -64, -62, ...] } In iPython, I time both the function seperately %timeit calculate_bonus_by_table(data, 199) 1000000 loops, best of 3: 1.64 µs per loop %timeit calculate_bonus_by_regression(data, 199) The slowest run took 7.99 times longer than the fastest. This could mean that an intermediate result is being cached. 1000000 loops, best of 3: 604 ns per loop running timeit for both functions multiple times always gives me similar results. The .._by_regression function result always gives warning about caching. How can I compare the 2 if one is cached while the other isn't? Why the _by_regression function is cached while _by_table isn't? Will _by_regression performance and caching hold when used in production environment, or should I assume the worst performace (from above, 7.99 * 604ns = 4.83us)? Thanks
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/49916547
has comment: http://stackoverflow.com/comment/86853851
has comment: http://stackoverflow.com/comment/86849832
has comment: http://stackoverflow.com/comment/86852237
has comment: http://stackoverflow.com/comment/86851054
has comment: http://stackoverflow.com/comment/86849297
score: 0
answers question: http://stackoverflow.com/q/49916212
has comment: http://stackoverflow.com/comment/86849643
has body: Insert a while loop to repeat the calculations you require. When L &gt; R, Wo and Omo are updated with the Omn and Wn values. So if this values are Omn&lt;0 or Wn&gt;0 you need to re-calulate them. When L &lt;= R, Wo and Omo are calculated from the previous iteration. Since the previous iteration already is Wo[i]&lt;=0 and Omo[i]&gt;=0 you don't need to repeat those calculations. Thus, as shown in the code below, you only need to re-calculate the Omn and Wn variables: Omo[0] = 0.24 Wo[0] = -0.2 Mo[0] = 1.0 N = 101 for i in range (1,N): is_valid = False if __debug__: print "Calculating position " + str(i) while (not is_valid): Omn[i] = Omo[i-1] + 0.05 * np.random.normal() Wn[i] = Wo[i-1] + 0.05 * np.random.normal() Mn[i] = Mo[i-1] + 0.1 * np.random.normal() if __debug__: print "- is_valid iteration values: " + str(Wn[i]) + " " + str(Omn[i]) print "- is_valid previous values: " + str(Wo[i-1]) + " " + str(Omo[i-1]) is_valid = Omn[i] &gt;= 0 and Wn[i] &lt;= 0 R = np.random.uniform(0,1) L = exp(-0.5 * ( func(Omn[i], Wn[i], Mn[i] ) - func( Omo[i-1], Wo[i-1], Mo[i-1] ))) if L &gt; R: Omo[i] = Omn[i] Wo[i] = Wn[i] Mo[i] = Mn[i] else: Omo[i] = Omo[i-1] Wo[i] = Wo[i-1] Mo[i] = Mo[i-1] print(Wo[i], Mo[i], Omo[i])
has comment: http://stackoverflow.com/comment/106622100
has comment: http://stackoverflow.com/comment/86851457
has comment: http://stackoverflow.com/comment/86853930
has comment: http://stackoverflow.com/comment/86851936
has comment: http://stackoverflow.com/comment/86850393
has comment: http://stackoverflow.com/comment/86851885
has comment: http://stackoverflow.com/comment/86851586
has comment: http://stackoverflow.com/comment/86852188
type: Answer
has comment: http://stackoverflow.com/comment/86850689
has comment: http://stackoverflow.com/comment/86851165
has comment: http://stackoverflow.com/comment/86850915

http://stackoverflow.com/a/52935389
answers question: http://stackoverflow.com/q/49837555
type: Answer
has body: Here is a partially async version, which can be improved (especially on getting the result into a python variable). #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import gi gi.require_version('Soup', '2.4') from gi.repository import Soup, GLib, Gio class HttpClient: def __init__(self): self.session = Soup.Session() def get(self, uri): print("Opening %s" % uri) message = Soup.Message.new("GET", uri) self.session.send_async(message, None, self.on_finished, message) def on_finished(self, session, result, message): input_stream = session.send_finish(result) status_code = message.status_code print(status_code) if input_stream: data_input_stream = Gio.DataInputStream.new(input_stream) lines = list() while True: line, length = data_input_stream.read_line_utf8() if line is None: print("Finished") break else: lines.append(line) page = "".join(lines) print(page) if __name__ == '__main__': c = HttpClient() ml = GLib.MainLoop() GLib.idle_add(c.get, "https://www.google.com") ml.run()
upvote count: 3
score: 3
downvote count: 0

http://stackoverflow.com/comment/86751563
comment on: http://stackoverflow.com/a/49867749
type: Comment
score: 0
type: AnswerComment
has text: I've done plenty of that too, and being completely new to Django (and web dev altogether), I can't seem to find a quick solution. I know beginner questions can be annoying, but I'm only posting this after trying many other solutions. The lines that I added in the question are the only ones pertinent to the situation. Like I said in my previous comment, if I comment out the var data line in game.js, it "works" (as in, the button press initiates the main function correctly). If I leave that line in, the button press doesn't work. The Django console raises no error.

http://stackoverflow.com/a/49846109
has comment: http://stackoverflow.com/comment/86708201
answers question: http://stackoverflow.com/q/49845715
type: Answer
has comment: http://stackoverflow.com/comment/86708151
downvote count: 0
has body: So thanks to a friend of mine I found the answer to my own question (Applause to fabiosantoscode - https://github.com/fabiosantoscode) As you can see when I import the database from json on the end I do save_database = map(load_game, save_database) And map is a generator soooo if i would have just save_database = list(map(load_game, save_database)) I wouldn't have had to bang my head on the walls for 3 consecutive days lol thanks to everyone for the attention!!
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49845715

http://stackoverflow.com/comment/86775864
comment on: http://stackoverflow.com/q/49872386
has text: The array can be appended to a column of a dataframe correctly by: df_train[feature] = list(onehot_encoder.fit_transform(integer_encoding_train).toarray()). However, next step is to convert object datatype in training algo, which I am use it in training.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49765280
has body: You can drop it firstly then reindex, thresh in dropna means how many notnull values are required df.dropna(thresh=2).mean(1).reindex(df.index) Out[264]: 0 1.5 1 1.5 2 NaN dtype: float64
upvote count: 2
answers question: http://stackoverflow.com/q/49765266
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/q/49840965
has comment: http://stackoverflow.com/comment/86749875
downvote count: 2
has body: id=TIC123 hyperlink=http://ontrack.com/browse/id TIC123 does not work How to add this hyperlink to id so that i can print id as an hyperlink
has answer: http://stackoverflow.com/a/49841029
favorite count: 0
has title: How to add hyperlinks to strings in python
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49841014
linked to: http://stackoverflow.com/q/13452410
upvote count: 1
tagged with: python
score: -1
answer count: 2

http://stackoverflow.com/comment/86787655
type: QuestionComment
comment on: http://stackoverflow.com/q/49885517
type: Comment
has text: That's odd. I would expect to see that error for the code you posted, because it's using an identifier `file_contents` that hasn't been given a value. Are you doing `file_contents = ...` somewhere outside your class?
score: 0

http://stackoverflow.com/a/49911171
has body: The reason this is happening is because the Main_Class you are modifying in BB.py is not the same Main_Class that AA.py is importing because you're running python BB.py as the main script. When you run a python script like this python BB.py Python will load that module as the __main__ module. It's why the if __name__ == '__main__': check works. The name of that module is __main__, not BB. Then, your __main__ (remember, not BB) module imports the AA module, which it finds because it's in the same directory, which python automatically adds to the PYTHONPATH. Then the AA module loads the BB module, which will be imported a 2nd time as a completely different module than the BB.py script you ran from the command prompt. This is the reason why you shouldn't run your module files directly form command prompts. You could fix this by creating a CC.py file and running python CC.py if __name__ == '__main__': import BB sat1 = BB.Main_Class() sat1.go() print('1 instacne', sat1.car) print('Class instacne', BB.Main_Class.car)
type: Answer
has comment: http://stackoverflow.com/comment/86838545
answers question: http://stackoverflow.com/q/49911095
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49911095

http://stackoverflow.com/comment/86805423
has text: I'm voting to close this question as off-topic because it merely shows a lack of understanding.
comment on: http://stackoverflow.com/q/49894665
type: Comment
score: 2
type: QuestionComment

http://stackoverflow.com/comment/86832162
comment on: http://stackoverflow.com/q/49907632
has text: You couldn't do this in C++ either.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49835256
has comment: http://stackoverflow.com/comment/86738800
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/86685692
type: AnsweredQuestion
tagged with: oop
tagged with: urwid
has title: correct way to extend __init__ in python 3 from parent class
has comment: http://stackoverflow.com/comment/86688150
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86685889
tagged with: initialization
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86685892
has comment: http://stackoverflow.com/comment/86685688
has body: General Question: What is the easiest/"most pythonic" way to initialize a child class exactly as its parent, but adding a single attribute? My specific question: I'd like to extend an (Urwid) Edit object to include a single additional attribute, my_attribute; I've copied the original signature into __init__ and super().__init__, but there are a few undefined parameters/constants (LEFT, SPACE) in the signature and I don't understand how they're set in the parent class. Below are my (breaking) class definition and the parent init method: class MyEdit(urwid.Edit): def __init__(self, my_attribute, caption="", edit_text="", multiline=False, align=LEFT, wrap=SPACE, allow_tab=False, edit_pos=None, layout=None, mask=None): super().__init__(caption="", edit_text="", multiline=False, align=LEFT, wrap=SPACE, allow_tab=False, edit_pos=None, layout=None, mask=None) self.my_attribute = [] # super().__super.__init__("", align, wrap, layout) def my_method(self): #some code that modifies my_attribute return self.my_attribute class Edit(Text): """ Text editing widget implements cursor movement, text insertion and deletion. A caption may prefix the editing area. Uses text class for text layout. Users of this class to listen for ``"change"`` events sent when the value of edit_text changes. See :func:``connect_signal``. """ # (this variable is picked up by the MetaSignals metaclass) signals = ["change"] def valid_char(self, ch): """ Filter for text that may be entered into this widget by the user :param ch: character to be inserted :type ch: bytes or unicode This implementation returns True for all printable characters. """ return is_wide_char(ch,0) or (len(ch)==1 and ord(ch) &gt;= 32) def selectable(self): return True def __init__(self, caption="", edit_text="", multiline=False, align=LEFT, wrap=SPACE, allow_tab=False, edit_pos=None, layout=None, mask=None): """ :param caption: markup for caption preceeding edit_text, see :class:`Text` for description of text markup. :type caption: tex…
has comment: http://stackoverflow.com/comment/86685666
has comment: http://stackoverflow.com/comment/86685628
accepted answer: http://stackoverflow.com/a/49835323
has comment: http://stackoverflow.com/comment/86685962
has comment: http://stackoverflow.com/comment/86685685
has answer: http://stackoverflow.com/a/49835323
tagged with: python

http://stackoverflow.com/q/49840723
possible better answer: http://stackoverflow.com/a/49847421
has answer: http://stackoverflow.com/a/49841308
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49847421
has body: I want to store values that I plan to later use for sorting pdfs on my computer using PyPDF2. I thought that if I created a class and stored identifying info for each type of file (such as a descriptor, a string that is unique to the file and can be found by PyPDF2 later such as an account number, and the path where the file should be moved to) that would work. Something like this: class File_Sort(object): def __init__(self, identifier, file_text, file_path): self.identifier = identifier self.file_text = file_text self.file_path = file_path so an example input from me would be: filetype0001 = File_Sort("Phone Bill", "123456", "/Users/Me/PhoneBills/") I would like to be able to have users generate new file types via a series of raw_input questions, but I can't figure how to generate the variable to create a new instance, so that I can get: filetype000[automatically incrementing number] = File_Sort(UserResponse1, UserResponse3, UserResponse3). Creating the "filetype000[automatically incrementing number]" text itself seems easy enough with: file_number += 1 file_name = "filetype" + str(file_number).zfill(4) but how do you turn the generated file_name string into a variable and populate it?
score: 1
has comment: http://stackoverflow.com/comment/86696231
tagged with: python
accepted answer: http://stackoverflow.com/a/49841308
tagged with: class
type: Question
has title: Dynamically generated Class instances
answer count: 2
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/49873970
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49859689
score: 0
answers question: http://stackoverflow.com/q/49859689
has body: I don't know exact length (N), but your answer helped my to find solutiuon, Thanks names = request.POST.getlist('first_name') surnames = request.POST.getlist('last_name') id = 0 for name in names: data = { 'first_name': name, 'last_name': surnames[id] } users_form = self.users_form_class(data) id += 1 if users_form.is_valid(): f_name = users_form.cleaned_data['first_name'] l_name = users_form.cleaned_data['last_name'] else: return HttpResponse('String is too long, or containts incorrect characters')

http://stackoverflow.com/a/49930506
has comment: http://stackoverflow.com/comment/86924959
has comment: http://stackoverflow.com/comment/123223320
type: Answer
has comment: http://stackoverflow.com/comment/123212474
has body: You could use graphiql - graphical interactive in-browser GraphQL IDE that is comes handy to explore API.
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/49897806
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49897806

http://stackoverflow.com/comment/86556849
comment on: http://stackoverflow.com/a/49769257
type: Comment
type: AnswerComment
has text: @T.Schoonbeek one question per time :) it is better if you have other issues to open new questions. This way not only I will be able to help but other people as well. About your questions, maybe the Q matrix is wrong? you may test it with some of the values with the formula [x y z w] = Q * transpose([x y disparity(x,y) w]) and then divide x y z from the result with the w of the result. you may notice the problem if those numbers are wrong (for example a 0 in the w)
score: 0

http://stackoverflow.com/comment/86585316
has text: `pip install pyopenssl -U` might help?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49784924
type: QuestionComment

http://stackoverflow.com/comment/86763029
score: 0
comment on: http://stackoverflow.com/a/49873857
type: Comment
has text: This is working, however, the result is changing the index of the row, is it possible to keep the same index of left? @jezrael
type: AnswerComment

http://stackoverflow.com/comment/86817235
type: AnswerComment
comment on: http://stackoverflow.com/a/49900572
type: Comment
has text: I wrote backend python scripts that I want to run on the user input and return the value obtained to the user. The code above is a simplified version of what I want to do, it aims at asking the user for age and printing it back. I still get the following error even after your corrections in the code: Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
score: 0

http://stackoverflow.com/comment/86742024
type: AnswerComment
has text: I don't think so. Or maybe I'm having a brain fart. you want the loop to repeat everytime the errorcode does not contain `0` which translates to success right? It might make more natural sense to name it `successcode` rather than `errorcode`.
type: Comment
comment on: http://stackoverflow.com/a/49863300
score: 0

http://stackoverflow.com/q/49847771
has comment: http://stackoverflow.com/comment/86710502
tagged with: dataframe
tagged with: python
score: 0
tagged with: pandas
type: UnansweredQuestion
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49847948
has title: How to iterate over an dataframe object list?
has comment: http://stackoverflow.com/comment/86710477
tagged with: matplotlib
has body: I have a dataset with a lot of int, float and object variables. I've used the code bellow to extract only the name of the object variables into a list. objects = df.dtypes[df.dtypes == "object"].index objects = list(objects) And now I want to plot all these variables against another variable Y. I'm trying to do something like that but it's not working. See the code bellow: import matplotlib.pyplot as plt import seaborn as sns i = 0 for i in objects: plt.figure(figsize=(15,8)) sns.boxplot(df.objects[i], df.Y) i = i+1 I'm new to Python and I don't exactly what I'm doing wrong.

http://stackoverflow.com/comment/86763026
comment on: http://stackoverflow.com/q/49830454
type: Comment
has text: Thank you for suggestion
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86752452
has text: So just make an alias in your .bashrc. I have this one, personally: `alias py='python -i -c ""'`.
score: 1
comment on: http://stackoverflow.com/a/49868454
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86596747
comment on: http://stackoverflow.com/q/49790960
has text: nearly the same error
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86840438
score: 1
type: Comment
has text: Marked as answer but thanks to everyone for all the fine choices. Hard to pick one.
type: AnswerComment
comment on: http://stackoverflow.com/a/49909185

http://stackoverflow.com/comment/134493269
type: Comment
has text: Don't use this one, it will create an identical id for all the rows.
comment on: http://stackoverflow.com/a/72360084
type: AnswerComment
score: 0

http://stackoverflow.com/a/49806932
has comment: http://stackoverflow.com/comment/86629899
score: 3
has comment: http://stackoverflow.com/comment/86656208
answers question: http://stackoverflow.com/q/49806642
type: Answer
accepted answer of: http://stackoverflow.com/q/49806642
has comment: http://stackoverflow.com/comment/86648949
has comment: http://stackoverflow.com/comment/86628644
has comment: http://stackoverflow.com/comment/86629954
has body: If you are thinking of the scripts in terms of their dependencies, that's difficult to translate directly to a master script. Consider using make, which would let you express these dependencies directly: SCRIPTS = $(wildcard *.py) .PHONY: all all: $(SCRIPTS) $(SCRIPTS): python $@ p_05.py p_08.py p_09.py: p_01.py p_09.py: p_03.py p_10.py: p_05.py p_11.py: p_08.py Running make -B -j4 would run all of the Python scripts with up to 4 executing in parallel at any one time.
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86802299
score: 0
has text: @BryanOakley There are no SQLite functions for the shell's dot commands.
type: Comment
comment on: http://stackoverflow.com/q/49880562
type: QuestionComment

http://stackoverflow.com/comment/86666562
type: QuestionComment
comment on: http://stackoverflow.com/q/49824331
has text: The class `init` magic method is using only one `_` when it should be two. So, `_init_` should be `__init__`
score: 0
type: Comment

http://stackoverflow.com/q/49850353
type: UnansweredQuestion
score: 3
tagged with: pythonplotter
tagged with: python
answer count: 0
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86781325
has body: def plot_pca_scatter3D(pca_values, x, y): for name, label in [('1', 0), ('2', 1), ('3', 2), ('4', 3)]: ax.text3D(pca_values[y == label, 0].mean(), pca_values[y == label, 1].mean() + 1.5, pca_values[y == label, 2].mean(), name, horizontalalignment='center', bbox=dict(alpha=.5, edgecolor='w', facecolor='w')) # Reorder the labels to have colors matching the cluster results y = np.choose(y, [1, 2, 0]).astype(np.float) ax.scatter(pca_values[:, 0], pca_values[:, 1], pca_values[:, 2], c=y, cmap=plt.cm.spectral, edgecolor='k') ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) plt.show() this is my plot scatter function. but when I try to perform it. from sklearn.decomposition import PCA pca = PCA(n_components=300) X_pca = pca.fit_transform(X) plot_pca_scatter3D(X_pca, X, Y) I am getting this error message Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe' My datatypes: X_pca (float 64) Size (944,300) Y (Series object of pandas.core.series module) Size (944,) X (dataFrame) Size (944,600) What to do ?
favorite count: 0
type: Question
tagged with: python-3.x
has title: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'
tagged with: data-analysis

http://stackoverflow.com/q/49762320
type: AnsweredQuestion
has title: Passing django request object as arg or kwarg?
answer count: 1
tagged with: keyword-argument
has comment: http://stackoverflow.com/comment/86540716
type: Question
has comment: http://stackoverflow.com/comment/86540669
has comment: http://stackoverflow.com/comment/86541148
score: 0
has body: I'm not sure if this is a django/drf question or just a simple Python question with handling args/kwaargs.. I created a function that alters some fields on incoming JSON and I am trying to call it from a POST method in my views.py The issue is I need the function to handle a variable number of variables as well as the django request object and I am not sure how to handle this without getting an error. Here is my current code: in views.py def post(self, request, person, city, format=None): request = PreSerializer(request, person, city) serializer = CreateRecordSerializer(data=request.data) if serializer.is_valid(): PreSerializer function def PreSerializer(request, *args): if person = "david": person = 1: # Converts strings in JSON to foreignkey ID's if 'name' in request.data: person_record = get_object_or_404(Person, name=[request.data['person']) request.data["person"] = person_record.id if 'city' in request.data: city_record = get_object_or_404(City, name=request.data['city]) request.data["city"] = city_record.id return request I believe the issue is related to (request, *args) Error if person UnboundLocalError: local variable 'person' referenced before assignment
has answer: http://stackoverflow.com/a/49762604
accepted answer: http://stackoverflow.com/a/49762604
tagged with: python
has comment: http://stackoverflow.com/comment/86540586

http://stackoverflow.com/comment/115713626
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49763412
type: Comment
has text: Hi @Scott Boston, I have posted a similar question: https://stackoverflow.com/questions/65445131/comparing-values-from-two-datasets . If you could have a look at mine too, it would be greatly appreciated. I have tried to follow your answer and other answers, but unfortunately I am still having difficulties in getting a good output (because of colours, lines and legend). Thanks a lot

http://stackoverflow.com/q/49793141
has comment: http://stackoverflow.com/comment/86621290
has comment: http://stackoverflow.com/comment/86621085
type: Question
has body: This is a program that already exists and I'm trying to extend it - so my hands are tied somewhat :-(. I have a program where I want to add an option that takes an unknown number of values so I'm trying to use nargs='+'. I can spot when a value is not actually for my option and is a positional argument and I can then use setattr to set the positional argument - but argparse doesn't get a chance to find the positional argument itself so complains. The syntax for the command, as show in arparse generated help text, is command [--option value [value...]] positional In theory this is possible if I did this instead command positional [--option value [value...]] This is precisely how examples, even in the argparse documentation, work but that is NOT how the command is currently used, NOT how users typically provide programs with options and NOT how argparse generated help text shows the expected syntax. So it there a way to somehow both handle the positional but also tell argparse 'oh, I found this positional so no need to complain that it is missing'?
has comment: http://stackoverflow.com/comment/86718460
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86619653
tagged with: python
has title: argparse nargs and positionals
score: 0
answer count: 0
tagged with: argparse
linked to: http://stackoverflow.com/q/26985650

http://stackoverflow.com/comment/86628785
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49806809
has text: Yes... dbl checking, yes. `0.22.0`. `df.index.inferred_freq` is the string `'30T'`. What do you get with `type(df.index.inferred_freq)`

http://stackoverflow.com/comment/86819011
has text: Seems pretty straightforward: `byref` wants an argument that isn't `None`. The [docs](https://docs.python.org/3/library/ctypes.html#ctypes.byref) are pretty clear on this point: "must be an instance of a ctypes type". `None` is not an instance of a ctypes type.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49901708

http://stackoverflow.com/q/49771122
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86558093
tagged with: python
accepted answer: http://stackoverflow.com/a/49771673
has comment: http://stackoverflow.com/comment/86558196
has answer: http://stackoverflow.com/a/49983139
possible better answer: http://stackoverflow.com/a/49983139
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86558244
answer count: 3
has title: Python coding — How to find the trail of a specific element in lists of lists?
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49771673
has answer: http://stackoverflow.com/a/49772260
has body: I am doing groklearning on python and I am trying to work out a problem as below: You're familiar with the story of Hansel and Gretel, so when you decide to go exploring you always make sure to keep track of where you've come from. Since you know how unreliable leaving a trail of breadcrumbs is, you decide to write a program to help you map out your trail. Your program should first read in the size of the grid that you will be exploring, and then read in directions: left, right, up or down. You always start exploring at the top left of your map. After every step, you should print out the trail, reading in directions until a blank line is entered. Your program should work like this: the output should like this: Grid size: 3 x.. ... ... Direction: right xx. ... ... Direction: down xx. .x. ... Direction: right xx. .xx ... Direction: My code is as below and I am stuck here. I am confused about how to find 'x' and how to change a specific neighbour of 'x'. size = int(input('Grid size: ')) table = [] for i in range(size): row=[] for j in range(size): row.append('.') table.append(row) table[0][0] = 'x' for row in table: print(*row,sep='') Direction = input('Direction: ') while Direction: if Direction == 'right': for i in range(size): for j in range(size-1): if table[i][j] == 'x': table[i][j+1] = 'x' table[i-1][j+1] = '.' break elif Direction == 'down': for i in range(size): for j in range(size-1): if table[j][i] == 'x': table[j+1][i] = 'x' table[j+1][i-1] = '.' break Direction = input('Direction: ')

http://stackoverflow.com/q/49797630
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49797987
linked to: http://stackoverflow.com/q/6520445
has answer: http://stackoverflow.com/a/49797987
tagged with: python
type: Question
score: 1
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
has title: Django Fallback to model lookup from external API
tagged with: django-rest-framework
has body: I'm using Django REST framework to serve up JSON content for a website front end. On the back end, I have two Django models, Player and Match, that each reference multiple of the other. A Match contains multiple Players, and a Player contains multiple Matches. This data is originally retrieved from a third-party API. Matches and Players must be fetched separately from the API, and can only be fetched one at a time. When an object is fetched, its data is converted from the external JSON format into my Django model. At this point, the Match/Player will live forever in Django. The hard part is that I want this external fetching to be seamless. If I query for a player or match and it's in the DB, then just serve what we have there. Otherwise, I want to fetch that object from the external DB. My question is, does Django provide any convenient way of handling this? Ideally, any query along the lines of Match.objects.get(id=...) will handle this API fallback transparently (I don't mind the fact that this query may take significantly longer in some cases).

http://stackoverflow.com/q/49811189
has title: The system cannot find the file specified in `edx-dl` module
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/51052825
favorite count: 0
score: 1
tagged with: windows
has answer: http://stackoverflow.com/a/49827166
has body: Am trying to use this Python Module. https://github.com/coursera-dl/edx-dl Please excuse my basic knowledge. Installed Anaconda 3 Windows 10 then: pip install edx-dl pip install --upgrade youtube-dl Then to get courses did: edx-dl -u user@user.com --list-courses edx-dl -u user@user.com COURSE_URL This all worked however once downloads actually started was getting: Got SSL/Connection error: HTTP Error 403: Forbidden Fiddler showed that it was being blocked by by Cloudfare I suspect due to User-Agent I the installed Fake_UserAgent https://pypi.python.org/pypi/fake-useragent and added: from fake_useragent import UserAgent #added this def edx_get_headers(): """ Build the Open edX headers to create future requests. """ logging.info('Building initial headers for future requests.') headers = { 'User-Agent': 'edX-downloader/0.01', 'Accept': 'application/json, text/javascript, */*; q=0.01', 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', 'Referer': EDX_HOMEPAGE, 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': _get_initial_token(EDX_HOMEPAGE), } ua = UserAgent() #added this headers['User-Agent'] = ua.ie #added this It then downloaded a pdf and an xls but got another error due to request.py adding a header so added fake to requests.py and commented out the default header as below. from fake_useragent import UserAgent ub = UserAgent() self.addheaders = [('User-Agent', ub.ie)] # self.addheaders = [('User-Agent', self.version), ('Accept', '*/*')] [('User-Agent', self.version), ('Accept', '*/*')] The new error is below. I can't work out how to troubleshoot further. I suspect it can't find a file / path possibly due to Windows. [download] https://youtube.com/watch?v=bKkrDLwDnDE =&gt; Downloaded\Implementing_ETL_with_SQL_Server_Integration_Services\02-Module_1__ETL_Processing\01-%(title)s-%(id)s.%(ext)s Downloading video with URL https://youtube.com/watch?v=bKkrDLwDnDE from YouTube. Traceback (most recent call last): File "edx-dl.py", line 6, in &lt;module&gt…
tagged with: python
tagged with: edx
type: Question
answer count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/49775012
has comment: http://stackoverflow.com/comment/86565379
type: Answer
accepted answer of: http://stackoverflow.com/q/49774943
has body: Using tuple() should help. import calendar dictMnths = dict((v,k) for k,v in enumerate(calendar.month_abbr)) print('aaFeb'.endswith(tuple( dictMnths.keys()))) # or 'aaFeb'.endswith(tuple(filter(None, dictMnths.keys()))) Output: True Note: I used filter(None, dictMnths.keys()) just to remove empty elements.
has comment: http://stackoverflow.com/comment/86565457
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/49774943

http://stackoverflow.com/a/49869350
has body: This is because of the floating point precision. The floats in Python are encode on 64 bits (on a 64 bits system). So, you have a maximum possible precision to represent number. If you want absolute precision, use fixed point with the Decimal module. For further explanation, see this [article].(https://docs.python.org/3/tutorial/floatingpoint.html)
type: Answer
answers question: http://stackoverflow.com/q/49869328
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/49785586
tagged with: dice
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86587066
answer count: 1
has comment: http://stackoverflow.com/comment/86586836
tagged with: simulator
has comment: http://stackoverflow.com/comment/86586630
has title: How to implement a quit option into my code?
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49785885
has comment: http://stackoverflow.com/comment/86587037
tagged with: python
has comment: http://stackoverflow.com/comment/86586772
has comment: http://stackoverflow.com/comment/86588462
score: 0
has comment: http://stackoverflow.com/comment/86588356
has body: hi I'm fairly new to programming and am currently writing the classic dice rolling simulator in python 3.6. I'm trying to make it as user-friendly as I can hence the amount of code there is, I've written the code and it works but I'm having trouble creating a part of the code where if the user types in 'quit' into the 'usersInput' variable it will break the loop and quit the program. I'm not currently sure on where and how to place this condition into the code any help will be of great thanks. import math import random import time numberList = [4,6,8,10,12,20] #list of dice sides print ('\n'*100) #keeping the screen clean! print("Hello User!") #Intro welcome nameLoop = 0 #loop variable while nameLoop &lt;= 0:#start a loop for inputting name usersName = str(input("Please enter your name:")) if len(usersName) &lt;= 0 or usersName == ' ': print('\n'*100 + "You need to enter a name") else: nameLoop += 1 print ('\n'*100) print ("Hi "+usersName+","+" let's get started") time.sleep(3) print ('\n'*50) returnProgram = 0#loop variable while returnProgram ==0:#returns user to the welcome page print ("Welcome to the dice rolling simulator!")#welcome page print ('\n')#new line try: usersInput = int(input("""To roll a die please input how many sides you would like the die to have or press the *ENTER* key to choose from a list:""")) if usersInput == 0:#catches if a user tries to randomize a number between 0 and 0 print ('\n'*100) print("That's not enough sides! Try again!")#error message time.sleep(2) print ('\n'*100) continue#continues loop and returns to welcome message except ValueError:#perform action if input isnt an integer print ('\n'*100) print("Type '0' to return") print ("Choose a number from the list:") print (numberList)#callinf a list of pres-selected numbers to roll from numListInputLoop = 0#loop variable while numListInputLoop == 0:#enters loop for user to input more than one option from 'numberList' try: numListInput = int(input(":")) except ValueError: print("That…

http://stackoverflow.com/a/49881792
score: 3
answers question: http://stackoverflow.com/q/49864209
type: Answer
has body: Here is the answer: You have to get past the AWS firewall. You have to Go into EC2 (from the list of all AWS services) Click security groups Click your Cloud9 instance Click Inbound Click Edit Click Add Rule Add this rule: For Type, choose Custom TCP Rule. - All Traffic also worked. For Port Range, type 8080, 8081, or 8082. - If you did 'All Traffic' this will default to all ports. For Source, choose Anywhere, which looks like 0.0.0.0/0 Here is a screen shot link: https://i.sstatic.net/xpW5F.jpg AWS does have this, buried, in their C9 documentation. https://docs.aws.amazon.com/cloud9/latest/user-guide/app-preview.html#app-preview-share-security-group In Share a Running Application over the Internet, Step 2: Set Up the Security Group for the Instance
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49864209

http://stackoverflow.com/comment/86566029
score: 1
comment on: http://stackoverflow.com/a/49775162
has text: I picked up on that, thanks. I actually could change param = 'c 1' to param = 'c 6' as well it turns out, but I prefer to loop so I can add new lines after each ping
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49768225
downvote count: 0
has comment: http://stackoverflow.com/comment/86590936
has body: One way is to group the dataframe by weekday and apply line plot for each group. Hopefully this is what you want: import matplotlib.pyplot as plt import numpy as np import pandas as pd ts = pd.DataFrame(np.random.randn(100), index=pd.date_range('1/1/2000', periods=100), columns=['quantity']) ts['weekday'] = ts.index.weekday_name fig, ax = plt.subplots() ts.groupby('weekday').agg(lambda x: x['quantity'].plot(ax=ax, legend=True, label=x['weekday'][0])) plt.show() Edit: Sort weekdays from Monday to Sunday The key change here is to use weekday rather than weekday_name since Pandas has it coded as "Monday=0, Sunday=6". Then you will need to label them with weekday_name during plotting: import matplotlib.pyplot as plt import numpy as np import pandas as pd ts = pd.DataFrame(np.random.randn(100), index=pd.date_range('1/1/2000', periods=100), columns=['quantity']) ts['weekday'] = ts.index.weekday fig, ax = plt.subplots() ts.groupby('weekday').agg(lambda x: x['quantity'].plot(ax=ax, legend=True, label=x.index.weekday_name[0])) plt.show()
accepted answer of: http://stackoverflow.com/q/49767096
score: 2
has comment: http://stackoverflow.com/comment/86558768
type: Answer
has comment: http://stackoverflow.com/comment/86576561
has comment: http://stackoverflow.com/comment/86588318
upvote count: 2
answers question: http://stackoverflow.com/q/49767096
has comment: http://stackoverflow.com/comment/86587986
type: AcceptedAnswer

http://stackoverflow.com/a/49913948
accepted answer of: http://stackoverflow.com/q/49912851
type: Answer
has body: np.histogram2d expects flat lists of x and y coordinates, not list-of-lists. You can fix this pretty easily. Just change the lines that populate x and y to flattening list comprehensions: x = [num for _ in range(10) for num in x_list()] y = [num for _ in range(10) for num in y_list()] Alternatively, you could skip the whole complexity of using random.sample and partial and just use np.random.randint instead, which can create random integer arrays of any given shape: x = np.random.randint(0, 80, size=100) y = np.random.randint(0, 80, size=100)
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49912851
has comment: http://stackoverflow.com/comment/86943186

http://stackoverflow.com/q/49827603
linked to: http://stackoverflow.com/q/33700049
score: 1
answer count: 1
downvote count: 0
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/49828878
type: Question
type: UnansweredQuestion
tagged with: diagonal
has title: Is there a way to extract the k diagonals of an (k,n,n) tensor in TensorFlow or Keras?
upvote count: 1
tagged with: python
has body: In the post Get the diagonal of a matrix in TensorFlow for an square matrix (n,n), one sugestion are use the function tf.diag_part(tensor). But if the tensor are dimensions (k,n,n) ? Exist any way to do that? The necessary output are the k diagonals of the k square matrix(n,n) of tensor, that is , I need one output of dimension (k,n). Some suggestion?
tagged with: keras

http://stackoverflow.com/a/49816504
type: Answer
has body: dateutil.parser: This module offers a generic date/time string parser which is able to parse most known formats to represent a date and/or time. This module attempts to be forgiving with regards to unlikely input formats, returning a datetime object even for dates which are ambiguous.
answers question: http://stackoverflow.com/q/49816416
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/86598984
type: QuestionComment
comment on: http://stackoverflow.com/q/49792061
has text: Possible duplicate of https://stackoverflow.com/questions/28892543/scraping-a-response-from-a-selected-option-in-dropdown-list
score: 2
type: Comment

http://stackoverflow.com/comment/86809592
comment on: http://stackoverflow.com/a/49883003
has text: Yes, it definately appears. But I'm trying to obtain an executable that open itselfs a console without having to execute it in the terminal, any idea?
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/comment/86578792
type: Comment
type: AnswerComment
has text: I wrote my follow up question wrongly, I wanted to ask how to implement it such that `p=product_function([f,g])` and then call `p(a=1, c=2)`
score: 0
comment on: http://stackoverflow.com/a/49776472

http://stackoverflow.com/comment/120322561
has text: According to https://pypi.org/project/psycopg2-binary/ "The binary package is a practical choice for development and testing but in production it is advised to use the package built from sources"
type: Comment
score: 5
type: AnswerComment
comment on: http://stackoverflow.com/a/49812755

http://stackoverflow.com/comment/86586024
comment on: http://stackoverflow.com/q/49784969
type: Comment
type: QuestionComment
score: 0
has text: And that 'complex' number, is that really complex or is it a string? `(2+3.12j)` is the normal Python display format.

http://stackoverflow.com/comment/86619825
score: 0
has text: Yes, to clarify in my dataframe the rows are not always as cleanly sorted as in my example. I should have edited it to reflect that.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49802402

http://stackoverflow.com/comment/86950725
type: AnswerComment
has text: But requests_html can render JS?
type: Comment
comment on: http://stackoverflow.com/a/49881973
score: 0

http://stackoverflow.com/comment/87101227
has text: From the errors in EDIT2, it seems than linker doesn't see you boost libraries. Make sure that the enviroment vars `LIBPATH` and `LIB` have correct values. Because when you copied `libboost_python36-vc141-mt-x32-1_67` to your local dir, It linked, but could not find the definitions of some functions.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49922720

http://stackoverflow.com/comment/86580955
comment on: http://stackoverflow.com/a/49781350
score: 0
type: Comment
type: AnswerComment
has text: You're right, there is some anomally here, this version of PyQt4 is somehow depleted (only bmp, pbm, pgm, png, ppm, xbm, xpm). Thanks ! (You should probably edit your answer before I accept it.)

http://stackoverflow.com/comment/86776485
comment on: http://stackoverflow.com/a/49879931
type: AnswerComment
has text: Note that in facts else simply means "if no condition is true, do that", but i tought it would be easyer for you to understand this way ^^ !
score: 0
type: Comment

http://stackoverflow.com/a/49762636
has body: In your curl JSON, the values of accountId and applicationId are integers, not strings. That might make a difference to the application. So use: data = {'accountId': 0, 'applicationId': 0, 'secret': '000'}
has comment: http://stackoverflow.com/comment/86541669
has comment: http://stackoverflow.com/comment/86541123
has comment: http://stackoverflow.com/comment/86541133
has comment: http://stackoverflow.com/comment/86541644
downvote count: 2
has comment: http://stackoverflow.com/comment/86541168
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49762587
upvote count: 3
has comment: http://stackoverflow.com/comment/86541204
answers question: http://stackoverflow.com/q/49762587
has comment: http://stackoverflow.com/comment/86541176
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86541233

http://stackoverflow.com/q/49835326
has body: i am trying to connect mysql in one of my django settings and then try to run django-admin db shell in command line but it is not working. here is my code for settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'investors_data', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', } } and when i am trying to run django-admin dbshell then i am fgetting the following error: Traceback (most recent call last): File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Nishant Singh\AppData\Local\Programs\Python\Python36-32\Scripts\django-admin.exe\__main__.py", line 9, in &lt;module&gt; File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\core\management\base.py", line 322, in execute saved_locale = translation.get_language() File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\utils\translation\__init__.py", line 195, in get_language return _trans.get_language() File "c:\users\nishant singh\appdata\local\programs\python\python36-32\lib\site-packages\django\utils\translation\__init__.py", line 59, in __getattr__ if settings.USE_I18N: File "c:\users\nish…
tagged with: mysql
type: Question
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49835348
answer count: 1
tagged with: django
tagged with: python
has title: Database connection is not working even after providing proper settings in settings.py in django

http://stackoverflow.com/q/49894829
upvote count: 1
favorite count: 0
type: Question
tagged with: numpy
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: interpolation
tagged with: pandas
has body: We have a few dataframes for the price of apples in different countries (say, China, USA, India etc) according to tenors, which look like the below. Taking China as example: tenors = pd.Series(['1W', '1M', '1Y']) apples_china = pd.Series([5.1, 6.2, 7.1]) days = pd.Series([7, 30, 365]) data = {'tenors': tenors, 'apples_china': apples_china, 'days' : days} apples_china = pd.DataFrame(data) Then we would have equivalent ones for the US (apples_usa), Europe (apples_eu) etc. We then have a larger 'portfolio' dataframe that looks like: country = pd.Series(['china', 'usa', 'europe',' china', 'china', 'india']) days = pd.Series([12, 45, 99, 101, 102, 300 ]) portfolio = {'country': country, 'days' : days} df_portfolio = pd.DataFrame(portfolio) I would like to add a column: df_portfolio['price'] that looks at the value in df_portfolio['country'] and, if it is 'china' for instance, takes the number of days (12 in row[0]) and linearly interpolates inside the apples_china dataframe. Thus it would be a value between 5.1 and 6.2 on row[0], a value between 6.2 and 7.1 on row[3] and so forth. For row[1], it would be looking inside the analogous apples_usa dataframe etc. What i tried is: from scipy.interpolate import interp1d test = interp1d(apples_china['apples_china'], apples_china['days']) #arrays Y and X df_portfolio['price'] = np.where(df_portfolio['country']=='china', test(df_portfolio['days']), 0) But it returned a ValueError with the x range.
accepted answer: http://stackoverflow.com/a/49895435
score: 1
answer count: 1
has title: Pandas linear interpolate between different dataframes given values in each row
has answer: http://stackoverflow.com/a/49895435
downvote count: 0

http://stackoverflow.com/a/50319825
has comment: http://stackoverflow.com/comment/128403492
has comment: http://stackoverflow.com/comment/119016896
has comment: http://stackoverflow.com/comment/121218374
has comment: http://stackoverflow.com/comment/127563521
score: 59
upvote count: 59
accepted answer of: http://stackoverflow.com/q/49908399
has body: The dataclasses module has a helper function for field replacement on instances (docs) from dataclasses import replace Usage differs from collections.namedtuple, where the functionality was provided by a method on the generated type (Side note: namedtuple._replace is documented/public API, using an underscore on the name was called a "regret" by the author, see link at end of answer). >>> from dataclasses import dataclass, replace >>> @dataclass ... class V: ... x: int ... y: int ... >>> v = V(1, 2) >>> v_ = replace(v, y=42) >>> v V(x=1, y=2) >>> v_ V(x=1, y=42) For more background of the design, see the PyCon 2018 talk - Dataclasses: The code generator to end all code generators. The replace API is discussed in depth, along with other design differences between namedtuple and dataclasses, and some performance comparisons are shown.
has comment: http://stackoverflow.com/comment/130644274
answers question: http://stackoverflow.com/q/49908399
has comment: http://stackoverflow.com/comment/130305458
has comment: http://stackoverflow.com/comment/130644250
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/132968431

http://stackoverflow.com/a/49854222
answers question: http://stackoverflow.com/q/49790025
has body: first question: restart runtime from runtime menu second question: i think you can use tensorboard to monitor your work.
type: Answer
score: 0

http://stackoverflow.com/a/49912581
has body: You can using reset_index with drop = True Yourdf=Yourdf.reset_index(level=0,drop=True)
score: 2
accepted answer of: http://stackoverflow.com/q/49912502
downvote count: 0
answers question: http://stackoverflow.com/q/49912502
upvote count: 2
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/76506650
score: 0
answers question: http://stackoverflow.com/q/49806074
has body: This question is also found here: How do you get the geckodriver version from python selenium firefox webdriver? browser = webdriver.Firefox print(browser.capabilities) The output contains 'moz:geckodriverVersion' where the version can be found.
type: Answer

http://stackoverflow.com/comment/86728731
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49856803
has text: I don't know if I've understood correctly, but that doesn't seem to change anything? And why 'form1=form1' and not 'form=form1'?

http://stackoverflow.com/a/49774732
has comment: http://stackoverflow.com/comment/86572633
answers question: http://stackoverflow.com/q/49774446
has comment: http://stackoverflow.com/comment/86567737
has body: I think this may help you. If I'm not mistaken PyDev needs to be told where to look for the "modules"/"libraries" where installing it the IDE uses the default and pydev would use its own environment. (below snippet is from comments) if you have any questions just ask - its ready to go you just need to put your own api key in. (it defaults to kelvin so you'd have to convert to f or c, i didn't take the time,if you want to do that i found an example here) also this is what the json response looks like if you are curious. the output would look like: the current temp of Seattle is 284.02 import requests import json # settings key = 'put your api key here' #you can get a free api from https://home.openweathermap.org/api_keys #takes less then 10 seconds to make an account, no verification. base = 'http://api.openweathermap.org/data/2.5/weather?q=' id = '&amp;appid=' city = 'Seattle,US' # found here; https://openweathermap.org/ you could add exceptions here for failed responses or a method for the user to input their own request etc) url = base + city + id + key #following their api structure, probably much better ways to do this lol response = requests.get(url) #send the request to the api and brings it back data = response.json() #saves the response as json (seemed easier they had multiple options) json_str = json.dumps(data) #turn the response into a string resp_dict = json.loads(json_str) #turn string into dict (i learned today to turn it into a dict it has to be a string,i couldn't figure out to print specifics from a str so i converted to a dict) temp = resp_dict['main']['temp'] #grabs the temp from the dict loc = resp_dict['name'] #grabs the location defined above (seattle) print('the current temp of {} is {}'.format(loc,temp)) #(prints the current location and temp) decided to try out the conversion - it was much easier to use the pyowm lib. the output would look like "The current temp in Seattle is 51.57" I made the variables stupid long so you could follow along.…
type: Answer
has comment: http://stackoverflow.com/comment/86568881
has comment: http://stackoverflow.com/comment/86574724
score: 0

http://stackoverflow.com/a/49836371
type: Answer
has body: .destroy() gets rid of the button altogether. To only remove it temporarily, use grid_forget(): def changeOne(): ModusAButton.grid(row=1,column=0,sticky=W, padx=10,pady=10) ModusBButton.grid_forget() def changeTwo(): ModusBButton.grid(row=1,column=1,sticky=W, padx=10,pady=10) ModusAButton.grid_forget()
upvote count: 2
has comment: http://stackoverflow.com/comment/86687861
score: 2
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49836294
has comment: http://stackoverflow.com/comment/86687847
has comment: http://stackoverflow.com/comment/86687832
accepted answer of: http://stackoverflow.com/q/49836294

http://stackoverflow.com/comment/86807651
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49894662
has text: Thanks for the tip, but I close and delete it in a finally statement, which is not shown here. Anyway, even if I forgot this, it would not change the situation, because ret=0 for A and B, and C hangs. While C is still hanging, the exception occurs right in the if ret==1 clause.

http://stackoverflow.com/q/49845362
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49845420
favorite count: 0
type: Question
has title: Python: Using functions of parent package in child package
has comment: http://stackoverflow.com/comment/86705640
accepted answer: http://stackoverflow.com/a/49845420
tagged with: python
has body: I have a python file in which I am importing 2 packages. In C.py: from A import a from B import b However, I want to use the use the functionality of package C in A and B. In B.py: from A import a from C import c In A.py: from C import c C is my main file. However, when I run C.py I get: ImportError: cannot import name c I get that perhaps I am trying to import a file inside itself and it is probably causing the issue. What is the solution for this?
type: AnsweredQuestion

http://stackoverflow.com/a/49916213
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/49916138
has body: Your code is written this way. First you execute all three functions. Then you print the results of all three functions. plus = add(1,1) # ADDING 1 + 1 minus = subtract(1,1) # SUBTRACTING 1 - 1 times = multiply(1,1) # MULTIPLYING 1 * 1 print plus # 2 print minus # 0 print times # 1 If you want the results interleaved with the calculations, then interleave them. plus = add(1,1) # ADDING 1 + 1 print plus # 2 minus = subtract(1,1) # SUBTRACTING 1 - 1 print minus # 0 times = multiply(1,1) # MULTIPLYING 1 * 1 print times # 1
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49916138

http://stackoverflow.com/a/49871182
has comment: http://stackoverflow.com/comment/86799648
has comment: http://stackoverflow.com/comment/86794440
answers question: http://stackoverflow.com/q/49870386
has comment: http://stackoverflow.com/comment/86799739
has comment: http://stackoverflow.com/comment/86799466
downvote count: 0
has body: The problem is with your input. Your input is of shape (100, 64) in which the first dimension is the timesteps. So ignoring that, your input is of shape (64) to a Conv1D. Now, refer to the Keras Conv1D documentation, which states that the input should be a 3D tensor (batch_size, steps, input_dim). Ignoring the batch_size, your input should be a 2D tensor (steps, input_dim). So, you are providing 1D tensor input, where the expected size of the input is a 2D tensor. For example, if you are providing Natural Language input to the Conv1D in form of words, then there are 64 words in your sentence and supposing each word is encoded with a vector of length 50, your input should be (64, 50). Also, make sure that you are feeding the right input to LSTM as given in the code below. So, the correct code should be embedding_size = 50 # Set this accordingingly mfcc_input = Input(shape=(100, 64, embedding_size), dtype='float', name='mfcc_input') CNN_out = TimeDistributed(Conv1D(64, 16, activation='relu'))(mfcc_input) CNN_out = BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001, center=True, scale=True)(CNN_out) CNN_out = TimeDistributed(MaxPooling1D(pool_size=(64-16+1), strides=None, padding='valid'))(CNN_out) # Directly feeding CNN_out to LSTM will also raise Error, since the 3rd dimension is 1, you need to purge it as CNN_out = Reshape((int(CNN_out.shape[1]), int(CNN_out.shape[3])))(CNN_out) LSTM_out = LSTM(64,return_sequences=True)(CNN_out) ... (more code) ...
has comment: http://stackoverflow.com/comment/86796958
has comment: http://stackoverflow.com/comment/86799389
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86794560
type: Answer

http://stackoverflow.com/comment/86664651
type: Comment
type: AnswerComment
score: 0
has text: Thanks! I've added version for 2.7 Python, hope its right
comment on: http://stackoverflow.com/a/49822603

http://stackoverflow.com/comment/86719225
has text: @Aran-Fey you're right, it's a small gotcha. The first creates the same list object, the second creates a new list object.
type: QuestionComment
comment on: http://stackoverflow.com/q/49852271
type: Comment
score: 0

http://stackoverflow.com/comment/87223915
type: AnswerComment
comment on: http://stackoverflow.com/a/49881170
score: 0
type: Comment
has text: seems i forgot to calculate the integration point coordinate.. after extracting this information i need to interpolate the values anyway, so i think getting the values at nodal coordinates is preferable. (i have checked and `val.position` gives me INTEGRATION_POINT) So how do i make sure my output request gives nodal data?

http://stackoverflow.com/comment/86830759
type: QuestionComment
has text: pyplot is kind of tricky; is it any help to switch the last two lines?
comment on: http://stackoverflow.com/q/49907462
score: 0
type: Comment

http://stackoverflow.com/a/52206646
downvote count: 0
upvote count: 2
type: Answer
has body: Maybe too late but in my case I had to create a new virtualenv with: python -m virtualenv &lt;virtual_env_venv&gt; then (after activating it) I was able to do a successful installation in the new virtualenv
answers question: http://stackoverflow.com/q/49862466
score: 2

http://stackoverflow.com/comment/86803767
score: 0
has text: yes. I was too much thinking loop as he talked about loop ... but indeed your solution is way better.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49894153

http://stackoverflow.com/q/49760852
has body: I have to implement a function that checks if a query string is accepted by the FSM (Finite State Automata) down below I have already made a small design that basically retrieves all the data which is needed to work with. I still need to implement code that checks for each character in the query_string if it is available in the certain arrow (transition). So we have for example the query string 'aab' The way the code must run is that it checks if the first character in the query is available in a transition from q0 to q1. In this case that's true so then the code needs to go and check if the second character in the query is present in the transitions going from q1 to q2. This is true again. But then there are no transitions left so the third character in the query is not present in any transitions and it needs to return false. If the query string is accepted the code must return True I'm pretty new to this so I hope you can understand this code down below Code: def accept(fsm, query_string): query_list = list(query_string) # this is the list of the query string print(query_list) start = fsm1.get_initial_state() betweenstates = fsm1.get_transitions() endstates = fsm1.get_end_states() # this function iterates through a dictionary and gives the available transtions per state for i,j in betweenstates.items(): print("The transition to the next state" + str(i) + " : ") for k in tuple(j): print(k) return False print('This is the first query_string') # This is the function that is ran print(accept(fsm1, "b")) # should be True print('\n') print('This is the second query_string') print(accept(fsm1, "aab")) # should be False This is the output: This is the first query_string ['b'] First entries for Q0 : ('a', 'Q1') ('b', 'Q1') First entries for Q1 : ('a', 'Q2') ('', 'Q2') ('b', 'Q2') False This is the second query_string ['a', 'a', 'b'] First entries for Q0 : ('a', 'Q1') ('b', 'Q1') First entries for Q1 : ('a', 'Q2') ('', 'Q2') ('b', 'Q2') False
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49761048
type: Question
upvote count: 0
has title: Python - Making a function to check whether a given query string, is accepted by the given FSM
type: UnansweredQuestion
tagged with: fsm
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/49817982
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/86650459
tagged with: gaussian
tagged with: python
accepted answer: http://stackoverflow.com/a/49818110
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49818110
score: 2
tagged with: regression
downvote count: 0
answer count: 1
has title: Sklearn: Using pretrained hyperparameters Gaussian Process Regression
tagged with: scikit-learn
has body: Fitting a GPR on my data takes a couple of hours, therefore, I want to reuse my pretrained GausianProcessRegressor I think I found a workaround for this, it seems to produce the same results, but I wondered whether there is a better solution for this, as this is kind of a hack. kernel = ConstantKernel(0.25, (1e-3, 1e3)) * RBF(hyper_params_rbf, (1e-3, 1e4)) + WhiteKernel(0.0002, (1e-23, 1e3)) gp = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=30) #normalize the data train = False if train: print('Fitting') gp.fit(X, y) else: gp.kernel_= kernel gp.X_train_ = X gp.y_train_ = y gp._y_train_mean = np.zeros(1) #unuse, as Y is not normalized in Regressor # Precompute quantities required for predictions which are independent of actual query points K = gp.kernel_(gp.X_train_) K[np.diag_indices_from(K)] += gp.alpha gp.L_ = cholesky(K, lower=True) gp.alpha_ = cho_solve((gp.L_, True), gp.y_train_) y_pred, sigma = gp.predict(x, return_std=True)
favorite count: 0

http://stackoverflow.com/q/49844007
upvote count: 0
downvote count: 2
tagged with: python
type: UnansweredQuestion
score: -2
has body: So I have the following code : import os import time os.system('modprobe w1-gpio') os.system('modprobe w1-therm') temp_sensor = '/sys/bus/w1/devices/28-0000095ea98a/w1_slave' def Temp_Raw(): f = open(temp_sensor, 'r') lines = f.readlines() f.close() return lines def Read_Temp(): lines = Temp_Raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = Temp_Raw() here is where the problem comes in:(temp_output) def Read_Temp(): lines = Temp_Raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = Temp_Raw() temp_output = lines[1].find('t=') if temp_output != -1: temp_sting = lines[1].strip()[temp_output+2:] temp_c = float(temp_string) / 1000.0 temp_f = temp_c * 9.0 / 5.0 + 32.0 return temp_c, temp_f while True: print(Read_Temp()) time.sleep(1) I am trying to program a temperature sensor and when I run the following code this error appears : NameError: name 'temp_output' is not defined I check the code multiple times and did not find what was wrong.Could anyone please help me out on what I have to do ? Thanks
has title: NameError: name 'temp_output' is not defined
has comment: http://stackoverflow.com/comment/86702953
has comment: http://stackoverflow.com/comment/86702735
has comment: http://stackoverflow.com/comment/86702700
has answer: http://stackoverflow.com/a/49844193
has comment: http://stackoverflow.com/comment/86702824
answer count: 1
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/q/49885352
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/86787277
score: 0
has comment: http://stackoverflow.com/comment/86787168
possible better answer: http://stackoverflow.com/a/49885748
linked to: http://stackoverflow.com/q/6255050
accepted answer: http://stackoverflow.com/a/49886506
has answer: http://stackoverflow.com/a/49885748
type: Question
has comment: http://stackoverflow.com/comment/86791027
has answer: http://stackoverflow.com/a/49886506
has body: from time import time class data(object): def get_data(self): return self._download_data() def _download_data(self): """ download data code """ print("data downloaded") return time() class A(data): def __init__(self): self.data = self.get_data() print(self.data) class B(data): def __init__(self): self.data = self.get_data() print(self.data) if __name__ == "__main__": a = A() b = B() Result: data downloaded 1523989483.9526002 data downloaded 1523989483.9536002 You can see the time is different that means the data is not same cause the data is time series data. In order to get same data, how can be fix? Also, I knew the following is possible solution but not really at all: class B(A): def __init__(self): self.data = self.get_data() print(self.data) Lets say I have class C, D, E... it is not good idea of using class C(B), class D(C), class E(D)...
has answer: http://stackoverflow.com/a/49886177
has title: Python class getting same data from parent
tagged with: python
tagged with: inheritance
tagged with: class

http://stackoverflow.com/comment/86662879
type: Comment
type: QuestionComment
has text: possibly helpful or related https://stackoverflow.com/questions/39060669/python-matplotlib-install-issue-on-windows-7-for-freetype-png-packages
comment on: http://stackoverflow.com/q/49823462
score: 0

http://stackoverflow.com/a/49889438
downvote count: 0
answers question: http://stackoverflow.com/q/49889383
has body: def double_preceding(values): """(list) -&gt; NoneType Replace each item in the list with twice the value of the preceding item, and replace the first item with 0. &gt;&gt;&gt; L = [1 , 2 , 3] &gt;&gt;&gt; double_preceding(L) &gt;&gt;&gt; L (0, 2, 4] """ if values != []: temp = values[0] # temp is 1 now values[0] = 0 #sets 1 to 0 for i in range(1, len(values)): # start at second item in array and go until end double = 2 * temp # double it by the last (which is stored in temp) temp = values[i] # temp is now equal to the item we just doubled (the "preceding item") values[i] = double # change the value of the item at the index so it is actually the doubled item
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/49854953
possible better answer: http://stackoverflow.com/a/49908626
tagged with: python
has body: Get Pip (Python file from Pypa.io) on Windows 10 is not extracting on my laptop. I followed all the instructions on pypa.io - Installing, however, when I tried to execute the file, despite many attempts to fix this, it says: ERROR: To modify pip, please run the following command: C:\Python27\python.exe -m pip So I ran C:\Python27\python.exe -m pip and then it shows another error message: C:\Python27\python.exe: No module named pip I then consulted with a friend of mine, and he said that the second error message is obviously not a file error, but (me reflecting now) is quite logical. Of course it says that there is no module named pip because that was the very thing that I am trying to download. Then it occurred to me that Python must think that I already have it because it is asking me to modify pip. So I looked into this and saw that I had a pip folder but nothing inside it to do with Python. So this made me think Why is it not downloading? or Why does it think that I already have it? UPDATE The Python installer now comes with an option to install pip which should solve any further problems!
has answer: http://stackoverflow.com/a/49855130
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/49863153
downvote count: 0
tagged with: pip
has title: get-pip.py broken on Windows 10
upvote count: 7
has answer: http://stackoverflow.com/a/49908626
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49863153
has comment: http://stackoverflow.com/comment/86724335
score: 7

http://stackoverflow.com/a/49785776
downvote count: 0
score: 1
upvote count: 1
has body: You can use \b[1-3][0-9]\s+[a-zA-Z]*\s+[1-9][0-9]{3}\b Demo It's based on you regex with some slight changes. I've replaced beginning/end of the line marks (^$)with word boundaries \b. I've added spaces (\s+) between date parts and I allowed zero in the day and year. When you have it, you can use strptime, as Sam Collins suggested.
answers question: http://stackoverflow.com/q/49785391
type: Answer

http://stackoverflow.com/comment/86586802
comment on: http://stackoverflow.com/q/49785649
score: 0
type: Comment
type: QuestionComment
has text: Well, you never change the button's font or font size, so... it's no surprise that it doesn't change, is it? Have you tried actually assigning the selected value to the button's `font` property?

http://stackoverflow.com/comment/118065471
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49843203
score: 0
has text: Does this answer your question? [Numpy mean with condition](https://stackoverflow.com/a/66790465/9067615)

http://stackoverflow.com/a/49793592
accepted answer of: http://stackoverflow.com/q/49793479
has comment: http://stackoverflow.com/comment/86602119
has comment: http://stackoverflow.com/comment/86602544
has comment: http://stackoverflow.com/comment/94902493
type: Answer
has body: This is how you use substring. Your position will be -3 and the length is 3. pyspark.sql.functions.substring(str, pos, len) You need to change your substring function call to: from pyspark.sql.functions import substring df.select(substring(df['number'], -3, 3), 'event_type').show(2) #+------------------------+----------+ #|substring(number, -3, 3)|event_type| #+------------------------+----------+ #| 022| 11| #| 715| 11| #+------------------------+----------+
score: 24
has comment: http://stackoverflow.com/comment/86617436
has comment: http://stackoverflow.com/comment/86603343
has comment: http://stackoverflow.com/comment/94898569
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86602359
has comment: http://stackoverflow.com/comment/86603275
upvote count: 24
answers question: http://stackoverflow.com/q/49793479

http://stackoverflow.com/comment/86812553
comment on: http://stackoverflow.com/q/49889113
has text: can you tell how are you creating the sentence vectors?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86884739
type: Comment
has text: yup, now it is correct and properly working, thnx. can you please explain the need of line `raise IOError('files not consistent')` twice. if we are check `if len(datasets) != len(datasets2):` then it's ok. what is need of checking again `for a,b in zip(datasets, datasets2):`
type: AnswerComment
comment on: http://stackoverflow.com/a/49924498
score: 0

http://stackoverflow.com/comment/86714311
score: 0
comment on: http://stackoverflow.com/a/49849827
type: Comment
has text: Thank you for your answer first, but you know what this error is ?-- join() got an unexpected keyword argument 'on'
type: AnswerComment

http://stackoverflow.com/comment/86683422
type: QuestionComment
comment on: http://stackoverflow.com/q/49832036
score: 0
has text: (1) Yes, you can; (2) `button.clicked.connect(slot)`.
type: Comment

http://stackoverflow.com/comment/86832156
has text: @ayhan my real application uses regex's and some other stuff, so processing for each row is unavoidable. I can't vectorize. OH -- never mind, I misunderstood, you mean create a Series for each call to `f()`.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49906526

http://stackoverflow.com/a/49871253
has comment: http://stackoverflow.com/comment/86758522
answers question: http://stackoverflow.com/q/49871107
has body: That's correct, as you seem to use global incorrectly. It can make existing variable out of your scope visible and available for modification, like this: a = 'test' def f(): global a a = 'edited' f() print(a) Output: &gt;&gt;&gt; edited You don't seem to declare variable with this name, hence the NameError. And again - global is not for creating global variables, it is for making them visible. By the way, think twice before using globals in python, that usually indicates huge design problems. It's surely possible to refactor your code in a way that you won't need global.
has comment: http://stackoverflow.com/comment/86758277
has comment: http://stackoverflow.com/comment/86758737
type: Answer
has comment: http://stackoverflow.com/comment/86758188
score: 0

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/49865829

http://stackoverflow.com/comment/87144331
comment on: http://stackoverflow.com/a/50009412
type: AnswerComment
score: 0
has text: I got an error : KeyErrorTraceback (most recent call last) <ipython-input-45-29d3775fa7ea> in <module>() 3 gen_dict = [{ii:dfs_paths(tree,ii)} for ii in all_items] 4 for gen in gen_dict: ----> 5 for row in list(gen.values()).pop(): 6 set_a.append(list(gen.keys()).pop()) 7 end_points.append(row) KeyError: '1'
type: Comment

http://stackoverflow.com/comment/86756809
has text: I already upgraded my python just before I posted this post, sir, and still did not work.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49862657
type: AnswerComment

http://stackoverflow.com/a/49824936
has comment: http://stackoverflow.com/comment/86665873
answers question: http://stackoverflow.com/q/49824886
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86665722
has comment: http://stackoverflow.com/comment/86665777
has body: You can use the format specification mini language together with str.format tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] for tup in zip(*tableData): print("{:&gt;9} {:&gt;9} {:&gt;9}".format(*tup)) prints apples Alice dogs oranges Bob cats cherries Carol moose banana David goose EDIT: You can generate these strings dynamically, if you don't know what size you want the columns when you write the code from itertools import chain def gen_format_str(widths): return ' '.join(["{{:&gt;{}}}".format(width) for width in widths]) def n_of_width(n, width): return gen_format_str([width] * n) def all_widest(list_of_lists): return n_of_width(len(list_of_lists), max(map(len, chain.from_iterable(list_of_lists)))) format_str = all_widest(tableData) for tup in zip(*tableData): print(format_str.format(*tup)) format_str is '{:&gt;8} {:&gt;8} {:&gt;8}', because the longest word, "cherries" is 8 characters long.
downvote count: 0
has comment: http://stackoverflow.com/comment/86666119
type: Answer

http://stackoverflow.com/q/49817091
tagged with: python
has body: I have a csv of the form: name,age,country john,23,japan mel,27,ireland When I try to append with the following code: import csv info=['kirsty','32','germany'] with open('data.csv','a') as file: writer=csv.writer(file) writer.writerow(info) file.close() I get this on opening the file in notepad: name,age,country john,23,japan mel,27,irelandkirsty,32,germany I dont understand why the new entry isn't appending to the next line.
has answer: http://stackoverflow.com/a/49817240
has comment: http://stackoverflow.com/comment/86654266
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86650938
favorite count: 0
has title: Appending new row to csv in python
type: Question
has comment: http://stackoverflow.com/comment/86648821
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86649098
has comment: http://stackoverflow.com/comment/86648779

http://stackoverflow.com/q/49823929
tagged with: lightgbm
has body: Refer to lightgbm.cv, there are two parameters confusing me: metrics and feval. Based on my little knowledge on gbdt, evaluation metrics and evaluation function are both to compute the loss, such as auc, from a vector of predictions and a vector of true labels. However, metrics and function sound like they are handling different tasks . Are they doing the same thing? To be more specific, if I execute lightgbm.cv(params,metrics='auc', feval='ks'), will feval='ks' override metrics='auc'?
tagged with: python
upvote count: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47817424
has answer: http://stackoverflow.com/a/49841183
accepted answer: http://stackoverflow.com/a/49841183
answer count: 1
downvote count: 0
tagged with: machine-learning
score: 4
favorite count: 0
type: Question
has title: Difference between evaluation metrics and evaluation function in lightgbm

http://stackoverflow.com/q/49849494
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49849827
upvote count: 0
tagged with: pyspark
answer count: 1
tagged with: hdfs
has comment: http://stackoverflow.com/comment/86713734
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49849827
has comment: http://stackoverflow.com/comment/86713694
has comment: http://stackoverflow.com/comment/86713856
tagged with: indexing
has comment: http://stackoverflow.com/comment/86713894
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86713908
has body: First I made two tables(RDD) to use following commands rdd1=sc.textFile('checkouts').map(lambda line:line.split(',')).map(lambda fields:((fields[0],fields[3],fields[5]), 1) ) rdd2=sc.textFile('inventory2').map(lambda line:line.split(',')).map(lambda fields:((fields[0],fields[8],fields[10]), 1) ) The keys in first RDD are BibNum, ItemCollection and CheckoutDateTime. And when I checked the values for first RDD to use rdd1.take(2) it shows [((u'BibNum', u'ItemCollection', u'CheckoutDateTime'), 1), ((u'1842225', u'namys', u'05/23/2005 03:20:00 PM'), 1)] and similarly the keys in second RDD are BibNum, ItemCollection and Itemlocation. And the values are as following: [((u'BibNum', u'ItemCollection', u'ItemLocation'), 1), ((u'3011076', u'ncrdr', u'qna'), 1)] Once I created two RDDs, I tried to join those two to use rdd3=rdd1.join(rdd2) After it, when I checked the value of rdd3 to use rdd3.take(2). Following error happened. IndexError: list index out of range I do not know why it happend. Please enlighten me if you know the reason. If you have any doubts for my question or code, just let me know I will try to clarify it. Thanks edit--- I put up my sample input data for each RDD BibNum,ItemBarcode,ItemType,ItemCollection,CallNumber,CheckoutDateTime,,,,,,, 1842225,10035249209,acbk,namys,MYSTERY ELKINS1999,05/23/2005 03:20:00 PM,,,,,,, 1928264,10037335444,jcbk,ncpic,E TABACK,12/14/2005 05:56:00 PM,,,,,,, 1982511,10039952527,jcvhs,ncvidnf,VHS J796.2 KNOW_YO 2000,08/11/2005 01:52:00 PM,,,,,,, 2026467,10040985615,accd,nacd,CD 782.421642 Y71T,10/19/2005 07:47:00 PM,,,,,,, 2174698,10047696215,jcbk,ncpic,E KROSOCZ,12/29/2005 03:42:00 PM,,,,,,, 1602768,10028318730,jcbk,ncpic,E BLACK,10/08/2005 02:15:00 PM,,,,,,, 2285195,10053424767,accd,cacd,CD 782.42166 F19R,09/30/2005 10:16:00 AM,,,,Input,BinNumber,Date,BinNumber+Month 2245955,10048392665,jcbk,ncnf,J949.73 Or77S 2004,12/05/2005 05:03:00 PM,,,,,,, 770918,10044828100,jcbk,ncpic,E HILL,07/22/2005 03:17:00 PM,,,,,,, . BibNum,Title,Au…
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/86714016
has title: Pyspark, error:input doesn't have expected number of values required by the schema and extra trailing comma after columns
has comment: http://stackoverflow.com/comment/86714004
has comment: http://stackoverflow.com/comment/86713938
has comment: http://stackoverflow.com/comment/86713798
downvote count: 1

http://stackoverflow.com/a/49807191
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86630458
has body: You are looping over the rows of only_adam, but index the columns of that array with the loop variable i. This does not make sense and leads to the error shown. The plot that shows the data points has lines in it. Those are the lines shown. You cannot make them smaller by decreasing the other plot's linewidth. Instead you need to set the linestyle of that plot off, e.g. plot(..., ls="")
answers question: http://stackoverflow.com/q/49806961
has comment: http://stackoverflow.com/comment/86629861
type: Answer
downvote count: 0

http://stackoverflow.com/comment/134700209
comment on: http://stackoverflow.com/a/76388659
has text: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/q/49830562
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/86676404
linked to: http://stackoverflow.com/q/1388818
has comment: http://stackoverflow.com/comment/86676282
tagged with: python
has body: Let the two lists be x = [0,1,2,2,5,2,1,0,1,2] y = [0,1,3,2,1,4,1,3,1,2] How to find the similar elements in these two lists in python and print them. What I am doing- for i, j in x, y: if x[i] == y[j]: print(x[i], y[j]) I want to find elements like x[0], y[0] and x[1], y[1] etc. This does not work, I am new to python. I want to find the exact index at which the elements are common. I want to find the index 0, 1, 3, 6, 8, 9; because the elements at these indices are equal
has comment: http://stackoverflow.com/comment/86676314
has comment: http://stackoverflow.com/comment/86676327
score: 0
has comment: http://stackoverflow.com/comment/86676291
has title: How to count the total number of similar elements in two lists occuring at the same index?
has answer: http://stackoverflow.com/a/49830615
has comment: http://stackoverflow.com/comment/86676427
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49830628
answer count: 2

http://stackoverflow.com/comment/86737686
type: AnswerComment
type: Comment
has text: No, but since it is a local installation, it is not difficult to have root access on mysql.
comment on: http://stackoverflow.com/a/49861136
score: 0

http://stackoverflow.com/comment/86753875
type: QuestionComment
has text: @Prune I updated the post and I receive an OverflowError: (34, 'Result too large') the error comes after several iterations of my gradient descent function. The exact function that throws the error is the costFunction. However, I expected to see my costFunction constantly return a decreasing value for the error.
type: Comment
comment on: http://stackoverflow.com/q/49865952
score: 0

http://stackoverflow.com/comment/86695761
type: QuestionComment
comment on: http://stackoverflow.com/q/49840577
has text: So what format are the dates that you're having trouble with in?
score: 1
type: Comment

http://stackoverflow.com/comment/86821428
type: AnswerComment
score: 0
has text: Yes, @Fl.pf., it does. When you run your code, `openfile` is immediately be called. Is this not what you want? Perhaps you want to save the return value of `openfile` and use it later. If so, simply assign it to a variable.
type: Comment
comment on: http://stackoverflow.com/a/49902660

http://stackoverflow.com/q/49908265
has answer: http://stackoverflow.com/a/49924380
tagged with: python
accepted answer: http://stackoverflow.com/a/49924380
has title: Dict type does not work with TypeVar using mypy?
type: Question
upvote count: 2
has body: I'm trying to create a little service locator. All services are children classes of BaseService class. I use registerService method to register a service class type with its instance and it is stored in the _services Dict. Then you can get the service instance calling getService with the class type needed. Example: ServiceLocator.instance().registerService(LogService,LogService()) logServiceInstance =ServiceLocator.instance().getService(LogService) This is the code showing the error: E = TypeVar('E', bound=BaseService) class ServiceLocator(QObject): #type: ignore _instance = None; allServicesInited = pyqtSignal() def __init__(self) -&gt; None: super().__init__() self._instance = self self._services: Dict[Type[E], E] = {} # This gives error: Invalid type "servicelocator.E" def registerService(self, t: Type[E], instance: E)-&gt;None: self._services[t]=instance def getService(self,service: Type[E])-&gt; E: return self._services[service] I get error: Invalid type "servicelocator.E" at the line where the Dict annotation is added as I show in the code. I'm using Python 3.6.4 and MyPy 0.590. Mypy flags are: --ignore-missing-imports --strict Shouldn't this work correclty?
answer count: 1
downvote count: 0
favorite count: 0
tagged with: mypy
score: 2
type: AnsweredQuestion
tagged with: subclass
tagged with: type-variables
tagged with: type-hinting

http://stackoverflow.com/a/49832932
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86682050
accepted answer of: http://stackoverflow.com/q/49831975
downvote count: 1
answers question: http://stackoverflow.com/q/49831975
upvote count: 2
type: Answer
has body: Your code is working well, but maybe u misunderstood it. As you can see all *.md are located under ./pages/01.home directory, however, your files list only has all files under `./pages'. Here is a simple modifing code to get all files under root path and the first sub-dir. import os import sys import glob def get_files(path): for root, dirs, files in os.walk(path): return files def get_mds(path): files_result = [] for root, dirs, files in os.walk(path): files_result.extend(files) for dir in dirs: files_result.append(get_files(path+dir)) for name in files_result: if name.endswith((".md")): print("success") else: print(os.path.join(root, name)) get_mds("./pages/")
has comment: http://stackoverflow.com/comment/86683249
score: 1

http://stackoverflow.com/q/49758227
type: Question
has comment: http://stackoverflow.com/comment/86531612
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86531861
has comment: http://stackoverflow.com/comment/86531988
tagged with: python-2.7
score: 0
answer count: 0
has title: mkdir on Python and Mac OS X
has body: Python2, Mac OS X 10.11... I found it on github. Everything is working fine expect this: error = Popen("%s \"mkdir -p '%s'\"" % (PathZero, MyPath), shell=True, stdout=PIPE, stderr=PIPE).stderr.read() if error != '': send_msg("%sError creating path:\n\t%s" % (red_minus, error), False) else: send_msg("%sCreated path '%s'.\n" % (PathTwo, PathOne), False) I'm always get: Error creating path /bin/sh: /Users/test/Downloads/File: Permission denied I don't need "sudo" for this folder. And I think there some problems with this one : Popen("%s \"mkdir -p '%s'\""
tagged with: macos
has comment: http://stackoverflow.com/comment/86531964

http://stackoverflow.com/a/49847712
type: AcceptedAnswer
has body: Try it: from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(535, 302) self.listWidget = QtWidgets.QListWidget(Form) self.listWidget.setGeometry(QtCore.QRect(50, 60, 256, 192)) self.listWidget.setObjectName("listWidget") self.list = self.listWidget # +++ self.currentRow = None self.currentText = '' self.listWidget.currentRowChanged.connect(self.itemActiv) self.listWidget.currentTextChanged.connect(self.itemActivText) self.pushButton = QtWidgets.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(320, 130, 90, 33)) self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(Form) self.pushButton_2.setGeometry(QtCore.QRect(420, 130, 90, 33)) self.pushButton_2.setObjectName("pushButton_2") self.pushButton_3 = QtWidgets.QPushButton(Form) self.pushButton_3.setGeometry(QtCore.QRect(329, 190, 181, 61)) self.pushButton_3.setObjectName("pushButton_3") self.label = QtWidgets.QLabel(Form) self.label.setGeometry(QtCore.QRect(50, 10, 431, 31)) self.label.setObjectName("label") self.lineEdit = QtWidgets.QLineEdit(Form) self.lineEdit.setGeometry(QtCore.QRect(310, 70, 221, 33)) self.lineEdit.setObjectName("lineEdit") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.pushButton.setText(_translate("Form", "ekle")) self.pushButton.clicked.connect(self.list_add) self.pushButton_2.setText(_translate("Form", "sil")) self.pushButton_3.setText(_translate("Form", "kapat")) self.pushButton_3.clicked.connect(quit) self.pushButton_2.clicked.connect(self.f1) #refresh) #f1) self.label.setText(_translate("Form", "veriler ekleniyor")) def list_add(self): self.label.setText(self.lineEdit.text() + " eklendi") self.listWidget.addItem(self.lineEdit.text()) def f1(self): self.label.setText(self.currentText + " silindi") it = self.listWidget.takeIt…
downvote count: 1
type: Answer
score: -1
answers question: http://stackoverflow.com/q/49846832
accepted answer of: http://stackoverflow.com/q/49846832
upvote count: 0

http://stackoverflow.com/comment/86747812
has text: Glad I could help! :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49861739
type: Comment

http://stackoverflow.com/q/49866323
has comment: http://stackoverflow.com/comment/86748907
tagged with: apache-spark
score: 0
answer count: 0
has body: I'm writing an python app that reads data from Cassandra, does some processing via Spark api, and then writes results to Mysql db via jdbc. The whole code to process data via spark just takes several seconds but writing the last dataframe (with about 5000 rows) to mysql taking around 10 mins so I'm trying to figure out how to speed up that part. This is the code that I'm using to write py spark dataframe to a mysql table: df_name.write.jdbc(url=mysql_url.value, table=tbl_name, mode=mode.value, properties={'user': mysql_user.value, 'password': mysql_pwd.value, 'driver': mysql_jdbc.value}) I allocated --executor-memory 4g --driver-memory 2g --total-executor-cores 6 to run my app. The number of partitions for the data frame that I want to write to mysql is 5740; I followed several advises to reduce number of partitions (via .repartition() function) but it doesn't speed up the writing phase. I also followed trick in [1] to set rewriteBatchedStatements=true and useServerPrepStmts=false but there is no improvement in performance yet. Are there any settings or tricks I would try to improve speed when writing from dataframe to mysql via jdbc? Thank you for your help. [1] Low JDBC write speed from Spark to MySQL P/S: Our Mysql db is in production, and we don't see performance issue in any other applications.
has comment: http://stackoverflow.com/comment/86775530
tagged with: mysql
has comment: http://stackoverflow.com/comment/86772596
has comment: http://stackoverflow.com/comment/86772659
has comment: http://stackoverflow.com/comment/86772316
type: Question
linked to: http://stackoverflow.com/q/36912442
tagged with: pyspark
has comment: http://stackoverflow.com/comment/86772365
has comment: http://stackoverflow.com/comment/86773902
type: UnansweredQuestion
tagged with: python
has title: Pyspark 1.6: Poor performance when writing Dataframe to Mysql via JDBC

http://stackoverflow.com/q/49889593
has answer: http://stackoverflow.com/a/49889656
tagged with: function
has title: I need to create a dictionary that counts the number of times a name appears in a list
tagged with: python
has answer: http://stackoverflow.com/a/49889622
has comment: http://stackoverflow.com/comment/86795267
answer count: 4
has answer: http://stackoverflow.com/a/49891327
upvote count: 2
type: AnsweredQuestion
tagged with: list
score: 1
has answer: http://stackoverflow.com/a/49889653
downvote count: 1
accepted answer: http://stackoverflow.com/a/49889653
has body: I have this code so far: def name_counts(name_list): name_dict = {} for word in name_list: if word in name_dict: name_dict[word] += 1 else: name_dict[word] = 1 print(name_counts(name_list)) which is resulting in: but I need it to only print the first names, not the lasts. How would I do that? I know that I should use the split function but anytime I do name_list.split() it returns with an attribute error.
possible better answer: http://stackoverflow.com/a/49889622
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86795317
has comment: http://stackoverflow.com/comment/86795225

http://stackoverflow.com/q/49868459
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
score: 0
has title: Maya Python referencing optionMenu returns as non-existent
has body: I am trying to write a script that, on button press with a joint selected, will copy the transform values from the selected joint(s) and then create a controller selected from an option menu. My problem is getting the code to read the option menu. I've tried several variations and all say there is no option menu with the selected name. Code follows.... import maya.cmds as maya def testWin(): winName = maya.window(title="test", rtf = True, mxb = False) maya.columnLayout() maya.button(label = "run test", c = "test()") shapeMenu = maya.optionMenu( label='Shape Menu', changeCommand="test()" ) maya.menuItem( label='Circle' ) maya.menuItem( label='Square' ) maya.menuItem( label='Triangle' ) maya.showWindow(winName) testWin() def test(): sel = maya.ls(type = "joint", sl=True) if not sel: print "select at least 1 JOINT" else: new_pos = maya.xform(q=True, t=True, ws=True) new_rot = maya.xform(q=True, rotation=True, ws=True) shape = maya.optionMenu("Shape Menu", q = True, value = True) if shape == "Circle": new_control = maya.circle(center = new_pos) elif shape == "Square": new_control = maya.nurbsSquare(center = new_pos) elif shape == "Triangle": new_control = maya.circle(center = new_pos, degree = 1, sections = 3)
tagged with: optionmenu
answer count: 1
tagged with: maya
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49990560

http://stackoverflow.com/comment/86616221
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49799273
has text: Thanks! Yes, it works. The key is to use to_datetime, even without unit='D' would still work. It would convert to date from 1970-01-01, ...

http://stackoverflow.com/q/49793479
accepted answer: http://stackoverflow.com/a/49793592
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49793592
score: 9
has answer: http://stackoverflow.com/a/70466942
upvote count: 9
downvote count: 0
tagged with: pyspark
tagged with: python
linked to: http://stackoverflow.com/q/45512884
has body: Closely related to: Spark Dataframe column with last character of other column but I want to extract multiple characters from the -1 index. I have the following pyspark dataframe df +----------+----------+ | number|event_type| +----------+----------+ |0342224022| 11| |0112964715| 11| +----------+----------+ I want to extract 3 characters from the last index of the number column. I tried the following: from pyspark.sql.functions import substring df.select(substring(df['number'], -1, 3), 'event_type').show(2) # which returns: +----------------------+----------+ |substring(number,-1,3)|event_type| +----------------------+----------+ | 2| 11| | 5| 11| +----------------------+----------+ The below is the expected output (and I'm not sure what the output above is): +----------------------+----------+ |substring(number,-1,3)|event_type| +----------------------+----------+ | 022| 11| | 715| 11| +----------------------+----------+ What am I doing wrong? Note: Spark version 1.6.0
possible better answer: http://stackoverflow.com/a/70466942
type: AnsweredQuestion
answer count: 2
tagged with: apache-spark
has title: substring multiple characters from the last index of a pyspark string column using negative indexing

http://stackoverflow.com/comment/86755820
type: Comment
type: QuestionComment
has text: I've updated the original post to contain the full code used. The goal of the program is to run through the database (Using the three defined variables for the journal, time, and search term) and capture the links of the individual results. The way the website is established however, simply copying the original link will not suffice, you need to capture the two hidden elements from each hit on the search in order to reconstruct a result link, which I want to save to an output file (.txt). I apologize if it wasn't clear, the above URL was the "desired result", built from the hidden fields.
score: 0
comment on: http://stackoverflow.com/q/49867912

http://stackoverflow.com/q/49761923
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86539824
has body: I'm trying to plot a matrix using pytlot in python. import matplotlib.pyplot as plt m = [ [1, 0, 2, 0, 0], [1, 1, 1, 2, 0], [0, 4, 1, 0, 0], [0, 4, 4, 1, 2], [1, 3, 0, 0, 1], ] plt.imshow(m) plt.show() This look like what I need, but the problem is that I need to be able to select the color for a position. For example: the position 1x2 has to be red. anyway to archive this with Python and Pyplot?
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has title: Plot a matrix in Python with custom colors
answer count: 2
has comment: http://stackoverflow.com/comment/86539714
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49762474
has answer: http://stackoverflow.com/a/49762515
has comment: http://stackoverflow.com/comment/86539438

http://stackoverflow.com/q/49866797
accepted answer: http://stackoverflow.com/a/49867005
has title: Convert Dictionary into Ordered Dictionary using Specified Order
tagged with: pandas
type: Question
possible better answer: http://stackoverflow.com/a/49866909
answer count: 2
has body: I currently have a dictionary with six keys, and the ideal ordering of those keys are as such: order_of_keys = ["id", "question", "choice1", "choice2", "choice3", "choice4", "solution"] Right now each one of those keys corresponds to a dictionary of all possible values. The way I constructed this dictionary was through a Pandas reader (not sure if this matters, but there might be a way to resolve this through Pandas). xls = ExcelFile('quiz/all_questions.xlsx') df = xls.parse(xls.sheet_names[0], parse_cols = 241, keep_default_na=False, na_values=[""]) questions_2 = df.to_dict() The current structure of the dict is like so: {'id': {0: 'CB_1', 1: 'CB_2'}, 'question': {0: 'Who is Ghoulsbee Scroggins?', 1: 'Who is Ebeneezer Yakbain?}, 'choice1': {0: 'Cat', 1: 'A mathematician'}, 'choice2': {0: 'Dog', 1: 'A mathematician'}, 'choice3': {0: 'Ape: 'A mathematician'}, 'choice4': {0: 'Astrophysicist', 1: 'A mathematician'}, 'solution': {0: 'Ape', 1: 'A mathematician'} I would like to turn it into an Ordered Dict of the form: [OrderedDict([('id', '1'), ('question', 'What is the capital of China?'), ('choice1', 'Shanghai'), ('choice2', 'Guangzhou'), ('choice3', 'Hong Kong'), ('choice4', 'Beijing'), ('solution', 'Beijing')]), OrderedDict([('id', '2'), ('question', 'What year did World War 1 start?'), ('choice1', '1896'), ('choice2', '1914'), ('choice3', '1921'), ('choice4', '1929'), ('solution', '1914')]), OrderedDict([('id', '3'), ('question', 'What is the second closest planet to the sun?'), ('choice1', 'Saturn'), ('choice2', 'Mercury'), ('choice3', 'Venus'), ('choice4', 'Mars'), ('solution', 'Venus')]), OrderedDict([('id', '4'), ('question', 'What is the symbol for gold on the periodic table?'), ('choice1', 'Au'), ('choice2', 'Gd'), ('choice3', 'Gl'), ('choice4', 'Or'), ('solution', 'Au')])] I can't seem to figure out how to iterate over the key, value pairs in the right order to construct a list of tuples. Any thoughts?
has answer: http://stackoverflow.com/a/49866909
tagged with: dataframe
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49867005
score: 0

http://stackoverflow.com/comment/87433567
type: AnswerComment
comment on: http://stackoverflow.com/a/49911412
score: 0
type: Comment
has text: This helps! Thanks.

tensorrt
tags question: http://stackoverflow.com/q/49785298
tags question: http://stackoverflow.com/q/49856793
tag name: tensorrt
type: Tag

http://stackoverflow.com/q/49776224
has comment: http://stackoverflow.com/comment/88312245
answer count: 1
has title: using apache tika for scanning documents on servers using sftp
has answer: http://stackoverflow.com/a/50650506
accepted answer: http://stackoverflow.com/a/50650506
has body: I have a tika code in a server. I want to create an SFTP session with another server with files and run Apache tika on that server. I am using python as back end. Will this work ? is my approach correct ? Thanks
type: AnsweredQuestion
tagged with: apache-tika
tagged with: sftp
tagged with: python
has comment: http://stackoverflow.com/comment/86592511
has comment: http://stackoverflow.com/comment/86569097
has comment: http://stackoverflow.com/comment/86610290
type: Question
has comment: http://stackoverflow.com/comment/88312131
score: 0

http://stackoverflow.com/q/49875342
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: random-forest
has comment: http://stackoverflow.com/comment/86771029
type: UnansweredQuestion
tagged with: python
tagged with: graphviz
has body: I am using Python (Pycharm community edition 2016) I've created a working model using Random Forest, and am very keen to see one of the trees visualized. I have researched a lot of info about how the Graphviz package can be used to do this, but I haven't been able to see any code snippets of it working. Below you can see some of my code that creates my model and I even plot its accuracy using the Precicion Recall Curve. How would I now include code to visualize one of the trees ? ###Split data into Training&amp;Testing data-use stratified sampling ### from sklearn.cross_validation import train_test_split X = Actual_DataFrame.copy() y = X.pop('Attrition') X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.30, random_state=42, stratify=y) ###----------------------------------------------------------------------### ### Procedure:- (Model) - RF ### from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier() rf.fit(X_train, y_train) predictions2 = rf.predict(X_test) print ("(Model )") print("Accuracy:",accuracy_score(y_test, predictions2)) print("Cohen's Kappa Score : ",cohen_kappa_score(y_test, predictions2)) print(classification_report(y_test, predictions2)) precision, recall, _ = precision_recall_curve(y_test, predictions2, pos_label=1) average_precision = average_precision_score(y_test, predictions2) print (precision) plt.plot(recall, precision, label='area = %0.2f' % average_precision, color="green") plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('Recall') plt.ylabel('Precision') plt.title('Precision Recall Curve - RF') plt.legend(loc="lower right") plt.show() ###--------------------------------------------------------------------### Any help appreciated Paul
tagged with: tree
has title: Visualizing a tree from a Random Forest model in Python using Graphviz?
answer count: 0
score: 1
linked to: http://stackoverflow.com/q/40155128

http://stackoverflow.com/a/49888338
has body: I think i've found the simplest solution. According to PEP 484, this is valid: T = TypeVar('T') # or TypeVar('T', int, float, bool, str) Action = Callable[[], T] def onReady(f: Action[Any]) -&gt; None: pass
has comment: http://stackoverflow.com/comment/86792934
answers question: http://stackoverflow.com/q/49887430
type: Answer
has comment: http://stackoverflow.com/comment/86792898
has comment: http://stackoverflow.com/comment/86793019
has comment: http://stackoverflow.com/comment/86793208
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86792948
upvote count: 9
accepted answer of: http://stackoverflow.com/q/49887430
score: 9

http://stackoverflow.com/q/49834317
tagged with: save
answer count: 1
type: Question
tagged with: for-loop
tagged with: if-statement
has title: Saving the value of previous step to use in next step in Python
has comment: http://stackoverflow.com/comment/86684254
accepted answer: http://stackoverflow.com/a/49834387
tagged with: python
has answer: http://stackoverflow.com/a/49834387
type: AnsweredQuestion
has body: For the following pseudo code I wrote the code at the end of this text. But for using x(i) and x(i-1) the code gets error NameError: name 'xt' is not defined We have a function here is def F (x). And random number u which is uniform(0,1). i=1...N. we define a x[0] as initial point. xt[i]=x[i-1]+u If F(x[i])&gt;1 then x[i]=xt[i], otherwise x[i]=x[i-1] the steps will continue to from 1 to N. I write 4 sample lines from 1 to 3 for more clarification. i=1 if F(x[1])&gt;1 then x[1]=xt[1], otherwise x[1]=x[0] which xt[1]=x[0]+u and here x[0] is our initial point i=2 if F(x[2])&gt;1 then x[2]=xt[2], otherwise x[2]=x[1] which xt[2]=x[1]+u and x[1] is the point of step 1 i=3 if F(x[3])&gt;1 then x[3]=xt[3], otherwise x[3]=x[2] which xt[3]=x[2]+u and x[2] is the point of step 2 i=4 if F(x[3])&gt;1 then x[4]=xt[4], otherwise x[4]=x[3] which xt[4]=x[3]+u and x[3] is the point of step 2 .... i=N the code is: import numpy as np import math from math import * x=[0.8] N=10 R = np.random.uniform(0, 5) def a(z): return sqrt(z) for i in range(1,N): xt[i]=x[i-1]+u if a(xt[i])&gt;1: x[i]=xt[i] else: x[i]=x[i-1] print(x[i]) I appreciate your help.
score: 0

http://stackoverflow.com/a/49876579
has comment: http://stackoverflow.com/comment/86815945
type: Answer
downvote count: 0
has body: You have to import os module and use the system function from it, then separate the two Python files you are running by &amp;&amp;. import os def song(): user = input() if user == "Chance": os.system('python ScriptA.py &amp;&amp; python ScriptB.py') else: print("Error") song() But I will advice you to just import the two files you want to run into the third file and just run the functions in there like normal functions. e.g. import ScriptA import ScriptB ScriptA.function() ScriptB.function() If there are no functions inside the scripts, the script runs immediately after they are imported.
has comment: http://stackoverflow.com/comment/86769225
score: 3
answers question: http://stackoverflow.com/q/49875889
upvote count: 3

http://stackoverflow.com/comment/86837884
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49910402
has text: @Lemayzeur I want to add a bootstrap class. class="list-group-item"

http://stackoverflow.com/q/49768961
upvote count: 1
tagged with: amazon-web-services
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86554576
tagged with: nginx
has body: I'm trying to run my flask app following a tutorial written in this link - https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-14-04#configure-uwsgi using amazon server's ec2 to run this... Amazon Linux AMI 2017.09.1 (HVM), free tiers on all options. my file structure is as follows: /home/ec2-user/login_test/login_test/app.py /wsgi.py /venv/ so I gave a uwsgi --socket 0.0.0.0:8000 --protocol=http -w wsgi command, as stated in the tutorial, "Testing uWSGI Serving" part, this returns: --- no python application found, check your startup logs for errors --- [pid: 24218|app: -1|req: -1/1] 127.0.0.1 () {24 vars in 257 bytes} [Wed Apr 11 07:01:38 2018] GET / =&gt; generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) with browser returning Internal Server Error so... what should I try and check?? the app works all fine if I activate this with without uwsgi (just python app.py command) and via cmd on my home computer(windows 10) EDIT: my wsgi.py contents: from app import app as application if __name__ == "__main__": application.run()
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/86554280
has comment: http://stackoverflow.com/comment/86553729
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86552995
has comment: http://stackoverflow.com/comment/86553542
accepted answer: http://stackoverflow.com/a/49770074
score: 1
has title: aws ec2 - running python uwsgi with bash command keeps returning --no python application found
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49770074

http://stackoverflow.com/comment/86625441
has text: i mean i got empty file, but when add new line:`tech = re.findall('TECH-\d+',data) and print it then got traider,domain.net ['TECH-1366']` (in new line with brackets)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49804996
type: QuestionComment

http://stackoverflow.com/q/49822879
has comment: http://stackoverflow.com/comment/86661694
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/49823286
answer count: 2
tagged with: pandas
has body: I suspect this use just isn't compatible with groupby, so maybe I'm actually asking for a different pattern that matches what I want. I have a dataframe of events w/ timespans and want to be able to iterate over/apply functions to the rows for each day. But if a row starts in one day and ends in another, I want that row to be included in both. start = pd.DatetimeIndex(start='2018-02-01 21:00:00', end='2018-02-05, 21:00:00', freq='6h') df = pd.DataFrame({'start': start.date, 'end': start.shift(1).date, 'value': 1}, columns=['start', 'end', 'value']) start end value 0 2018-02-01 2018-02-02 1 1 2018-02-02 2018-02-02 1 2 2018-02-02 2018-02-02 1 3 2018-02-02 2018-02-02 1 4 2018-02-02 2018-02-03 1 5 2018-02-03 2018-02-03 1 6 2018-02-03 2018-02-03 1 7 2018-02-03 2018-02-03 1 8 2018-02-03 2018-02-04 1 9 2018-02-04 2018-02-04 1 10 2018-02-04 2018-02-04 1 11 2018-02-04 2018-02-04 1 12 2018-02-04 2018-02-05 1 13 2018-02-05 2018-02-05 1 14 2018-02-05 2018-02-05 1 15 2018-02-05 2018-02-05 1 16 2018-02-05 2018-02-06 1 So the first group should contain [0, ..., 4], then [4, ..., 8], etc. In practice the events aren't evenly spaced so the lengths (in rows) of each day won't be constant. The closest I've managed is starting with groupby.indices and manipulating the groups to match what I want, but this feels pretty gross. {k: np.append(v[0] - 1, v) for k, v in df.groupby('start').indices.items() if not (len(v) == 1 and v[0] == 0)} {Timestamp('2018-02-02 00:00:00'): array([0, 1, 2, 3, 4]), Timestamp('2018-02-03 00:00:00'): array([4, 5, 6, 7, 8]), Timestamp('2018-02-04 00:00:00'): array([ 8, 9, 10, 11, 12]), Timestamp('2018-02-05 00:00:00'): array([12, 13, 14, 15, 16])}
downvote count: 0
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/49825339
has title: Pandas groupby with overlapping groups / windows
type: UnansweredQuestion

http://stackoverflow.com/q/49866283
has answer: http://stackoverflow.com/a/49876768
answer count: 2
tagged with: google-cloud-platform
possible better answer: http://stackoverflow.com/a/73966135
downvote count: 0
has body: After installing and configuring Google Cloud SDK gsutil command can be run by simply typing its name and the argument(-s) using Windows cmd. Here is the example: "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin\gcloud" version But the same command fails if run using Python subprocess. With subprocess's shell argument set to True the ImportError occurs: import subprocess cmd = '"C:/Program Files (x86)/Google/Cloud SDK/google-cloud-sdk/bin/gsutil" version' p = subprocess.Popen(cmd, shell=True) ..... ImportError: No module named site With subprocess's shell argument set to False then the WindowsError: [Error 2] The system cannot find the file specified occurs: p = subprocess.Popen(cmd, shell=False) Is there a way to run gsutil on Windows using Python?
tagged with: gcloud
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/97553498
tagged with: gsutil
has title: How to run Google gsutil using Python
tagged with: python
has answer: http://stackoverflow.com/a/73966135
score: 15
accepted answer: http://stackoverflow.com/a/49876768
type: AnsweredQuestion
upvote count: 15

http://stackoverflow.com/a/49868047
has body: If I am understanding your question correctly, you are trying to run the script above and it's not doing anything? If this is your complete module, you are not calling the class at all, but defining the class object. also the parenthesis in class deleteMongo(): are redundant in a class, since it always inherits the object. On the current setup of this class object, you should use def instead, or setup your class to initialize shared objects of the class. Based on your current code, try this: from pymongo import MongoClient class deleteMongo: def __init__(self, databaseAddress): # if the databseAddress is always the same, you can remove it from the arguments # and hardcode it here self.client = MongoClient(databaseAddress) def deleteFirst(self): db = self.client.TableData db.Employe.delete_one({"name": "EmployeOne"}) def deleteSecond(self): db = self.client.PersonData db.Person.delete_one({"name": "PersonOne"}) def deleteThird(self): db = self.client.AutoData db.Auto.delete_one({"name": "AutoThird"}) and then when you need to call one of the class functions, call it like this: deleteMongo(databaseAddress='someaddress').deleteFirst()
answers question: http://stackoverflow.com/q/49866879
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49866879
type: Answer
score: 0

http://stackoverflow.com/q/49894386
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: matplotlib
has body: I want to label my plots alphabetically in a multi-axes plot. With ax.text and manual coordinates, I can achieve that on a single figure: ax.text(0.01, 0.96, 'A', transform=ax.transAxes, fontweight='bold', va='top', ha='left', backgroundcolor='k', color='white') I want the black box to match the upper left corner exactly. Applying the above code on another figure does not work: Is there a way to match the black box of the text background with the axis corner exactly?
has title: Position text with background exactly in corner of matplotlib plot
type: Question
accepted answer: http://stackoverflow.com/a/50091489
has answer: http://stackoverflow.com/a/50091489
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
tagged with: plot

http://stackoverflow.com/a/49796393
score: 0
has comment: http://stackoverflow.com/comment/86607331
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86608890
has comment: http://stackoverflow.com/comment/86608874
accepted answer of: http://stackoverflow.com/q/49796079
type: Answer
has comment: http://stackoverflow.com/comment/86607167
answers question: http://stackoverflow.com/q/49796079
has body: Your first step is writing a factorial function. This can be done recursively or with a for-loop: def factorial(n): return 1 if n &lt; 2 else n * factorial(n-1) or: def factorial(n): x = 1 for i in range(2, n+1): x *= i return x and then for calculating e we can again use recursion or a for-loop. This function takes a parameter which indicates how many terms in the formula it should evaluate (so you should call with 10 in your case). def calc_e(t): if not t: return 0 else: return 1 / factorial(t-1) + calc_e(t-1) or: def calc_e(t): s = 0 for i in range(t): s += 1 / factorial(i) return s and they both work: &gt;&gt;&gt; calc_e(1) 1.0 &gt;&gt;&gt; calc_e(2) 2.0 &gt;&gt;&gt; calc_e(3) 2.5 &gt;&gt;&gt; calc_e(4) 2.6666666666666665 &gt;&gt;&gt; calc_e(5) 2.708333333333333 &gt;&gt;&gt; calc_e(10) 2.7182815255731922 &gt;&gt;&gt; calc_e(20) 2.7182818284590455

rotation
tags question: http://stackoverflow.com/q/49830644
type: Tag
tags question: http://stackoverflow.com/q/49790453
tag name: rotation

http://stackoverflow.com/comment/86563522
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49774300
has text: and i noticed that using your code returns me the error "'DataFrame' object has no attribute 'map'" do you think I should convert it into numpy array?
score: 0

http://stackoverflow.com/a/49797987
has body: If a way is "convenient" depends on your expectations ... You could create a custom QuerySet where you override the get() method to include your fetch-from-API logic. Then you create a custom manager based on that QuerySet, like the docs show here. Finally add that custom manager to your model. See also this question from 2011.
accepted answer of: http://stackoverflow.com/q/49797630
score: 0
has comment: http://stackoverflow.com/comment/86919095
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86611037
has comment: http://stackoverflow.com/comment/86912766
answers question: http://stackoverflow.com/q/49797630
type: Answer

http://stackoverflow.com/a/49857235
answers question: http://stackoverflow.com/q/49857105
has body: You can try something like that: from subprocess import check_output import shlex output = check_output(shlex.split(your_command_as_string)) In case your program does not accept password as command line argument, you can use following method: import subprocess import shlex prog = subprocess.Popen( shlex.split(your_command_as_string), stdin=subprocess.PIPE ) # run program with piped stdin for password in your_passwords: prog.stdin.write("{}\n".format(password)) # feed password if prog.Poll() is not None: # check if program finished print(password) break
score: 0
type: Answer

http://stackoverflow.com/comment/86807912
type: QuestionComment
type: Comment
has text: I added the new traceback error and found this answer to the issue at hand, which solved my problem.
comment on: http://stackoverflow.com/q/49883992
score: 0

http://stackoverflow.com/comment/86826653
type: Comment
type: QuestionComment
score: 0
has text: There is 400 Bad Request error in every file. Links are ok when I open them. Tried to time.sleep but didnt help.
comment on: http://stackoverflow.com/q/49904801

http://stackoverflow.com/q/49837963
has title: Selenium Python unable to click on a select button
has comment: http://stackoverflow.com/comment/86785900
has comment: http://stackoverflow.com/comment/86701498
tagged with: python
has comment: http://stackoverflow.com/comment/86782704
has comment: http://stackoverflow.com/comment/86784738
has comment: http://stackoverflow.com/comment/86783589
has comment: http://stackoverflow.com/comment/86701160
has comment: http://stackoverflow.com/comment/86693812
tagged with: element
answer count: 0
has body: I'm practicing my automation skills and trying to automate around the Amazon website. Currently, I'm having issues where my automation test script won't click on the select button so then the drop-down list will display the variety of sizes for its items. Is there any other options I can use so then Selenium can click on the button? I tried the following method but no luck. driver.find_element_by_css_selector('#dropdown_selected_size_name > span > span').click() Here is the HTML I'm trying to test: //*[@id="dropdown_selected_size_name"]/span/span. Select 18 oz (532 ml) Standard Mouth 21 oz (621 ml) Standard Mouth 24 oz (710 ml) Standard Mouth 12 oz (354 ml) Standard Mouth additional htmls #variation_size_name > span.twister-dropdown-highlight.transparentTwisterDropdownBorder > span Select 18 oz (532 ml) Standard Mouth 21 oz (621 ml) Standard Mouth 24 oz (710 ml) Standard Mouth 12 oz (354 ml) Standard Mouth Select Element I want to select: 21 oz (621 ml) Standard Mouth
has comment: http://stackoverflow.com/comment/86704420
score: 1
has comment: http://stackoverflow.com/comment/86782367
downvote count: 0
tagged with: selenium
upvote count: 1
has comment: http://stackoverflow.com/comment/86865514
has comment: http://stackoverflow.com/comment/86701520
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86785023
type: UnansweredQuestion

http://stackoverflow.com/comment/86627490
has text: crypt.h is part of the libc. maybe you should install "libc-dev" even if it might be part of clang package...
type: Comment
comment on: http://stackoverflow.com/q/49805480
score: 0
type: QuestionComment

http://stackoverflow.com/q/49905851
tagged with: image-processing
has body: import cv2 import numpy as np cap = cv2.VideoCapture(0) while(1): # Take each frame _, frame = cap.read() # frame olarak goruntuyu aldık # BGR ' yi HSV ye çevirdik hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # HSV nin içindeki renk aralıgını belirledik lower_yellow = np.array([20,0,0]) upper_yellow = np.array([40,255,255]) # Yukarıda belırledıgımız eşik değerlerini gray goruntunun içinde eşleştirdik. mask = cv2.inRange(hsv, lower_yellow, upper_yellow) # bitwise and operatörü ile de ana goruntude yukarıda buldugumuz mask'i aldık. res = cv2.bitwise_and(frame,frame, mask= mask) img = cv2.medianBlur(res, 5) cimg = cv2.cvtColor(img, cv2.COLOR_HSV2BGR) cimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 5, 20, param1=50, param2=30, minRadius=0, maxRadius=10) circles = np.uint16(np.around(circles)) for i in circles[0, :]: # draw the outer circle cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2) # draw the center of the circle cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3) cv2.imshow('detected circles', cimg) #ayarladıgımız 3 görüntüyü gösterdik cv2.imshow('res',res) k = cv2.waitKey(5) &amp; 0xFF if k == 27: break cv2.destroyAllWindows() When I run , There is a error called : cv2.error: /io/opencv/modules/imgproc/src/hough.cpp:1494: error: (-215) !_image.empty() &amp;&amp; _image.type() == (((0) &amp; ((1 &lt;&lt; 3) - 1)) + (((1)-1) &lt;&lt; 3)) &amp;&amp; (_image.isMat() || _image.isUMat()) in function HoughCircles I want to find circle on video .
downvote count: 1
favorite count: 0
has title: Hough Circle Transform on Video
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/59443650
has answer: http://stackoverflow.com/a/59443650
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49906519
has comment: http://stackoverflow.com/comment/86828481
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49906519
score: 0
tagged with: hough-transform

http://stackoverflow.com/comment/86666063
type: AnswerComment
comment on: http://stackoverflow.com/a/49825013
score: 0
type: Comment
has text: I've shown you this in the second snippet, simply add more arguments to format

http://stackoverflow.com/comment/86547049
type: Comment
has text: One possibility is to look into [pandas](https://pandas.pydata.org/pandas-docs/stable/index.html). You'd be able to accomplish this within a few lines without a loop. It's very well suited to manipulate data like this.
type: QuestionComment
comment on: http://stackoverflow.com/q/49765676
score: 0

http://stackoverflow.com/a/49902401
downvote count: 0
answers question: http://stackoverflow.com/q/49896377
score: 2
type: Answer
has body: If you add print statements for xnew in the errorfunc then you will see that fsolve works with a list (of one element). This means that the function is re-interpreted that way, not the original function. Somehow the type information is lost after exiting the solver so that then the address/reference to that list is interpreted as floating point data, which gives the wrong value. Setting self.x = xnew[0] there restores the desired behavior.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49896377
type: AcceptedAnswer

http://stackoverflow.com/q/49836552
score: 1
upvote count: 1
has title: How to test Exception in signal?
tagged with: unit-testing
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49837784
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49838120
tagged with: django
tagged with: python
has body: I have a signal: create_flat_referral = django.dispatch.Signal(providing_args=["request", "user"]) And I have a receiver: @receiver(create_flat_referral, sender=None) def save_flat_referral(sender, request, user, **kwargs): referral_link = request.POST.get('referral', None) if not referral_link: referral_link = request.GET.get('ref', None) try: if referral_link: link = Link.objects.get(token = referral_link) referral = FlatReferral.objects.create( referrer = link.user, referred = user ) except Link.DoesNotExist: logger.exception('...') except ValidationError: logger.exception('...') I want to cover all the exceptions with the tests. In addition to what I want to get assertRaises, I also want to get assertRaisesMessage What's the best way to do this? If I'm trying to do something like this: self.assertRaises( ValidationError, lambda: signals.create_flat_referral.send( sender = None, request = post_request, user = self.referred ) ) That I fail the test: AssertionError: ValidationError not raised by lambda
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/86713777
has text: Please read about the `lambda` feature in the official language tutorial: https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions and the documentation for the `sorted` function: https://docs.python.org/3/library/functions.html?highlight=sorted#sorted and try again if you have a more specific question. "Please help me understand this code" is usually not a good question for SO.
comment on: http://stackoverflow.com/q/49849589
score: 0
type: Comment
type: QuestionComment

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/49913043
tags question: http://stackoverflow.com/q/49846516

http://stackoverflow.com/comment/86827177
type: AnswerComment
comment on: http://stackoverflow.com/a/49903753
has text: a feature vector, from some ML model, like the house prices in your town.
type: Comment
score: 0

http://stackoverflow.com/comment/86627301
score: 0
has text: @LeeDanielCrocker, by "valid," I mean that the terminal is able to produce an effect that is consistent with the Unicode description of the corresponding character. For most defined characters, this would be placing a graphical representation of the character at the cursor position.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49785638

http://stackoverflow.com/q/49760595
tagged with: django
tagged with: python
has title: Ubuntu Nginx uwsgi socket not work
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/103331241
score: 2
has comment: http://stackoverflow.com/comment/86544455
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/88498059
tagged with: uwsgi
favorite count: 0
type: Question
upvote count: 2
has body: I am trying to set up my Django(2.0) project with nginx and uwsgi, but it just fails when running: uwsgi --socket :8001 --wsgi-file test.py which follows https://uwsgi.readthedocs.io/en/latest/tutorials/Django_and_nginx.html it's failed, can not connect server , but uwsgi --http :8000 --wsgi-file test.py is ok here is my uwsgi log: (venv) ubuntu@VM-49-116-ubuntu:~/code/blog/mmxy$ uwsgi --socket :8001 --wsgi-file test.py *** Starting uWSGI 2.0.17 (64bit) on [Wed Apr 11 02:19:40 2018] *** compiled with version: 5.4.0 20160609 on 09 April 2018 17:37:14 os: Linux-4.4.0-91-generic #114-Ubuntu SMP Tue Aug 8 11:56:56 UTC 2017 nodename: VM-49-116-ubuntu machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/ubuntu/code/blog/mmxy detected binary path: /home/ubuntu/code/blog/venv/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 3306 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to TCP address :8001 fd 3 Python version: 3.6.4 (default, Apr 10 2018, 00:02:46) [GCC 5.4.0 20160609] *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0xe92290 your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 72920 bytes (71 KB) for 1 cores *** Operational MODE: single process *** WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0xe92290 pid: 8870 (default app) *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 8870, cores: 1) nginx conf: upstream django { # server unix:///tmp/mmxy.sock; server 127.0.0.1:8001; # for a web port socket (we'll use this first) } server { list…
tagged with: nginx
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86542293

http://stackoverflow.com/q/49773491
has comment: http://stackoverflow.com/comment/86562582
has title: Neural Networks Time Series Classification
tagged with: time-series
type: Question
has body: I just started reading about neural nets, and stumbled upon an intersting project from this article which i'm trying to replicate using Keras in python. I'm stuck a bit on underinging the issue on a High-Level. My question is regarding what exactly the input features in a time series in such a case are. what i'm trying to do is classify very specific patterns in a time series (of unknown lenght), in this case is each value in the time series a feature (so if i have 10 points i have 10 nodes in my input) or is it a 1D array with the values? In the paper it seems that each input node represents a specific point in time, but what doesn't make sense is that if this is the proper setup, how do i deal if my time series has 10+ points (obviously i can't dynamically add nodes). Just need a bit of guidance as i am not sure where to look for an answer. Thank you for your time.
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86562072
score: 0
tagged with: neural-network
answer count: 0

http://stackoverflow.com/q/49861354
linked to: http://stackoverflow.com/q/13352280
tagged with: scipy
tagged with: sparse-matrix
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/14491548
has body: Is there a way to select the rows corresponding to some given indices in a scipy sparse matrix? The dummy approach does not work: sparse.eye(3)[:2, :] returns TypeError: 'dia_matrix' object is not subscriptable
accepted answer: http://stackoverflow.com/a/49863234
tagged with: python
has answer: http://stackoverflow.com/a/49863234
has comment: http://stackoverflow.com/comment/86738651
type: AnsweredQuestion
score: 0
has title: Selecting rows in scipy sparse matrix
upvote count: 2
downvote count: 2
answer count: 1

linux
tags question: http://stackoverflow.com/q/49766192
tags question: http://stackoverflow.com/q/49778805
tags question: http://stackoverflow.com/q/49813003
tags question: http://stackoverflow.com/q/49772156
tags question: http://stackoverflow.com/q/49806070
tags question: http://stackoverflow.com/q/49795352
tags question: http://stackoverflow.com/q/49871192
tag name: linux
tags question: http://stackoverflow.com/q/49813012
tags question: http://stackoverflow.com/q/49790960
tags question: http://stackoverflow.com/q/49837756
tags question: http://stackoverflow.com/q/49810184
tags question: http://stackoverflow.com/q/49851913
tags question: http://stackoverflow.com/q/49800656
tags question: http://stackoverflow.com/q/49897527
tags question: http://stackoverflow.com/q/49824504
tags question: http://stackoverflow.com/q/49839787
tags question: http://stackoverflow.com/q/49780822
tags question: http://stackoverflow.com/q/49798741
tags question: http://stackoverflow.com/q/49884433
tags question: http://stackoverflow.com/q/49866943
tags question: http://stackoverflow.com/q/49889702
tags question: http://stackoverflow.com/q/49826834
tags question: http://stackoverflow.com/q/49889279
tags question: http://stackoverflow.com/q/49906994
tags question: http://stackoverflow.com/q/49840045
tags question: http://stackoverflow.com/q/49806893
type: Tag
tags question: http://stackoverflow.com/q/49797295
tags question: http://stackoverflow.com/q/49874711
tags question: http://stackoverflow.com/q/49761229
tags question: http://stackoverflow.com/q/49771406
tags question: http://stackoverflow.com/q/49860522
tags question: http://stackoverflow.com/q/49812650
tags question: http://stackoverflow.com/q/49908444

http://stackoverflow.com/a/49789165
has comment: http://stackoverflow.com/comment/105989201
has body: Use str.strip if strings: print (type(df.loc[0, 'From'])) &lt;class 'str'&gt; df['From'] = df['From'].str.strip('[]') ... and if lists convert them by str.join: print (type(df.loc[0, 'From'])) &lt;class 'list'&gt; df['From'] = df['From'].str.join(', ') Thank you @juanpa.arrivillaga for suggestion if one item lists: df['From'] = df['From'].str[0] what is possible check by: print (type(df.loc[0, 'From'])) &lt;class 'list'&gt; print (df['From'].str.len().eq(1).all()) True print (df) From TO 0 wrestle engage in a wrestling match 1 write communicate or express by writing 2 write publish 3 spell write 4 compose write music
answers question: http://stackoverflow.com/q/49789135
has comment: http://stackoverflow.com/comment/105989088
type: Answer
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/86593601
downvote count: 0
has comment: http://stackoverflow.com/comment/86593469

http://stackoverflow.com/q/49888437
downvote count: 2
has answer: http://stackoverflow.com/a/49889327
has comment: http://stackoverflow.com/comment/86792986
tagged with: python
tagged with: properties
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86793574
accepted answer: http://stackoverflow.com/a/49889327
possible better answer: http://stackoverflow.com/a/49888550
score: 1
has answer: http://stackoverflow.com/a/49888550
has body: What is the cleanest way to define a class with a large number of properties, each of which calls the same setter function with a different parameter? Below is what I'm trying to achieve. Each of the three properties (red_LED etc) call the same TalkToHardware() function when they are set, but with a different address. As you can see, this works, but the class definition is long and unwieldy. It is also error prone. class Hardware_Controller(object): def __init__(self): self.red_LED_address = 0 self.blue_LED_address = 1 self.green_LED_address = 2 @property def red_LED(self): return self._red_LED_status @red_LED.setter def red_LED(self,value): self.TalkToHardware(self.red_LED_address,value) self._red_LED_status = value @property def blue_LED(self): return self._red_LED_status @blue_LED.setter def blue_LED(self,value): self.TalkToHardware(self.blue_LED_address,value) self._blue_LED_status = value @property def green_LED(self): return self._red_LED_status @green_LED.setter def green_LED(self,value): self.TalkToHardware(self.green_LED_address,value) self._green_LED_status = value def TalkToHardware(self,address,value): print('Sending %i to address %i' % (value,address)) if __name__ == "__main__": a = Hardware_Controller() a.red_LED = 1 a.green_LED = 0 print(a.red_LED) Output: Sending 1 to address 0 Sending 0 to address 2 1 I would like the class definition to look more like this: class Hardware_Controller(object): def __init__(self): self.red_LED_address = 0 self.blue_LED_address = 1 self.green_LED_address = 2 self.red_LED = some_magic(self.red_LED_address) self.blue_LED = some_magic(self.blue_LED_address) self.green_LED = some_magic(self.green_LED_address) def some_magic(address): # Do magic things pass Is there a clean way to accomplish this, still being able to access each of the LEDs directly as shown in the main function of the first example?
has comment: http://stackoverflow.com/comment/86794573
type: Question
answer count: 2
upvote count: 3
has title: Multiple properties with similar getter/setter functions?

http://stackoverflow.com/comment/86829795
score: 0
comment on: http://stackoverflow.com/q/49905849
type: Comment
type: QuestionComment
has text: Well either you could be patient and or probably set them to half the size of the validation set (I think 6000 images should be enough for you to get an estimation epoch-by-epoch to get a feel on your model's progress).

http://stackoverflow.com/a/60957902
answers question: http://stackoverflow.com/q/49864209
has comment: http://stackoverflow.com/comment/107859613
type: Answer
score: 0
has body: flask run --host=127.0.0.1 --port=8080

http://stackoverflow.com/q/49913996
has comment: http://stackoverflow.com/comment/86843960
has comment: http://stackoverflow.com/comment/86844104
answer count: 1
has comment: http://stackoverflow.com/comment/86844204
has comment: http://stackoverflow.com/comment/86843719
tagged with: django
linked to: http://stackoverflow.com/q/12848605
tagged with: django-forms
tagged with: django-rest-framework
has body: I am having an issue in setting the user automatically in django rest framework. In my models.py I have the following: Models.py class Space(models.Model): creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Serializers.py class SpaceSerializer(serializers.HyperlinkedModelSerializer): creator = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CreateOnlyDefault(serializers.CurrentUserDefault())) class Meta: model = Space fields = '__all__' The intent is that the creator field will be set during creation through the API. When I issue a POST request to create the model, i get the following error: "IntegrityError at /api/space/ NOT NULL constraint failed: apiapp_space.creator_id I assume the serializer is not even using this field override, as when I set null=True in my model, it seems to save correctly with the creator field set to null. Note that I have also tried using serializers.ModelSerializer. How can I get django to recognize this field override?
has answer: http://stackoverflow.com/a/49915503
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49915503
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/86844662
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has title: Django not recognizing field override for Current User in Serializer

http://stackoverflow.com/q/49792096
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: R/apcluster and skilearn
tagged with: python
has answer: http://stackoverflow.com/a/49821430
tagged with: http://stackoverflow.com/tag/r
score: 1
has body: I have been involved in analysis using a software called depict which includes affinity propagation analysis in Python. I am keen to implement a counterpart using R/apcluster for additional analysis. It seems both use correlation but the results are slightly different. Is that possible to get to the bottom of this? Thanks very much. af_obj = AffinityPropagation(affinity = 'precomputed', max_iter=10000, convergence_iter=1000) # using almost only default parameters print "Affinity Propagation parameters:" for param, val in af_obj.get_params().items(): print "\t{}: {}".format(param, val) print "Perfoming Affinity Propagation.." af = af_obj.fit(matrix_corr) as in Python: https://github.com/jinghuazhao/PW-pipeline/blob/master/files/network_plot.py require(apcluster) apres &lt;- apcluster(corSimMat,tRaw,details=TRUE) as in R: https://github.com/jinghuazhao/PW-pipeline/blob/master/files/network.R J Jing hua

http://stackoverflow.com/comment/128403492
type: Comment
has text: @ely I disagree with your claim that dataclasses must be completely logic-free containers. Consider a frozen dataclass modeling a 2D triangle, for example, where you might want a method for computing the area, and validation that the triangle is not degenerate (no collinear vertices). What better place to put the validation than in a post-init hook?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50319825

http://stackoverflow.com/comment/86647957
has text: If you google "Electron with Python" there are tutorials that pop up...
comment on: http://stackoverflow.com/q/49816446
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/49865790
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49860435
tagged with: conditional-statements
tagged with: if-statement
tagged with: pandas
tagged with: group-by
has body: Piggy backing off this question python pandas new column categorization based on conditions in other columns #code to re-create my example date df = pd.DataFrame({'customer_id': ['abc','abc','xyz','xyz','xyz','xyz','thr','thr','abc','abc','urt','urt'], 'transaction_id': ['A123','A123','B345','B345','C567','C567','D678','D678','E789','E789','D903','F865'], 'product_id': [255472, 251235, 253764,257344,221577,209809,223551,290678,908354,909238,436758,346577], 'product_category': ['X','X','Y','Y','X','Y','Y','X','Y','Z','X','X']}) #example data customer_id| transaction_id | product_id | product_category abc A123 255472 X abc A123 251235 X xyz B345 253764 Y xyz B345 257344 Y xyz C567 221577 X xyz C567 209809 Y thr D678 223551 Y thr D678 290678 X abc E789 908354 Y abc E789 909238 Z urt D903 436758 X urt F865 346577 X I want to flag all customer_ids that have X and Y in different transactions (not in the same transaction). #expected output customer_id| transaction_id | product_id | product_category | flag abc A123 255472 X 1 abc A123 251235 X 1 xyz B345 253764 Y 0 xyz B345 257344 Y 0 xyz C567 221577 X 0 xyz C567 209809 Y 0 thr D678 223551 Y 0 thr D678 290678 X 0 abc E789 908354 Y 1 abc E789 909238 Z 1 urt D903 436758 X 0 urt F865 346577 X 0 I couldn't come up with a clean solution. In the example above, we have customer abc who has a transaction with only product category X and then a transaction with product category Y and Z. This is the customer I want to flag, they had X and Y, but in different transaction_ids. One way of doing it I thought of would be to use the code from my previous answer: df['pre_flag']=df.groupby('transaction_id')['product_category'].transform(lambda x: x + ' only' if len(set(x)) &lt; 2 else ' &amp; '.join(set(x))) And then split the dataset into two: df_1 = df.loc[df['pre_flag'] == 'X&amp;Y'].copy() df_2 = df.loc[df['pre_flag'] != 'X&amp;Y'].copy() ... and use an isin statement; but this is very messy; there must be a better approach. Thank You!
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/49867410
score: 0
has title: Python pandas if statement based on two conditions
answer count: 1
has answer: http://stackoverflow.com/a/49867410
has comment: http://stackoverflow.com/comment/86871156

http://stackoverflow.com/q/49781435
has comment: http://stackoverflow.com/comment/86579024
has comment: http://stackoverflow.com/comment/86578914
favorite count: 0
type: Question
has title: csv file turkish characters not showing
has comment: http://stackoverflow.com/comment/86582046
has comment: http://stackoverflow.com/comment/86579474
has answer: http://stackoverflow.com/a/49790355
has comment: http://stackoverflow.com/comment/86585122
tagged with: encoding
has comment: http://stackoverflow.com/comment/86582511
has comment: http://stackoverflow.com/comment/86578820
has comment: http://stackoverflow.com/comment/86578623
has comment: http://stackoverflow.com/comment/86579494
has comment: http://stackoverflow.com/comment/86579280
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86578978
has comment: http://stackoverflow.com/comment/86594792
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/49790355
has comment: http://stackoverflow.com/comment/86578659
upvote count: 3
has comment: http://stackoverflow.com/comment/86598721
has comment: http://stackoverflow.com/comment/86579455
has comment: http://stackoverflow.com/comment/86579576
answer count: 1
has comment: http://stackoverflow.com/comment/86579635
downvote count: 0
linked to: http://stackoverflow.com/q/904041
has body: I am importing csv file to django model with below commands: if request.method == 'POST' and request.FILES['csv_file2']: myfile = request.FILES['csv_file2'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) data = csv.reader(fs.open(filename, mode='r')) The problem that I am having that I can't see turkish characters. I searched at stackoverflow and I need to add utf-8 encoding while reading the csv file ,I tried several examples that I found but I couldn't make it work anywhere I tried to add encoding in my codes. Where should I add ?
tagged with: utf-8

http://stackoverflow.com/a/49860833
type: Answer
accepted answer of: http://stackoverflow.com/q/49860688
downvote count: 0
score: 1
upvote count: 1
has body: This seems indeed to be a bug on your machine. On my machine (Python 3.6.3 in Ubuntu 17.10) negative numbers work correctly as UTC time-stamp. As a workaround you can try datetime.datetime.toordinal and datetime.datetime.fromordinal. The ordinals start on January 1, 0001 and should therefore be able to cover your date range using only positive numbers: import datetime start = datetime.datetime(1830, 1, 1) event_1 = datetime.datetime(1835, 2, 10) diff = (event_1 - start).days # 1866 datetime.datetime.fromordinal(start.toordinal() + diff) # datetime.datetime(1835, 2, 10, 0, 0)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86766455
answers question: http://stackoverflow.com/q/49860688

http://stackoverflow.com/a/49897476
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: try replacing if self.Qn &lt; self.recordNum: with if self.Qn &lt; self.recordNum['text']:
has comment: http://stackoverflow.com/comment/86854480
accepted answer of: http://stackoverflow.com/q/49897336
type: Answer
has comment: http://stackoverflow.com/comment/86811476
answers question: http://stackoverflow.com/q/49897336

http://stackoverflow.com/q/49865761
linked to: http://stackoverflow.com/q/37098546
score: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/86773926
has comment: http://stackoverflow.com/comment/86765433
linked to: http://stackoverflow.com/q/46705354
has body: I am learning tensorflow and i found a code online in which they used get_variable() in it. What is this function? Like this line of code: W1 = tf.get_variable("W1", [25, 122], initializer = tf.contrib.layers.xavier_initializer()) And also what this initializer is doing in it?
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/86746879
answer count: 0
has title: What is get_variable in tensorflow?
type: UnansweredQuestion
tagged with: neural-network
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/comment/86823746
type: Comment
score: 0
type: AnswerComment
has text: Thank you. But I have another clarification, what if I want to select only two csv files from a folder which contains more than 3 csv files.
comment on: http://stackoverflow.com/a/49903761

http://stackoverflow.com/comment/129328206
type: AnswerComment
has text: While using the 2nd option, I was getting an error `traitlets.traitlets.TraitError: The 'remove_cell_tags' trait of a TagRemovePreprocessor instance must be a set, but a value of class 'str' (i.e. '{"hide_code"}') was specified.`. I had to amend it to `jupyter nbconvert --to html --TagRemovePreprocessor.remove_cell_tags={\"hide_code\"} my-notebook.ipynb` to make it work. Note that the first single quotes were removed and I had to use the escape backslash before each double quote.
comment on: http://stackoverflow.com/a/72462601
score: 0
type: Comment

http://stackoverflow.com/comment/86675645
type: Comment
has text: @Aayush That's too much to explain here. Take a look at [list comprehensions](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) and [lambda functions](https://stackoverflow.com/questions/13669252/what-is-key-lambda). The code `(isinstance(v, str), v)` creates a tuple where the first element is a boolean (the result of `isinstance(v, str)`) and the second element is `v`.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49829913

http://stackoverflow.com/q/49847953
has comment: http://stackoverflow.com/comment/86711539
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86711977
answer count: 1
has title: what does parameters = int(theta.ravel().shape[1]) mean?
has comment: http://stackoverflow.com/comment/86710811
type: AnsweredQuestion
upvote count: 0
has body: Can someone explain that code for me? def gradientDescent(X, y, theta, alpha, iters): temp = np.matrix(np.zeros(theta.shape)) parameters = int(theta.ravel().shape[1]) cost = np.zeros(iters) for i in range(iters): error = (X * theta.T) - y for j in range(parameters): term = np.multiply(error, X[:,j]) temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term)) theta = temp cost[i] = computeCost(X, y, theta) return theta, cost
tagged with: gradient-descent
has answer: http://stackoverflow.com/a/49848342
accepted answer: http://stackoverflow.com/a/49848342
tagged with: linear-regression
has comment: http://stackoverflow.com/comment/86710870
downvote count: 1
tagged with: python
score: -1

http://stackoverflow.com/q/49835842
tagged with: docker
type: AnsweredQuestion
has body: I'm trying to use Docker to create a dependency package for AWS Lambda using this repository, but whenever I try to run the build.sh file, I end up with the message: no such option: --use-wheel Then when I try to use pip install wheel (outside of Docker), I'm told that it's already on my local machine, which it is. How do I install Wheel in the Docker container? If it's helpful, this appears to be the line of code in build.sh that is giving the issue: test -f /outputs/requirements.txt &amp;&amp; pip install --use-wheel -r /outputs/requirements.txt Any help is much appreciated!
downvote count: 0
has answer: http://stackoverflow.com/a/49835917
accepted answer: http://stackoverflow.com/a/49835917
has title: Docker: no such option: --use-wheel
favorite count: 0
type: Question
answer count: 2
tagged with: python-wheel
possible better answer: http://stackoverflow.com/a/50171690
tagged with: pip
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/50171690
score: 4
tagged with: dockerfile

http://stackoverflow.com/comment/86656746
type: QuestionComment
has text: Thank you. Do you mean read the CSV and just select the column "mandados" and the desired columns within it?
score: 0
comment on: http://stackoverflow.com/q/49820691
type: Comment

http://stackoverflow.com/q/49758189
has answer: http://stackoverflow.com/a/49760073
downvote count: 0
has comment: http://stackoverflow.com/comment/86536457
tagged with: python-trio
favorite count: 0
type: AnsweredQuestion
has title: async trio way to solve Hettinger's example
accepted answer: http://stackoverflow.com/a/49760073
has body: Raymond Hettinger gave a talk on concurrency in python, where one of examples looked like that: import urllib.request sites = [ '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/', ] for url in sites: with urllib.request.urlopen(url) as u: page = u.read() print(url, len(page)) Essentially we go after these links and print amount of received bytes and it takes about 20 seconds to run. Today I found trio library that has quite friendly api. But when I am trying to use it with this rather basic example I am failing to do it right. first try (runs around the same 20 seconds): import urllib.request import trio, time sites = [ '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 show_len(sites): t1 = time.time() for url in sites: with urllib.request.urlopen(url) as u: page = u.read() print(url, len(page)) print("code took to run", time.time() - t1) if __name__ == "__main__": trio.run(show_len, sites) and second one (same speed): import urllib.request import trio, time sites = [ '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 link_user(url): with urllib.reque…
tagged with: python
tagged with: asynchronous
score: 12
type: Question
upvote count: 12
answer count: 2
has answer: http://stackoverflow.com/a/70675488
possible better answer: http://stackoverflow.com/a/70675488

http://stackoverflow.com/a/49896196
type: Answer
answers question: http://stackoverflow.com/q/49895190
downvote count: 0
has body: You could try to decorate your module like this: class ReloadingModule: def __init__(self, module): self.module = module def __getattr__(self, attr): print("reloading {}...".format(self.module.__name__)) imp.reload(self.module) return getattr(self.module, attr) import this this = ReloadingModule(this) print('\n\n',this.c, '\n\n') print('\n\n',this.s, '\n\n') Output: reloading this... The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. [...] 97 reloading this... The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. [...] Gur Mra bs Clguba, ol Gvz Crgref Ornhgvshy vf orggre guna htyl. Rkcyvpvg vf orggre guna vzcyvpvg. Fvzcyr vf orggre guna pbzcyrk. [...] With some math: import math math = ReloadingModule(math) print(math.pi) print(math.sin(math.pi/2)) Output: reloading math... 3.141592653589793 reloading math... reloading math... 1.0
score: 3
upvote count: 3

http://stackoverflow.com/comment/86750515
has text: what do you think?
type: Comment
comment on: http://stackoverflow.com/a/49866022
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86745515
comment on: http://stackoverflow.com/a/49865070
has text: Shouldn't need to escape forward slashes in a python regex. See here: https://regex101.com/r/xNg1mr/2 The main issue he is facing is the lack of the multiline flag.
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/q/49888252
answer count: 1
downvote count: 0
tagged with: du
has comment: http://stackoverflow.com/comment/135459225
upvote count: 1
favorite count: 0
type: Question
tagged with: stat
has body: Before I start, I don't have a lot of knowledge in terms of file system behaviors, and so any explanations/hypothesis will greatly help. Premise I have ~3 million files I wanted to find spread across a giant NFS file system. The file system itself has probably ~50-100 million files. The 3 million files are listed by their parent directories. I tried running find to find all the necessary files, and it was MUCH faster than os.walk, or os.scandir, taking at least 4-5x less time. I needed find to find symlinks. I tried calling du, to find the size of the directories recursively. This took forever - a single call on a big directory took me more than 5 minutes. In comparison to a ext4fs, which took maybe a couple seconds at most, this was much worse. I tried to find mtimes and ctimes using os.stat, and this took the longest - to find all 3 million files it takes me ~40 minutes. The file system is organized in such a way that file sizes are not by themselves huge (low variance), but the number of files under a directory greatly varies. Question I know that find uses fts underneath, but why does it run so much faster? Is there a faster alternative to using os.stat or os.scandir in python for the same purpose(finding mtimes/ctimes)?
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/52873963
tagged with: nfs
tagged with: filesystems
has title: Why is find so much faster than os.walk on large NFS? How to improve traversal speeds on NFS
type: UnansweredQuestion

http://stackoverflow.com/comment/86750493
score: 0
comment on: http://stackoverflow.com/q/49867434
type: Comment
type: QuestionComment
has text: Mostly I've ignored this warning. Newer `ipython` versions` have changed the message to something like `1.05 ms ± 498 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)`, letting us interpret the `std. dev.` for ourselves.

http://stackoverflow.com/a/49839338
has comment: http://stackoverflow.com/comment/86695661
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49837578
has body: You have to place await bot.process_commands(message) outside of the if statement scope, process_command should be run regardless if the message startswith ”/lockdown”. @bot.event async def on_message(message): if message.content.startswith('/lockdown'): ... await bot.process_commands(message) By the way, @commands.has_role(...) cannot be applied to on_message. Although there aren't any errors (because there’s checking in place), has_role wouldn't actually work as you would've expected. An alternative to the @has_role decorator would be: @bot.event async def on_message(message): if message.channel.is_private or discord.utils.get(message.author.roles, name="Admin") is None: return False if message.content.startswith('/lockdown'): ... await bot.process_commands(message)
accepted answer of: http://stackoverflow.com/q/49837578
has comment: http://stackoverflow.com/comment/86728671
has comment: http://stackoverflow.com/comment/86695472
score: 10
upvote count: 10
has comment: http://stackoverflow.com/comment/86693741
type: Answer
has comment: http://stackoverflow.com/comment/86698118
downvote count: 0

http://stackoverflow.com/comment/86738918
comment on: http://stackoverflow.com/a/49861739
has text: I'm not really sure what you're asking here, can you give an example please?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/86852401
type: QuestionComment
score: 0
has text: Is your file sorted?
comment on: http://stackoverflow.com/q/49908444
type: Comment

http://stackoverflow.com/a/49889746
accepted answer of: http://stackoverflow.com/q/49790580
answers question: http://stackoverflow.com/q/49790580
score: 5
type: AcceptedAnswer
downvote count: 0
has body: PipelineOptions uses argparse behind the scenes to parse its argument. In the case of machine type, the name of the argument is machine_type however the flag name is worker_machine_type. This works fine in the following two cases, where argparse does its parsing and is aware of this aliasing: Passing arguments on the commandline. e.g. my_pipeline.py --worker_machine_type custom-1-6656 Passing arguments as a command line flags e.g. flags['--worker_machine_type', 'worker_machine_type custom-1-6656', ...] However it does not work well with **kwargs. Any additional args passed in that way are used to substitute for known argument names (but not flag names). In short, using machine_type would work everywhere. I filed https://issues.apache.org/jira/browse/BEAM-4112 for this to be fixed in Beam in the future.
upvote count: 5
type: Answer

http://stackoverflow.com/comment/86670864
has text: updated code i forget to add two imports. and no space in `jpgfiles.sort()`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49827668
type: Comment

http://stackoverflow.com/comment/86827099
score: 0
has text: @IMCoins I think I'm searching for functionality that doesn't exist. My problem is that the change in HTML I'm looking for is prompted by me receiving a cookie. The way the cookie is generated is if I'm on the website for a certain period of time (e.g. 1 hour), so that is why I would like to be able to keep a request open (as if I'm actually on the website), and check for those changes. Selenium isn't lightweight enough unfortunately.
type: Comment
comment on: http://stackoverflow.com/q/49879471
type: QuestionComment

http://stackoverflow.com/a/49889489
has body: The only thing that seemed unclear in your code was the double-for-loop. It may be clearer to collapse the demandlist into a flat iterable—then the loopant presents the logic as simply as possible. Consider: demandlist = [{ u'2018-04-29': 1, u'2018-04-30': 1, u'2018-05-01': 1 }, { u'2018-04-21': 1 }, { u'2018-04-18': 1, u'2018-04-19': 1, u'2018-04-17': 1 }] import itertools as it from collections import defaultdict demandresult = defaultdict(int) for k, v in it.chain.from_iterable(map(lambda d: d.items(), demandlist)): demandresult[k] = demandresult[k] + v (With this, print(demandresult) prints defaultdict(&lt;class 'int'&gt;, {'2018-04-29': 1, '2018-04-30': 1, '2018-05-01': 1, '2018-04-21': 1, '2018-04-18': 1, '2018-04-19': 1, '2018-04-17': 1}).) Imagining myself reading this for the first time (or a few months later), I can see myself thinking, "Ok, I'm collapsing demandlist into a key-val iterable, I don't particularly care how, and then summing values of matching keys." It's unfortunate that I need that map there to ensure the final iterable has key-val pairs… it.chain.from_iterable(demandlist) is a key-only iterable, so I need to call items on each dict. Note that unlike many of the answers proposed, this implementation (like yours!) minimizes the number of scans over the data to just one—performance win (and I try to pick up as many easy performance wins as I can).
answers question: http://stackoverflow.com/q/49889225
score: 0
type: Answer

http://stackoverflow.com/comment/86643912
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49798330
has text: @Kanguros, I tried that, but it does not make any difference. Actually, in my question you can see that the `PUT` request is being sent to the right `devpi` server, but somehow the server refuses to complete the request.

http://stackoverflow.com/comment/86782700
type: Comment
type: QuestionComment
has text: Does your graphenedb instance have SSL enabled? If so, you'll need to specify that in your connection by passing `secure=True` to your `Graph()` initialization.
score: 0
comment on: http://stackoverflow.com/q/49883223

http://stackoverflow.com/comment/86562528
has text: You could use a [PY3__cmp__ mixin class](https://stackoverflow.com/a/39166382/4349415)
comment on: http://stackoverflow.com/q/49773657
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86701637
has text: @at KeerthiBachu Thank you for answering...I tested your code...you are too damnn close to output...I studied your code ..but I couldn't got the output too. Still ..thanks again ....lets see if anyone answer it with 100% accuracy..
type: AnswerComment
comment on: http://stackoverflow.com/a/49829598
type: Comment
score: 0

http://stackoverflow.com/comment/86620354
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49802811
has text: This question would be better asked on [su]
score: 0

http://stackoverflow.com/q/49868038
has answer: http://stackoverflow.com/a/49868150
accepted answer: http://stackoverflow.com/a/49868150
tagged with: python
has title: can someone explain what are the '+' and '-' in the error output of pytest?
type: Question
has body: in the example below, can someone please explain what does the '-' and '+' are for? import pytest assert 'foo 1 bar' == 'foo 2 bar' E – foo 1 bar E ? ^ bar E + foo 2 bar E ? ^
upvote count: 2
answer count: 1
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: pytest
score: 1

http://stackoverflow.com/comment/86542486
type: AnswerComment
has text: Ah that's smarter, I guess you don't really need the dictionary in this case
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49763334

http://stackoverflow.com/q/49915577
has body: Suppose I have a data frame which has 5 rows of data. I want to make 4 duplicate set of same data frame. Input col1 col2 a 1 b 2 c 3 d 4 e 5 Output: col1 col2 a 1 b 2 c 3 d 4 e 5 a 1 b 2 c 3 d 4 e 5 a 1 b 2 c 3 d 4 e 5 a 1 b 2 c 3 d 4 e 5 for example in python if i have a string s='-' to make duplicate I could do something like this print s*4. I want similar functionality in pandas. So far I tried pd.concat df=pd.concat([df,df,df,df]) But the problem is Some times i have to create more than 20 duplicates dataframes. Is there any other way to make duplicate dataframes in pythonic way
accepted answer: http://stackoverflow.com/a/49915597
favorite count: 0
type: Question
has title: What is the simple way to create duplicates of dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49915597
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: pandas
downvote count: 0
answer count: 1

http://stackoverflow.com/q/49784816
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86664847
has body: I have a hybrid_property that returns a string based on some calculations made on a one-to-many relationship. The raw sql for the hybrid_property expression is: Here's the raw sql: SELECT CASE WHEN s.quantity_received = 0 THEN "unreceived" WHEN s.dif = 0.0 THEN "received" WHEN s.dif &gt; 0.0 THEN "partially_received" WHEN s.dif &lt; 0.0 THEN "over_received" END as status FROM ( SELECT li.quantity_received, sum(li.quantity - li.received) as 'dif' FROM line_items as li WHERE li.o_id = xxx ) as s The Models class LineItem(BaseModel): __table__ = Table('line_items', autoload=True) order = relationship("Order", backreef="line_itms", primaryjoin="Order.id == foregin(LineItem.o_id)") class Order(BaseModel): __table__ = Table('orders', autoload=True) @hybrid_property def status(self): qty_received, qty_ordered = 0, 0 for li in self.line_items: if li.status != "cancelled": qty_ordered += li.quantity qty_received += li.quantity_received if qty_received == 0: status = "unreceived" elif qty_received == qty_ordered: status = "received" elif qty_received &lt; qty_ordered: status = "partially_received" elif qty_received &gt; qty_ordered: status = "over_received" return status @status.expression def status(cls): line_items_calc = select([LineItem.quantity_received, func.sum(LineItem.quantity - LineItem.quantity_received).label('dif')]) \ .where(and_(LineItem.o_id == Order.id, or_(LineItem.fulfillment_status != "cancelled", LineItem.fulfillment_status == None))) \ .alias() qq = select([ case([ (qs.c.quantity_received == 0, "unreceived"), (qs.c.dif == 0, "received"), (qs.c.dif &gt; 0, "partially_received"), (qs.c.dif &lt; 0, "over_received")] )]) \ .select_from(line_items_calc) \ .as_scalar() return qq I have 2 orders, o1 and o2 with line items: LineItem(o_id=o1.id, quantity=1, quantity_received=1) LineItem(o_id=o2.id, quantity=1, quantity_received=0) LineItem(o_id=o2.id, quantity=2, quantity_received=1) Order1 should have status "received" and Order2 should have "partially_received"…
tagged with: sqlalchemy
has title: SQLAlchemy reference a subquery from a case expression
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/86608404
has comment: http://stackoverflow.com/comment/86626463
accepted answer: http://stackoverflow.com/a/49830986
has answer: http://stackoverflow.com/a/49830986

http://stackoverflow.com/q/49863921
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86743565
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49888250
tagged with: http://stackoverflow.com/tag/csv
score: 1
has answer: http://stackoverflow.com/a/49888250
tagged with: python
type: Question
tagged with: dask
has title: How should I read and use data from a ~40GB csv for time series prediction?
has body: I have a ~40GB csv file with data about taxi rides from 2013-2016 (approx. 105 million rows), using which I am trying to forecast revenue for the year 2017. Currently, I am testing techniques such as random forests, xgboost and Prophet. I have only been working with a small subset of the data because of memory constraints and now I need to do my predictions using all the data available. What would be the best way to read all this data for forecasting purposes: will dask fit the purpose? For the smaller subsets, I used pandas, and I am currently looking into dask for reading the full data. Once I read the data in, I need to do rearranging operations like sorting them by date, computing the daily/weekly medians of some of the data, etc. Even while using dask, wouldn't it need to keep all the data in memory for doing the prediction?

http://stackoverflow.com/comment/86845717
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49914716
type: Comment
has text: I haven't forgotten, but every time I try it tells me I can accept the answer in 10 minutes.

http://stackoverflow.com/comment/107776372
comment on: http://stackoverflow.com/a/49918007
type: Comment
type: AnswerComment
score: 0
has text: I haven't really check it, I was moslty focusing on the procedure,"how to do it", so you can do it with any package

http://stackoverflow.com/q/49845791
accepted answer: http://stackoverflow.com/a/51490938
linked to: http://stackoverflow.com/q/240178
tagged with: python
has answer: http://stackoverflow.com/a/49845808
upvote count: 4
answer count: 4
type: Question
score: 2
tagged with: list
has answer: http://stackoverflow.com/a/49845849
has answer: http://stackoverflow.com/a/49846117
possible better answer: http://stackoverflow.com/a/49845849
downvote count: 2
has comment: http://stackoverflow.com/comment/86706471
has title: Why Python gives ['th', 'th', 'th', 'th', 'th'] as the result of '5 * ['th']' and not five lists?
has comment: http://stackoverflow.com/comment/86961240
favorite count: 0
has body: In Python, why do these two 5 * ['th'] and [5 * ' th'] give almost the same result? The question here is why 5* ['th'] gives a list five times big and not five lists. &gt;&gt;&gt;5 * ['th'] ['th', 'th', 'th', 'th', 'th'] &gt;&gt;&gt; [5 * 'th'] ['ththththth'] For 5 * ['th'] the expected result is 5 lists!
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51490938

http://stackoverflow.com/comment/86649153
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49817284
has text: You should probably first install python 3.5 with conda, and then do an offline install
type: Comment

http://stackoverflow.com/q/49787022
tagged with: python-requests
favorite count: 0
has title: How to convert requests.RequestsCookieJar to string
type: Question
has body: I have a requests.cookies.RequestCookieJar object which contains multiple cookies from different domain/path. How can I extract a cookies string for a particular domain/path following the rules mentioned in here? For example >>> r = requests.get("https://stackoverflow.com") >>> print(r.cookies) <RequestsCookieJar[<Cookie prov=4df137f9-848e-01c3-f01b-35ec61022540 for .stackoverflow.com/>]> # the function I expect >>> getCookies(r.cookies, "stackoverflow.com") "prov=4df137f9-848e-01c3-f01b-35ec61022540" >>> getCookies(r.cookies, "meta.stackoverflow.com") "prov=4df137f9-848e-01c3-f01b-35ec61022540" # meta.stackoverflow.com is also satisfied as it is subdomain of .stackoverflow.com >>> getCookies(r.cookies, "google.com") "" # r.cookies does not contains any cookie for google.com, so it return empty string
has comment: http://stackoverflow.com/comment/86590259
has comment: http://stackoverflow.com/comment/86589967
has answer: http://stackoverflow.com/a/71798674
has answer: http://stackoverflow.com/a/71188151
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/60662282
tagged with: python
has comment: http://stackoverflow.com/comment/86643613
has answer: http://stackoverflow.com/a/49793670
upvote count: 13
has answer: http://stackoverflow.com/a/69365296
has comment: http://stackoverflow.com/comment/86590097
has answer: http://stackoverflow.com/a/49800595
has answer: http://stackoverflow.com/a/66195530
has comment: http://stackoverflow.com/comment/86615091
downvote count: 0
answer count: 7
has comment: http://stackoverflow.com/comment/86590051
score: 13

http://stackoverflow.com/a/49792381
score: 0
answers question: http://stackoverflow.com/q/49791845
has body: You can override save to check the consistency. A ValueError will be raised if type is invalid. def save(self, *args, **kwargs): if self.setting_type == 'int': int(self.setting_value) # Checking int first to avoid treating floats as valid int type elif self.setting_type == 'float': float(self.setting_value) elif self.setting_type == 'string': # Logic for validating string here else: raise ValueError('Setting type not recognized' + self.setting_type) super(Setting, self).save(*args, **kwargs)
type: Answer

http://stackoverflow.com/a/49833974
has comment: http://stackoverflow.com/comment/86683256
upvote count: 3
has comment: http://stackoverflow.com/comment/86683339
has comment: http://stackoverflow.com/comment/86683242
has comment: http://stackoverflow.com/comment/86683286
downvote count: 1
has comment: http://stackoverflow.com/comment/86782664
score: 2
has body: tuple is a class, that does not require a parameter to be constructed. Calling instance.tuple() returns tuple() which is just an empty tuple. The difference with your anonymous function is that it is a function. When calling a class function from outside of the functional scope using instance.function(), self is automatically passed in as a parameter. Classes don't have this same treatment. What's passed in is ._revert(instance), which calls tuple(instance) which actually reverts your tuple. from collections import namedtuple Point = namedtuple('Point',['x','y']) Point2 = namedtuple('Point2',['x','y']) class test: def __init__(self): print(self) def func(a): print(a) Point._revert = test Point2._revert = func instance = Point(x=10,y=20) instance._revert() &gt;&gt;&gt;&lt;__main__.test object at 0x0000020ECAE1DFD0&gt; instance = Point2(x=10,y=20) instance._revert() &gt;&gt;&gt;Point2(x=10, y=20)
type: Answer
has comment: http://stackoverflow.com/comment/86683220
answers question: http://stackoverflow.com/q/49833804

http://stackoverflow.com/comment/86778356
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49881167
has text: awesome thanks man, I appreciate it! I was searching for this for a while but it can be hard to find info when unsure of how to ask the question in a general way.

http://stackoverflow.com/a/49895654
has comment: http://stackoverflow.com/comment/86807654
downvote count: 0
has body: You can use values to get required data with one query: records = tableA.objects.values('Name', 'desc', 'tableBID__Name`) tableBID__Name will fetch name from related TableB record. Or to get list of objects instead of dictionaries use select_related: records = tableA.objects.all().select_related('tableBID')
has comment: http://stackoverflow.com/comment/86807762
accepted answer of: http://stackoverflow.com/q/49895499
type: Answer
answers question: http://stackoverflow.com/q/49895499
score: 4
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/a/49844292
type: Answer
has comment: http://stackoverflow.com/comment/86703449
accepted answer of: http://stackoverflow.com/q/49844117
has comment: http://stackoverflow.com/comment/86703390
answers question: http://stackoverflow.com/q/49844117
type: AcceptedAnswer
has body: You need '200' and '400' in np.where change to 200 and 400 for integers: xtest['SportYes'] = np.where(xtest['c']&lt;=16897, 200, 400) xtest['stateYes'] = np.where(xtest['k']&lt;=62, 200, 400) xtest['durYes'] = np.where(xtest['a']&lt;=0.0585, 200, 400) xtest.loc[(xtest['SportYes'] == 200) &amp; (xtest['stateYes'] == 200), 'k'] = 3 print(xtest) Or add '' to 200 and 400 in loc statement for compare by strings: xtest['SportYes'] = np.where(xtest['c']&lt;=16897, '200', '400') xtest['stateYes'] = np.where(xtest['k']&lt;=62, '200', '400') xtest['durYes'] = np.where(xtest['a']&lt;=0.0585, '200', '400') xtest.loc[(xtest['SportYes'] == '200') &amp; (xtest['stateYes'] == '200'), 'k'] = 3 print(xtest)
score: 0

http://stackoverflow.com/q/49872824
tagged with: selenium
has body: Here is the page source code snippet. &lt;tr&gt; &lt;th&gt;Model Name&lt;span class="c-c60000 txtNormal"&gt;*&lt;/span&gt;&lt;/th&gt; &lt;td&gt;&lt;table cellpadding="0" cellspacing="0" border="0"&gt;&lt;tr&gt;&lt;td&gt;&lt;input tabindex="-1" readonly="readonly" value="" disabled="disabled" type="text" class="inputText" name="modelName" id="modelName" style="width:150px;" style = "ime-mode:disabled"/&gt;&amp;nbsp;&lt;/td&gt;&lt;td&gt;&lt;table class="btnTypeA"&gt;&lt;tr&gt;&lt;td&gt; &lt;a href="javascript:popUpModelSearch();"&gt;Search&lt;/a&gt; &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/td&gt; &lt;th&gt;Customer Code&lt;span class="c-c60000 txtNormal"&gt;*&lt;/span&gt;&lt;/th&gt; &lt;td&gt;&lt;input readonly="readonly" disabled="disabled" type="text" value="" class="inputText" name="cc" id="cc" style="width:150px;" style = "ime-mode:disabled"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Model Alias&lt;/th&gt; &lt;td&gt;&lt;input readonly="readonly" disabled="disabled" type="text" value="" class="inputText" name="modelAlias" id="modelAlias" style="width:150px;" style = "ime-mode:disabled"/&gt;&lt;/td&gt; &lt;th&gt;Scenario Type&lt;/th&gt; &lt;td&gt; &lt;select style="width:155px;" name="testOrUse" id="testOrUse" onchange="javascript:loadSubField('');"&gt; &lt;!-- Admin, Lead Model Developer --&gt; &lt;option value="T"&gt;Testing Scenario&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; My code is element4 = browser.find_element_by_id("modelAlias") browser.execute_script("arguments[0].value = 'GT-I9192';", element4) element2 = browser.find_element_by_id("modelName") browser.execute_script("arguments[0].value = 'GT-I9192';", element2) First 2 lines seem to work and value gets updated for "modelAlias" but last two lines are not working correctly. Also my code is not throwing any error which is making things difficult. I think span here is the reason of different behavior.
favorite count: 0
type: Question
has title: I am using Selenuim on python. I need to update value for two Webelement but am able to only update for one
has comment: http://stackoverflow.com/comment/86765096
has comment: http://stackoverflow.com/comment/86764401
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86767064
has answer: http://stackoverflow.com/a/49893193
downvote count: 0
has comment: http://stackoverflow.com/comment/86762081
answer count: 1
has comment: http://stackoverflow.com/comment/86761471
has comment: http://stackoverflow.com/comment/86765191
tagged with: python
has comment: http://stackoverflow.com/comment/86767161
has comment: http://stackoverflow.com/comment/86801839
has comment: http://stackoverflow.com/comment/86798528
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86772783
has comment: http://stackoverflow.com/comment/86765778

http://stackoverflow.com/comment/86842751
type: Comment
comment on: http://stackoverflow.com/q/49787860
score: 0
has text: What is the python and pip version you are using?
type: QuestionComment

http://stackoverflow.com/comment/86602366
type: Comment
type: QuestionComment
has text: @kabanus going to that link, I found a better version of their answer in another link: https://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c-using-posix/478960#478960. Though this is neat however and I quote the first comment to the top answer in my link "Be aware that this will only grab stdout and not stderr. – kalaxy". But stderr is where the warning and errors are. Using popen and assigning the output to a string is not enough, neither to a text file because I need something C++ can pickup later and embed inside the warning and error log.
comment on: http://stackoverflow.com/q/49793399
score: 0

http://stackoverflow.com/a/51848489
type: Answer
answers question: http://stackoverflow.com/q/49865952
score: 0
has body: import numpy as np import pandas as pd X = [0.5, 2.5] Y = [0.2, 0.9] def f(w, b, x): #sigmoid with parameter w,b return 1.0/(1.0 * np.exp(-(w * x + b))) def error(w, b): err = 0.0 for x, y in zip(X, Y): fx = f(w, b, x) err += 0.5 * (fx - y)**2 return err def grad_b(w, b, x, y): fx = f(w, b, x) return (fx - y) * fx * (1 - fx) def grad_w(w, b, x, y): fx = f(w, b, x) return (fx - y) * fx * (1 - fx) * x def do_gradient_descent(): w, b, eta, max_epochs = 1, 1, 0.01, 100 for i in range(max_epochs): dw, db = 0, 0 for x, y in zip(X, Y): dw += grad_w(w, b, x, y) db += grad_b(w, b, x, y) w = w - eta * dw print(w) b = b - eta * db print(b) er = error(w, b) #print(er) return er ##Calling Gradient Descent function do_gradient_descent()

django-views
tags question: http://stackoverflow.com/q/49831584
tags question: http://stackoverflow.com/q/49901193
tags question: http://stackoverflow.com/q/49842383
tags question: http://stackoverflow.com/q/49848267
tags question: http://stackoverflow.com/q/49886388
tags question: http://stackoverflow.com/q/49846147
tags question: http://stackoverflow.com/q/49759078
tags question: http://stackoverflow.com/q/49808022
tag name: django-views
tags question: http://stackoverflow.com/q/49837092
tags question: http://stackoverflow.com/q/49905484
tags question: http://stackoverflow.com/q/49916246
tags question: http://stackoverflow.com/q/49857165
tags question: http://stackoverflow.com/q/49893672
tags question: http://stackoverflow.com/q/49848167
type: Tag
tags question: http://stackoverflow.com/q/49795525
tags question: http://stackoverflow.com/q/49776144
tags question: http://stackoverflow.com/q/49853623
tags question: http://stackoverflow.com/q/49889399
tags question: http://stackoverflow.com/q/49778993

http://stackoverflow.com/comment/86667012
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49824338
has text: thanks, I'll try it. Oddly it looks like `np.concatenate` is supported by numba: https://numba.pydata.org/numba-doc/dev/reference/numpysupported.html
type: Comment

http://stackoverflow.com/q/49843975
type: Question
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has title: gspread - Using "find" function for input values
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86721212
tagged with: gspread
has comment: http://stackoverflow.com/comment/86721284
answer count: 0
score: 2
has body: I'm writing a Python program using gspread and was wondering if there's any easy way to use the "find" function to search by input values instead of plain values. For example, I'm trying to locate =HYPERLINK("https://stackoverflow.com","Stack Overflow") instead of just Stack Overflow. Just want to make sure there's nothing I'm missing before I attempt to rewrite the function. Thanks! :)
has comment: http://stackoverflow.com/comment/86752047
favorite count: 0

http://stackoverflow.com/comment/86902261
has text: nice ... an alternative to just picking sample with greatest amplitude, which may be vulnerable to spurious spikes outside the indented max amplitude point, would be to slide across the audio file a window of a few samples where you feed into a RMS calculation that set of samples to identify a power metric
score: 0
comment on: http://stackoverflow.com/a/49933467
type: AnswerComment
type: Comment

telegram
tags question: http://stackoverflow.com/q/49779933
tags question: http://stackoverflow.com/q/49859332
tag name: telegram
tags question: http://stackoverflow.com/q/49839857
type: Tag

http://stackoverflow.com/q/49799770
tagged with: python
score: -2
has body: My problem is that I am trying to make the background colour to change when the string variable is higher than 5. this is the code: colour_p1="White" kills_p1 = IntVar() kills_p1.set(0) def kill_count_p1(): kills_p1.set(kills_p1.get()+1) if kills_p1.get() &gt;= 5: colour_p1 = "Yellow" Label(master, textvariable=kills_p1, bg=colour_p1, font=("Courier", 20)).grid(column = 4, row=2) I have tried a few different ways like "if", but it keeps it on the same colour all the time. I want the background to be yellow when the variable "kills_p1" is higher than 5. ps. this is only a part of the project and not the whole
has comment: http://stackoverflow.com/comment/86614559
has answer: http://stackoverflow.com/a/49806044
favorite count: 0
has comment: http://stackoverflow.com/comment/86614460
tagged with: tkinter
type: Question
answer count: 2
has title: Changing background colour when IntVar is higher than 5 (tkinter/python)
upvote count: 1
possible better answer: http://stackoverflow.com/a/49806044
accepted answer: http://stackoverflow.com/a/49803568
has answer: http://stackoverflow.com/a/49803568
has comment: http://stackoverflow.com/comment/86616599
has comment: http://stackoverflow.com/comment/86614725
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86614830
downvote count: 3

http://stackoverflow.com/a/49834246
has comment: http://stackoverflow.com/comment/86683934
downvote count: 0
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/49834133
upvote count: 3
has body: One way is to escape your characters using re, then use pd.Series.str.replace. import pandas as pd import re bad_chars = ['?', '!', ',', ';', "'", '|', '-', '--', '(', ')', '[', ']', '{', '}', ':', '&amp;', '\n'] df = pd.DataFrame({'page': ['hello?', 'problems|here', 'nothingwronghere', 'nobrackets[]']}) df['page'] = df['page'].str.replace('|'.join([re.escape(s) for s in bad_chars]), '') print(df) # page # 0 hello # 1 problemshere # 2 nothingwronghere # 3 nobrackets
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49834133

http://stackoverflow.com/a/49863260
has body: Consider the example df df = pd.DataFrame(dict(my_date=pd.date_range('now', periods=4, freq='15D'))) df my_date 0 2018-04-16 10:39:16.218988 1 2018-05-01 10:39:16.218988 2 2018-05-16 10:39:16.218988 3 2018-05-31 10:39:16.218988 Here are some examples df.assign( Period=df.my_date.dt.to_period('M'), String=df.my_date.dt.strftime('%Y-%m'), NewDate=pd.to_datetime(df.my_date.dt.strftime('%Y-%m-01')) ) my_date Period String NewDate 0 2018-04-16 10:39:16.218988 2018-04 2018-04 2018-04-01 1 2018-05-01 10:39:16.218988 2018-05 2018-05 2018-05-01 2 2018-05-16 10:39:16.218988 2018-05 2018-05 2018-05-01 3 2018-05-31 10:39:16.218988 2018-05 2018-05 2018-05-01
answers question: http://stackoverflow.com/q/49863141
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49824262
tagged with: http://stackoverflow.com/tag/csv
has title: Syntax error in csv.writer
tagged with: python
accepted answer: http://stackoverflow.com/a/49824329
type: AnsweredQuestion
has body: I getting a syntax error and I need some help please? I tried to solve the problem, but I couldn't. Here is the code with error: from pandas.tseries.offsets import * light1 = pd.read_csv('G:/light1.csv') light1.Time = pd.to_datetime(light1.Time) tdelta = datetime.timedelta(hours=5) time_before_5_hours = light1.Time + tdelta #rng = pd.date_range(start=light1.Time, end=time_before_5_hours,periods=1, freq='m' ) s = light1.Time m= light1.Time - DateOffset(hours = 5) from dateutil import rrule import datetime def hours_between(start_date, end_date): time = rrule.rrule(rrule.MINUTELY, dtstart=s, until=m) return hours_between with open('G:/project/light1.csv') as input_file: with open('G:/light2.csv', 'w') as csvoutput: writer = csv.writer(csvoutput, lineterminator='\n') reader = csv.reader(input_file) all = [ ] row = next(reader) row.append('k') all.append(row) for row[0] in csv.reader(input_file): try: v = hours_between(input_file.Time,input_file.Time - DateOffset(hours = 5)) if v.bool() == True : row.append(1) all.append(row) writer.writerows(all) row = next(reader) else: row.append(0) all.append(row) writer.writerows(all) Error: File "&lt;ipython-input-139-aa2b4e5dbb1e&gt;", line 41 writer.writerows(all) ^ SyntaxError: invalid syntax
score: 0
has answer: http://stackoverflow.com/a/49824329
has comment: http://stackoverflow.com/comment/86664531
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/86664466
upvote count: 1
has comment: http://stackoverflow.com/comment/86664530
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/86708703
type: QuestionComment
has text: Because you never set a value for `y[1] = ...`... so it throws a key-error. For `x` you do in your `if...else...`
score: 0
comment on: http://stackoverflow.com/q/49846661
type: Comment

http://stackoverflow.com/a/49867568
answers question: http://stackoverflow.com/q/49867472
type: Answer
has body: You can use the panda package to parse your CSV and skip specific row. import pandas as pd df = pd.read_csv('myfile.csv', skiprows='list with row number to skip')
score: 0

http://stackoverflow.com/q/49823192
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49823979
accepted answer: http://stackoverflow.com/a/49823979
answer count: 1
has title: Autoencoder Gridsearch Hyperparameter tuning Keras
tagged with: keras
favorite count: 0
type: Question
has body: My data shape is the same, I just generated here random numbers. In real the datas are float numbers from range -6 to 6, I scaled them as well. The Input layer size and Encoding dimension have to remain the same. When I am training the loss starts and stays at 0.631 all the time. I changed the learning rate manually. I am new to python and do not know to implement to a grid search to this code to find the right parameters. What else can I do to tune my network ? import numpy as np from keras.layers import Input, Dense from keras.models import Model from keras import optimizers #Train data x_train=np.random.rand(2666000) x_train = (train-min(train))/(max(train)-min(train)) x_train=x_train.reshape(-1,2000) x_test=[]#empty testing later #Enc Dimension encoding_dim=100 #Input shape input_dim = Input(shape=(2000,)) #Encoding Layer encoded = Dense(encoding_dim, activation='relu')(input_dim) #Decoding Layer decoded = Dense(2000, activation='sigmoid')(encoded) #Model AE autoencoder = Model(input_dim, decoded) #Model Encoder encoder = Model(input_dim, encoded) #Encoding encoded_input = Input(shape=(encoding_dim,)) #Decoding decoder_layer = autoencoder.layers[-1] #Model Decoder decoder = Model(encoded_input, decoder_layer(encoded_input)) optimizers.Adadelta(lr=0.1, rho=0.95, epsilon=None, decay=0.0) autoencoder.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy']) #Train and test autoencoder_train= autoencoder.fit(x_train, x_train, epochs=epochs, shuffle=False, batch_size=2048)
tagged with: grid-search
tagged with: python

http://stackoverflow.com/q/49899100
has comment: http://stackoverflow.com/comment/96803658
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/69408314
tagged with: rest
has body: I'm trying to perform a simple query with Firestore REST API. Being on Google App Engine standard I cannot use the google-cloud-firestore client which is not yet compatible with GAE standard. Instead, I'm using google-api-python-client as for other Google APIs. This is how I initialize my service: service = build('firestore', 'v1beta1', credentials=_credentials) Once this is done, I perform the query that way: query = { "structuredQuery": { "from": [{ "collectionId": "mycollection" }], "where": { "fieldFilter": { "field": { "fieldPath": "myfield" }, "op": "EQUAL", "value": { "stringValue": "myvalue" } } } } } response = service.projects().databases().documents().runQuery( parent='projects/myprojectid/databases/(default)/documents', body=query).execute() This returns an error quite explicit: TypeError: Parameter "parent" value "projects/myprojectid/databases/(default)/documents" does not match the pattern "^projects/[^/]+/databases/[^/]+/documents/[^/]+/.+$" which obviously is true. My point is that the documentation cleary states that this should be an accepted value: The parent resource name. In the format: projects/{project_id}/databases/{database_id}/documents or projects/{project_id}/databases/{database_id}/documents/{document_path}. For example: projects/my-project/databases/my-database/documents or projects/my-project/databases/my-database/documents/chatrooms/my-chatroom (string) Performing the same query with the API Explorer (or curl) works fine and returns the expected results. (even though the API Explorer does state that the parent parameter does not match the expected pattern). It seems that the discovery document (which is used by google-api-python-client) enforces this pattern check for the parent parameter but the associated regular expression does not actually allow the only parent path that seems to work (projects/myprojectid/databases/(default)/documents). I tried to use a different pattern path like projects/myprojectid/databases/(default)/documen…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/96831067
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/105902250
has answer: http://stackoverflow.com/a/61173706
tagged with: google-cloud-firestore
answer count: 2
has title: Firestore: REST API runQuery method expects wrong parent path pattern
downvote count: 0

serverless-framework
tag name: serverless-framework
type: Tag
tags question: http://stackoverflow.com/q/49913228
tags question: http://stackoverflow.com/q/49839924

http://stackoverflow.com/q/49822818
type: Question
has body: somebody help me. How to run urdu-tokenizer.py file. i have taken this file from the following link https://www.cs.cmu.edu/afs/cs.cmu.edu/project/cmt-40/Nice/Urdu-MT/code/urdu-tokenizer.py Do anyone know how to add urdu text file to run urdu-tokenizer.py file.
type: UnansweredQuestion
tagged with: python
tagged with: ubuntu
score: 0
answer count: 1
has title: How to run Urdu tokenizer in Ubuntu
has answer: http://stackoverflow.com/a/49822859

http://stackoverflow.com/a/49915597
has body: Use concat one dataframe in list with multiple by repeats: df = pd.concat([df] * 3, ignore_index=True) print (df) col1 col2 0 a 1 1 b 2 2 c 3 3 d 4 4 e 5 5 a 1 6 b 2 7 c 3 8 d 4 9 e 5 10 a 1 11 b 2 12 c 3 13 d 4 14 e 5 Another solution with repeat index values numpy.tile and expand by loc: df = df.loc[np.tile(df.index, 3)].reset_index(drop=True)
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49915577
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49915577
type: Answer

http://stackoverflow.com/comment/86745178
type: Comment
score: 0
type: AnswerComment
has text: I see your point. The way the cohort is calculated is correct, since its tracking the first moment that customer has joined. However, I think I need to create the 'Retention' from the Plan_Start_Date and then do a datetime range to match the total Lifetime of each customer, and then groupby the way you did. Will update you on the results.
comment on: http://stackoverflow.com/a/49864212

http://stackoverflow.com/a/49847826
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49839439
has body: I ended up converting the initial output to a pivot using Pandas, then uploaded the df into a new model that I created with the same exact field names. def users(request): df = pd.read_sql(query, cnxn) pvt = df.pivot(columns='label', index='post_id', values='meta_value') pvt = pvt.reset_index() pvt['id'] = pvt.index pvt.to_sql('table_name', cnxn, if_exists='replace') The model configured includes all the fields in the queried table, so the outcome matched the model and I can treat it as an object. Hope this helps.

http://stackoverflow.com/q/49778805
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86573325
has comment: http://stackoverflow.com/comment/86577089
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86573188
tagged with: compiler-errors
has body: I have been unpacking binary using python 2.7 on windows for months, but when I transferred to linux python 2.7 I get a value error. I am using the standard struct.unpack_from function, with the option "L" for unsigned long structure. (https://docs.python.org/2/library/struct.html) When I change the structure to "I" for unsigned integer I don't get the value error, but I'm wary of using this. The closest problem I could find similar to mine: Problems with python 2.4 and 2.4.4 in struct.unpack and win/lin Is there a way to make sure I get the same implementation of data types between the windows and linux compilers? EDIT: For future readers who have encountered a similar problem. If you are using long on windows and switch to Linux, the data types consist of a different number of bytes between the two operating systems. Long (unsigned) on windows is 4 bytes, but 8 on linux. Switching to unsigned int worked for me.
has title: Int vs. Long Windows to Linux
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/86574349
has comment: http://stackoverflow.com/comment/86577161
has comment: http://stackoverflow.com/comment/86572996
tagged with: python
linked to: http://stackoverflow.com/q/7583687
linked to: http://stackoverflow.com/q/9689049
tagged with: linux
answer count: 0

http://stackoverflow.com/a/64274737
has comment: http://stackoverflow.com/comment/136323536
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49798775
has body: You will try this way: import sys, os import gitlab file_content = open(os.getcwd() + 'testfile.txt').read() f = project.files.create({ 'file_path': 'testfile.txt', 'branch': 'master', 'content': file_content, 'author_email': 'test@example.com', 'author_name': 'yourname', 'commit_message': 'Create testfile' })
score: 1
upvote count: 1

http://stackoverflow.com/q/49901868
favorite count: 0
type: Question
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/86820760
duplicate of: http://stackoverflow.com/q/45575626
tagged with: python
duplicate of: http://stackoverflow.com/q/25560748
linked to: http://stackoverflow.com/q/46671067
has title: OnClick event for textboxes in PyQt5?
duplicate of: http://stackoverflow.com/q/13465329
tagged with: python-3.x
downvote count: 0
linked to: http://stackoverflow.com/q/25560748
tagged with: pyqt
type: UnansweredQuestion
answer count: 1
has body: Do we have onclick event handler for textboxes in PyQt5, like we have in JQuery and C# ? If not, Is there any other way of handling clicks on textboxes ?
tagged with: pyqt5
has answer: http://stackoverflow.com/a/49904623

cron
tags question: http://stackoverflow.com/q/49797295
tag name: cron
tags question: http://stackoverflow.com/q/49858760
tags question: http://stackoverflow.com/q/49916125
tags question: http://stackoverflow.com/q/49914630
tags question: http://stackoverflow.com/q/49859931
tags question: http://stackoverflow.com/q/49896915
type: Tag

http://stackoverflow.com/a/49805351
has body: You seem to have expected np.array(y) to automatically turn your scalar y into a 1-element row. That's not how NumPy works. np.array(y) is 0-dimensional. Putting a bunch of those in a list and calling array on the list produces a 1-dimensional result, not a 2-dimensional one.
score: 3
type: Answer
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49805236
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49805236

http://stackoverflow.com/comment/86724852
comment on: http://stackoverflow.com/a/49855040
score: 0
type: Comment
type: AnswerComment
has text: Great, I somehow missed that. Can you now please also tell me how to change the color of the individual widgets?

http://stackoverflow.com/comment/87088136
score: 6
comment on: http://stackoverflow.com/a/49836753
has text: I needet to use the command 'python -m pip uninstall pip' as 'sudo pip uninstall pip' gave a similar error to the original question
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86752665
type: AnswerComment
comment on: http://stackoverflow.com/a/49858281
type: Comment
has text: I have edited the question above, sorry for the confusion here. I believe the reason is not the way I write parameters in tf.slice() but the unknown dimensions in there. Is it possible to get what I want? Thanks.
score: 0

http://stackoverflow.com/q/49909538
favorite count: 0
has title: mapping a multi-index to existing pandas dataframe columns using separate dataframe
type: Question
tagged with: indexing
possible better answer: http://stackoverflow.com/a/49909897
upvote count: 2
tagged with: python
has body: I have an existing data frame in the following format (let's call it df): A B C D 0 1 2 1 4 1 3 0 2 2 2 1 5 3 1 The column names were extracted from a spreadsheet that has the following form (let's call it cat_df): current category broader category X A Y B Y C Z D First I'd like to prepend a higher level index to make df look like so: X Y Z A B C D 0 1 2 1 4 1 3 0 2 2 2 1 5 3 1 Lastly i'd like to 'roll-up' the data into the meta-index by summing over subindices, to generate a new dataframe like so: X Y Z 0 1 3 4 1 3 2 2 2 1 8 1 Using concat from this answer has gotten me close, but it seems like it'd be a very manual process picking out each subset. My true dataset is has a more complex mapping, so I'd like to refer to it directly as I build my meta-index. I think once I get the meta-index settled, a simple groupby should get me to the summation, but I'm still stuck on the first step.
has answer: http://stackoverflow.com/a/49910269
score: 2
has answer: http://stackoverflow.com/a/49909924
accepted answer: http://stackoverflow.com/a/49909924
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49909897
answer count: 3
tagged with: pandas
downvote count: 0
linked to: http://stackoverflow.com/q/14744068

http://stackoverflow.com/comment/86775972
type: QuestionComment
score: 0
has text: How would I use it in pandas df?
comment on: http://stackoverflow.com/q/49879942
type: Comment

http://stackoverflow.com/q/49779932
has title: Parsing Python function declaration
has body: In order to write a custom documentation generator for my Python code, I'd like to write a regular expression capable of matching to following: def my_function(arg1,arg2,arg3): """ DOC """ My current problem is that, using the following regex: def (.+)\((?:(\w+),)*(\w+)\) I can only match my_function, arg2 and arg3 (according to Pythex.org). I don't understand what I'm doing wrong, since my (?:(\w+),)* should match as many arguments as possible, until the last one (here arg3). Could anyone explain? Thanks
tagged with: python
tagged with: regex
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49781514
linked to: http://stackoverflow.com/q/380455
has answer: http://stackoverflow.com/a/49781514
downvote count: 0
answer count: 1
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/86848168
type: Comment
has text: Since `retrieve BIOS data using F:\tools64\BiosConfigUtility64.exe` is between `seq call @ 2018/02/26 23:07:51 node: ttt retrieve BIOS data using F:\tools64\BiosConfigUtility64.exe /GetConfig:\working\bcudump.txt BCU is working seq done @ 2018/02/26 23:07:55 node:ttt` So it needs to be in the outout.
comment on: http://stackoverflow.com/a/49915670
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86751476
type: Comment
comment on: http://stackoverflow.com/q/49867945
type: QuestionComment
score: 0
has text: So in your case, `a[1, :, np.newaxis]`.

http://stackoverflow.com/q/49847901
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
tagged with: python
has title: Python BeautifulSoup4 - Scrape Section/Table Header and Values from Multiple Sections/Tables
score: 0
has body: I'm trying to scrape links with contextual information from the following page: https://www.reddit.com/r/anime/wiki/discussion_archive/2018. I'm able to get the links just fine using BS4 using Python, but having year, season, titles, and episodes associated to the links is ideal. The desired output would look like this: I've started with the code below, but don't know how to loop through the code to capture things in sections for each season/title: import requests from bs4 import BeautifulSoup session = requests.Session() link = 'https://www.reddit.com/r/anime/wiki/discussion_archive/2018' request_2018 = session.get(link, headers={'User-agent': 'Chrome'}) soup = BeautifulSoup(request_2018.content, 'lxml') data_table = soup.find('div', class_='md wiki') Is this something that's doable with BS4? Thanks for your help!
answer count: 1
tagged with: web-scraping
has answer: http://stackoverflow.com/a/49849644

http://stackoverflow.com/comment/86630994
has text: I'd use some version of the `numpy` `transpose` to reorder the axes - either the simplest completer reversal, or a partial swap.
score: 0
comment on: http://stackoverflow.com/q/49807797
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86554310
comment on: http://stackoverflow.com/q/49767101
score: 0
has text: @RahulKumar, can you [edit] your question to add this (important) information? Looking at the question, it looks like you are using `&` instead of `and`. Change the question accordingly, and I'll retract my close vote.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86747696
comment on: http://stackoverflow.com/q/49784872
type: Comment
type: QuestionComment
has text: I no longer use CVX. Cannot compare it to CVXPY.
score: 0

http://stackoverflow.com/comment/86705671
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49842120
score: 0
has text: @StefanCrain i am lookin for just a function like th.delete() or any thing th.remove whatever....like th,start to start the thread

http://stackoverflow.com/comment/86805424
type: AnswerComment
has text: Great. Note that you can simplify the line as `driver.switch_to.frame("newBodyFrame")`
type: Comment
comment on: http://stackoverflow.com/a/49892086
score: 0

http://stackoverflow.com/q/49875116
tagged with: python-webbrowser
has title: open a html file in web browser at a particular hyperlink using python
type: Question
has comment: http://stackoverflow.com/comment/86765915
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4216985
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86868113
has body: I am able to open an html file using the code import webbrowser webbrowser.open_new_tab('file:///C:/filename.html') The issue I am facing is opening the same html file but with a hyperlink. webbrowser.open_new_tab('file:///C:/filename.html#hyperlinkId') This opens the file in the browser tab but does not move to the hyperlink as required. Kindly let me know if I am missed anything. Thanks in advance.

http://stackoverflow.com/comment/87315888
score: 0
type: QuestionComment
has text: @Riya208 Great, write it as an answer then!
type: Comment
comment on: http://stackoverflow.com/q/49892504

http://stackoverflow.com/a/49803089
has comment: http://stackoverflow.com/comment/86669312
has body: Not a direct answer to your question about "why" what you are noticing is occurring, but I would highly recommend changing strategies for how you are dealing with your multiprocessing by using ThreadPoolExecutor to manage system resources. Since your system can't effectively manage more processes than it has system threads, I would try: &gt;&gt;&gt; from concurrent.futures import ThreadPoolExecutor &gt;&gt;&gt; from multiprocessing import cpu_count &gt;&gt;&gt; with ThreadPoolExecutor(workers=cpu_count()) as pool: results = pool.map(lambda cmd: subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE), command_list) I find the API to be easy and the resource managment to be quite effective, and there are less "gotchas". https://docs.python.org/3.6/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor.shutdown Although this is for 3.6, the API is largely the same once you pip install the concurrent.futures module for 2.7.
has comment: http://stackoverflow.com/comment/86663071
has comment: http://stackoverflow.com/comment/86663345
has comment: http://stackoverflow.com/comment/86660404
has comment: http://stackoverflow.com/comment/86660346
has comment: http://stackoverflow.com/comment/86662210
has comment: http://stackoverflow.com/comment/86620686
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/86663214
answers question: http://stackoverflow.com/q/49802662

http://stackoverflow.com/a/49869642
answers question: http://stackoverflow.com/q/49869483
has body: It looks like writenow only takes the string as an arg, nothing else. https://docs.python.org/2/library/csv.html#csv.csvwriter.writerow If you want a \t at the end just do chr(i)+'\t'. Char just converts a single character though. I think you're looking for str(i)+'\t' So, csv_write.writerow(str(i)+'\t') And csv_write.writerow(str(random.randint(1,10001))+'\t' When you specified delimiter \t when creating the csv_write I think it will end the row with \t anyway so you don't need to append it to the end. Might have to try it out.
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49869483

http://stackoverflow.com/q/49826277
type: Question
tagged with: xpath
linked to: http://stackoverflow.com/q/8505375
answer count: 2
has body: Comment from Beckie F. of Yard House Business Customer Service 4/4/2018 Hi Kim. We are happy to be apart of the community. Thank you for the warm welcome! I'm trying to get the class biz-owner-reply's value with selenium and python. I first find the element and then try to get its value as below: response = "" responses = review_wrappers[0].find_elements_by_class_name("biz-owner-reply") if len(responses) > 0: response = responses[0].text However, the result also contains the values from its child elements: 'response':'Comment from Beckie F. of Yard House\nBusiness Customer Service\n4/4/2018 Hi Kim. We are happy to be apart of the community. Thank you for the warm welcome!' How can I get only: Hi Kim. We are happy to be apart of the community. Thank you for the warm welcome!
has title: How can I get only the value of the parent
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86673575
tagged with: python
has answer: http://stackoverflow.com/a/49826468
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/49826607
score: 0
has comment: http://stackoverflow.com/comment/86673112
tagged with: http://stackoverflow.com/tag/html
tagged with: selenium
has comment: http://stackoverflow.com/comment/86668362
has comment: http://stackoverflow.com/comment/86677022

http://stackoverflow.com/comment/86666516
has text: @tdelaney Just using the code `v.replace('”','"',)` doesn't seem to make a difference i seem to get an output of `'datafile.csv'` when I do. @Harry_pb I haven't checked with that so I'll look into that. @chb Ah, I didn't know that was a possibility (I'm pretty new to python and pandas) so I'll try that. The ” characters are in there it's on the 4th row between Tuesday and no `"Tuesday”;”no"`
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49825205

http://stackoverflow.com/a/49852723
answers question: http://stackoverflow.com/q/49852583
accepted answer of: http://stackoverflow.com/q/49852583
has body: There's no particular treatment for hex numbers other than printing them in hex format. &gt;&gt;&gt; def myroundup(n, step): ... return ((n - 1) // step + 1) * step ... &gt;&gt;&gt; hex(myroundup(0x7f8000, 0x10000)) '0x800000' &gt;&gt;&gt; myroundup(998000, 10000) # works with other bases too 1000000 If you need rounding down instead, use this: &gt;&gt;&gt; def myrounddn(n, step): ... return n // step * step And for completeness, rounding to closest step: &gt;&gt;&gt; def myround(n, step): ... return (n + step // 2) // step * step which you can also define using myrounddn: &gt;&gt;&gt; def myround(n, step): ... return myrounddn(n + step // 2, step)
has comment: http://stackoverflow.com/comment/86923822
downvote count: 0
type: Answer
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/49815872
type: AnsweredQuestion
has title: Can I create a pytest.fixture that returns combinations of arguments?
downvote count: 0
tagged with: pytest
score: 7
upvote count: 7
answer count: 1
accepted answer: http://stackoverflow.com/a/49821021
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49821021
has body: The inputs to the the algorithm being tested is a list of strings (known in advance) with associated years, e.g. all of the following are valid inputs: ['A_2018', 'B_2019', 'C_2018'] [] ['A_2018'] I've got the following simple year fixture: @pytest.fixture(params=range(2018, 2025)) def year(request): return request.param If I create individual fixtures for each valid string: @pytest.fixture(params=['A', '']) def A(request, year): return request.param, year @pytest.fixture(params=['B', '']) def B(request, year): return request.param, year etc. and use them in tests like: def test_foo(A, B): args = [] if A[0]: args.append('%s_%d' % A) if B[0]: args.append('%s_%d' % B) assert old_algorithm(args) == new_algorithm(args) I get ['A_2018', 'B_2018'] ['A_2019', 'B_2019'] ['A_2020', 'B_2020'] etc. where the year is always the same for both parameters. Is there a way to create all combinations?
tagged with: python

http://stackoverflow.com/a/56699655
upvote count: 16
downvote count: 0
score: 16
has body: In recent versions of jupyter nbconvert you can use the --no-input option: echo 'A Markdown cell with an equation $x=y+1$ ```python 1 + 1 ``` ' | jupytext --to ipynb | jupyter nbconvert --stdin --execute --no-input --to html --output notebook.html Now if you don't have the --no-input option, use --TemplateExporter.exclude_input=True, which is available from version 5.2.1 on.
type: Answer
answers question: http://stackoverflow.com/q/49907455

http://stackoverflow.com/q/49765985
downvote count: 0
has body: I have a string as below , val = '["10249/54","10249/147","10249/187","10249/252","10249/336"]' I need to parse it and take the values after / and put into list as below ['54','147','187','252','336'] My code: [a[a.index('/')+1:] for a in val[1:-1].split(',')] Output : ['54"', '147"', '187"', '252"', '336"'] It has double quotes also " which is wrong. After i tried as below c = [] for a in val[1:-1].split(','): tmp = a[1:-1] c.append(tmp[tmp.index('/')+1:]) Output : ['54', '147', '187', '252', '336'] Is there any better way to do this?
tagged with: python
tagged with: string
possible better answer: http://stackoverflow.com/a/49766033
answer count: 4
accepted answer: http://stackoverflow.com/a/49766040
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49766033
tagged with: list
has answer: http://stackoverflow.com/a/49766040
has title: Convert string list to list in python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49766889
score: 5
has answer: http://stackoverflow.com/a/49766092
upvote count: 5

http://stackoverflow.com/a/49771481
score: 2
has body: You should use "\" to indicate to Python that the line does not terminate: my_variable = "beginning of the string" \ "end of the string" For your second case: my_variable = \ "beginning of the string" \ "end of the string" You can also use parentheses for the same purpose: my_variable = ( "beginning of the string" "end of the string" ) For your specific case: self.poster_image_url = ( 'http://image.tmdb.org/t/p' '/w185' + str(detail_new[4]) ) self.trailer_youtube_url = ( 'https://www.youtube.com/watch?' 'v=' + str(self.get_trailer_link(movie_name)) )
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49771421
has comment: http://stackoverflow.com/comment/86558177
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86558212
type: Answer
has comment: http://stackoverflow.com/comment/86558145
answers question: http://stackoverflow.com/q/49771421
has comment: http://stackoverflow.com/comment/86558099

http://stackoverflow.com/q/49886483
has body: I am running Python3 on my Mac testing simple sql database. I have the below code import sqlite3 # connecting to the database connection = sqlite3.connect("myTable.db") crsr = connection.cursor() # SQL command to create a table in the database sql_command = """CREATE TABLE emp ( staff_number INTEGER PRIMARY KEY, fname VARCHAR(20), lname VARCHAR(30), gender CHAR(1), joining DATE);""" # execute the statement crsr.execute(sql_command) # SQL command to insert the data in the table sql_command = """INSERT INTO emp VALUES (23, "Rishabh", "Bansal", "M", "2014-03-28");""" crsr.execute(sql_command) crsr.execute(sql_command) connection.commit() connection.close() When I run this code, I am getting error: Traceback (most recent call last): File "test.py", line 8, in &lt;module&gt; connection = sqlite3.connect("myTable.db") sqlite3.OperationalError: unable to open database file What am I missing? I tried replacing ("myTable.db") with (".myTable.db") and ("./myTable.db") but same issue. Please suggest.
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49886737
score: 3
upvote count: 3
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/86789212
downvote count: 0
has title: python sqlite3.connect - unable to open database file
accepted answer: http://stackoverflow.com/a/49886737
favorite count: 0
type: Question

http://stackoverflow.com/q/49758896
has comment: http://stackoverflow.com/comment/86533383
has title: Python - Rotated Template Matching (not using Feature Matching)
answer count: 0
has comment: http://stackoverflow.com/comment/86536562
type: UnansweredQuestion
type: Question
has body: I’m looking for a method to do template matching (in Python), where the template is rotated (the angle is unknown). The scale is not modified: I just need to find the rigid body motion. The template is in fact a crop of the original image, rotated by an unknown angle. I've tried feature matching approaches, using SIFT, SURF, FAST, etc. The problem is that the template is small (around 90x90 pixels) and the keypoint detectors don't find enough strong keypoints (they filter them out). If I relax the constraints and take the keypoints anyway, when I search for point correspondences, I have a lot of outliers. If a filter the outliers with RANSAC, for example, again I have not enough point correspondences to find a transformation. The problem doesn't seem that difficult, given the template is originated from the original image (crop) and then rotated. Is there a method I didn't contemplate that is generally used for this kind of problems?
tagged with: template-matching
tagged with: python
tagged with: image-processing
tagged with: image-registration
score: 0

http://stackoverflow.com/comment/86673309
comment on: http://stackoverflow.com/a/49821430
type: AnswerComment
has text: Thanks -- it looks I still have homework to do. A related question, how do you recommend select number of clumbers K for cutree?
score: 0
type: Comment

http://stackoverflow.com/comment/86620627
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49797674
has text: @Patrick - I can't use the aws/aws cli/boto3 direct copy from one bucket to other. I just can't in my project :(. So I have to do the download and upload model :(.
type: Comment

http://stackoverflow.com/comment/86634127
comment on: http://stackoverflow.com/q/49809438
has text: @jezrael What's your NumPy version?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49809658
type: Answer
has comment: http://stackoverflow.com/comment/86635517
has comment: http://stackoverflow.com/comment/86634193
has comment: http://stackoverflow.com/comment/86634646
has comment: http://stackoverflow.com/comment/86635346
score: 0
has body: You may have a problem in this line return render(request,"registration/signup.html",{"form":form,"title"=title}) # here, should be {"form":form,"title":title} you have that problem twice. Please, try to format better your code next time.
answers question: http://stackoverflow.com/q/49809420
has comment: http://stackoverflow.com/comment/86634603

http://stackoverflow.com/q/49885332
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49885448
tagged with: primes
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49885656
accepted answer: http://stackoverflow.com/a/49885448
tagged with: math
has body: I have the following code which takes 2 inputs: an upper and lower limit. This then calculates the number of primes between the upper and lower. For example: Upper = 100, lower = 0, so the number of primes is 25. lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) total = 0 print("Prime numbers between",lower,"and",upper,"are:") for num in range(lower,upper + 1): # prime numbers are greater than 1 if num &gt; 1: for i in range(2,num): if (num % i) == 0: break else: print(num) total = total + 1 print("total primes found", total) I want to calculate the density of primes, so the density between 0-100 would be 25%. I'm not 100% sure if that's actually the density or the frequency. (I`ve been asked to find the density, not the frequency.) I was thinking something along these line (upper - lower) / total. That's obviously not the correct expression to calculate the density, but I can't seem to get my head around how I can do it.
score: 1
has title: Calculating Density in Python
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/49885656
downvote count: 0

http://stackoverflow.com/comment/86662491
type: Comment
score: 0
has text: @rollstuhlfahrer so I executed module "createTexture" from the Python Controller.
type: QuestionComment
comment on: http://stackoverflow.com/q/49822986

http://stackoverflow.com/comment/86684638
score: 0
comment on: http://stackoverflow.com/q/49834650
type: QuestionComment
type: Comment
has text: When you declared `mouseX` and `mouseY` to 0, they would now accept integer values. You can check this with `type(mouseX)` which returns `int`. If you want explicit conversion to integer, without these declarations, use `int(mouseX)`, `int(mouseY)`.

http://stackoverflow.com/q/49882253
has body: Good day, I have an html as string, where I need to find any class which has word 'content' there. For example: class='?content?' Where ? - any number of symbols or characters. I wanted to pass variable with the right string instead of 'entry-content'. However I can not input 'div[class*="content"] - it doesnt' work for me. If there is a way to match all classes with 'content' without preprocessing of html, that would be perfect. Its just that preproccessing was my initial idea. import pandas as pd import requests from bs4 import BeautifulSoup import sys import urllib USER_AGENT = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'} import re resultText = '' url = 'http://kakzarabativat.ru/soveti/s-chego-nachat-biznes-ili-poshagovyj-plan-starta-biznesa/' html = urllib.request.urlopen(url).read() content = soup.find('div', {'class': 'entry-content'}) raw = content.find_all('p') for item in raw: text = BeautifulSoup(str(item), 'html.parser').get_text() resultText += text + ' ' resultText = resultText.replace("\n", "") resultText = resultText.replace("\xa0", "") resultText = resultText.replace("\n\n ", "") Sorry If thats a stupid question, or I'm making it totally wrong.
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86780733
has comment: http://stackoverflow.com/comment/86780624
has comment: http://stackoverflow.com/comment/86780576
has comment: http://stackoverflow.com/comment/86782506
has comment: http://stackoverflow.com/comment/86780619
has title: Regular expression to find particular type of class in html
type: Question
has comment: http://stackoverflow.com/comment/86780414
has comment: http://stackoverflow.com/comment/86780628
linked to: http://stackoverflow.com/q/1732348
has comment: http://stackoverflow.com/comment/86781291
has comment: http://stackoverflow.com/comment/86780524
has comment: http://stackoverflow.com/comment/86781919
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/86780544
has comment: http://stackoverflow.com/comment/86781020
linked to: http://stackoverflow.com/q/34660417

http://stackoverflow.com/comment/86559381
has text: Possible duplicate of [Unable to install python libraries](https://stackoverflow.com/questions/49734434/unable-to-install-python-libraries)
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49768770

http://stackoverflow.com/a/49909056
type: Answer
answers question: http://stackoverflow.com/q/49909027
has body: The % operator, when used with a string as the left-hand argument, is for printf-style formatting. If you want to test the length of your strings, you need to convert from string to the length with len, e.g. myList3 = [ 'even' if len(x) % 2==0 else 'nope' for x in myNames]
score: 0

http://stackoverflow.com/q/49803308
has body: I was searching a way to get text from pdf file and found a pdfminer library, on github there was a working example. I have slightly modified it to pass arguments and it works fine when I use python to execute script. But I would like to have an exe file for that. I have used pyinstaller to create exe, unfortunatelly when I try to run the file I get following error: Traceback (most recent call last): File "onlypdfminer.py", line 5, in &lt;module&gt; File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "c:\python36-32\lib\site- packages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.__dict__) File "site-packages\pdfminer\pdfpage.py", line 10, in &lt;module&gt; File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "c:\python36-32\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.__dict__) File "site-packages\pdfminer\pdfdocument.py", line 12, in &lt;module&gt; File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "c:\python36-32\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 631, in exec_module exec(bytecode, module.__dict__) .... and this is my code: from io import StringIO from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage import os import sys import argparse parser=argparse.ArgumentParser(desc…
score: 2
has comment: http://stackoverflow.com/comment/86621558
tagged with: pyinstaller
tagged with: pdfminer
tagged with: python
has comment: http://stackoverflow.com/comment/86621660
has title: Python 3.6 - create exe with pyinstaller - error
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/49907145
upvote count: 2
has comment: http://stackoverflow.com/comment/86830179
downvote count: 0
has comment: http://stackoverflow.com/comment/86830359
has comment: http://stackoverflow.com/comment/86830328
has comment: http://stackoverflow.com/comment/86831772
has comment: http://stackoverflow.com/comment/86830123
has comment: http://stackoverflow.com/comment/86830465
type: Answer
has body: For a more pythonic solution, use collections.defaultdict or a collections.Counter: import collections new_dict = collections.defaultdict(int) # alternatively: new_dict = collections.Counter() for key, value in my_dict.items(): # converting the tuples to frozensets removes the order and makes # them hashable key = frozenset(key) new_dict[key] += value # turn the defaultdict with frozensets back into a normal dict with tuples new_dict = {tuple(key): value for key, value in new_dict.items()} Result: {('A', 'B'): 8, ('A', 'C'): 4} Keep in mind that this only works if the values in your tuples are unique. If there was a tuple like ('A', 'A') in the dict, calling frozenset on it would collapse it to {'A'} and produce incorrect output. If this is a concern, you can replace the line key = frozenset(key) with key = tuple(sorted(key)) to make it work correctly.
answers question: http://stackoverflow.com/q/49907090
has comment: http://stackoverflow.com/comment/86830709
score: 2

http://stackoverflow.com/q/49758589
has title: Why does a numpy array not appear to be much faster than a standard python list?
has answer: http://stackoverflow.com/a/49760495
favorite count: 0
has comment: http://stackoverflow.com/comment/86532282
type: Question
has comment: http://stackoverflow.com/comment/86533348
accepted answer: http://stackoverflow.com/a/49760495
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/86534234
possible better answer: http://stackoverflow.com/a/49760559
tagged with: parallel-processing
has body: From what I understand, numpy arrays can handle operations more quickly than python lists because they're handled in a parallel rather than iterative fashion. I tried to test that out for fun, but I didn't see much of a difference. Was there something wrong with my test? Does the difference only matter with arrays much bigger than the ones I used? I made sure to create a python list and numpy array in each function to cancel out differences creating one vs. the other might make, but the time delta really seems negligible. Here's my code: My final outputs were numpy function: 6.534756324786595s, list function: 6.559365831783256s import timeit import numpy as np a_setup = 'import timeit; import numpy as np' std_fx = ''' def operate_on_std_array(): std_arr = list(range(0,1000000)) np_arr = np.asarray(std_arr) for index,elem in enumerate(std_arr): std_arr[index] = (elem**20)*63134 return std_arr ''' parallel_fx = ''' def operate_on_np_arr(): std_arr = list(range(0,1000000)) np_arr = np.asarray(std_arr) np_arr = (np_arr**20)*63134 return np_arr ''' def operate_on_std_array(): std_arr = list(range(0,1000000)) np_arr = np.asarray(std_arr) for index,elem in enumerate(std_arr): std_arr[index] = (elem**20)*63134 return std_arr def operate_on_np_arr(): std_arr = list(range(0,1000000)) np_arr = np.asarray(std_arr) np_arr = (np_arr**20)*63134 return np_arr print('std',timeit.timeit(setup = a_setup, stmt = std_fx, number = 80000000)) print('par',timeit.timeit(setup = a_setup, stmt = parallel_fx, number = 80000000)) #operate_on_np_arr() #operate_on_std_array()
has comment: http://stackoverflow.com/comment/86535977
upvote count: 4
tagged with: numpy
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49760559
has comment: http://stackoverflow.com/comment/86533199
has comment: http://stackoverflow.com/comment/86534244
tagged with: arrays
has comment: http://stackoverflow.com/comment/86532207
downvote count: 0

http://stackoverflow.com/comment/86947033
type: Comment
comment on: http://stackoverflow.com/a/49956566
score: 0
type: AnswerComment
has text: 3: it's true after refactoring, it's not sure it's true if we consider all solutions. I may think about it.

http://stackoverflow.com/a/49820179
has comment: http://stackoverflow.com/comment/86655938
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/86655608
score: 4
has comment: http://stackoverflow.com/comment/86684937
downvote count: 0
answers question: http://stackoverflow.com/q/49819922
has body: You should add handler for socket.timeout exception: import http.client import socket activeTanks = 4 # no semicolon here myTanks = [100, 100, 100, 100] for tank in range(0, activeTanks): tankAddress = ("192.168.1.4" + str(tank)) conn = http.client.HTTPConnection(tankAddress, timeout=1) try: conn.request("GET", "/Switch=Read") except socket.timeout as st: # do some stuff, log error, etc. print('timeout received') except http.client.HTTPException as e: # other kind of error occured during request print('request error') else: # no error occurred r1 = conn.getresponse() # do some stuff with response myTanks[tank] = int(r1.read().decode('ASCII').split("...")[1]) finally: # always close the connection conn.close() print(myTanks)

http://stackoverflow.com/comment/86613899
score: 1
type: Comment
type: QuestionComment
has text: You don't need `f.close()` in the `with` block. It will automatically be closed when you exit the `with` block.
comment on: http://stackoverflow.com/q/49799566

http://stackoverflow.com/comment/86666517
type: AnswerComment
comment on: http://stackoverflow.com/a/49824929
score: 0
has text: @jpp Not sure what you mean. Just returning a value without adding it to the dict is as simple as implementing `__missing__` (see first example). It's only a problem to detect changes when you don't assign to the dictionary directly. Could you indicate what kind of behavior you want (i.e. a code snippet that you want to work)?
type: Comment

http://stackoverflow.com/a/49774165
type: Answer
has comment: http://stackoverflow.com/comment/86563613
has comment: http://stackoverflow.com/comment/86563661
accepted answer of: http://stackoverflow.com/q/49773873
score: 2
has body: Simple solution: instead of returning a tuple of lists, return a dict of lists where keys are the subdicts keys and values the lists of collected values: from collections import defaultdict def get_contacts(): id = [10, 12] results = defaultdict(list) for j in id: obj = d[j] for key, value in obj.items(): results[key].append(value) return results results = get_contacts() for k, v in results.items(): print("{} : {}".format(k, v)) As a general rule: when you think you need "dynamic names", you really want a dict. EDIT: names, emails, managers = get_contacts() for name, email, manager in zip(names, emails, managers): # ... => results = get_contacts() names, emails, managers = results["Owner Name"], results['Manager Name'], results["Email"] for name, email, manager in zip(names, emails, managers): # ...
upvote count: 2
answers question: http://stackoverflow.com/q/49773873
has comment: http://stackoverflow.com/comment/86564665
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86565411

http://stackoverflow.com/q/49887076
has comment: http://stackoverflow.com/comment/86791782
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
has body: Let's say I did 16 experiments replicated 3 times for a total of 48 measures. Here's an example of my dataframe and a snippet that replicates my problem: import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame(np.abs(np.random.randn(48, 4)), columns=list("ABCD")) color_list = plt.cm.gnuplot(np.linspace(0,1,16)) df.A.plot.bar( figsize=(16,7), color=color_list) plt.axvline(15.5, c="black", lw=1) plt.axvline(31.5, c="black", lw=1) plt.plot() And here's the output of the graph: So, the vertical lines represents each replica, there is 16 bars in each. My color list is also of length 16 so I would expect to have 3 times the same colors, but at 16 and 17, there is two black bars (which is the 0th color in the list) and at 32, there is this yellow bar that comes from the offset caused by the second black line at 17. Followed by 2 black lines again. It looks like my color_list puts a 0 automatically when it starts for the second time. Edit : My temporary solution was to create a list of length 48 that is the first list repeated 3 times: lst=list(np.linspace(0,1,16)) liste = lst + lst + lst color_list = plt.cm.gnuplot(liste)
upvote count: 1
tagged with: python
has title: Matplotlib error while coloring barplot with list
has comment: http://stackoverflow.com/comment/86827528
answer count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86827369
has comment: http://stackoverflow.com/comment/86825778
tagged with: matplotlib
score: 1

http://stackoverflow.com/q/49911206
has body: I'm using Keras for a regression task and want to restrict my output to a range (say between 1 and 10) Is there a way to ensure this?
has answer: http://stackoverflow.com/a/49911669
has answer: http://stackoverflow.com/a/49911299
linked to: http://stackoverflow.com/q/43099233
has comment: http://stackoverflow.com/comment/86838447
has comment: http://stackoverflow.com/comment/86838384
has title: How to restrict output of a neural net to a specific range?
favorite count: 0
has comment: http://stackoverflow.com/comment/86838562
upvote count: 11
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: regression
downvote count: 0
tagged with: neural-network
tagged with: python
score: 11
tagged with: keras

http://stackoverflow.com/q/49831841
has title: Python selenium failing on same function on 2nd time
has body: I am using page object model in unittest. There is a function "screenshot" which is passing in 1 test case but failing in another. It is really strange and since it is passing in 1 test case, i am sure about having all the dependancies. Any help would be appreciated. Code: import ... class Abc(unittest.TestCase): def setUp(self): self.xvfb = Xvfb(width=1280, height=720) self.xvfb.start() self.driver = webdriver.Firefox() self.driver.get(data.baseurl) def test_001_login(self): home_page = home.HomePage(self.driver) home_page.login(data.username, data.password) home_page.screenshot(self.id() + "_login_success") def test_002_test_scenario(self): home_page = home.HomePage(self.driver) self.driver.get(data.baseurl) home_page.screenshot(self.id() + "_home_page") def tearDown(self): self.driver.close() self.xvfb.stop if __name__ == "__main__": unittest.main() Error: Traceback (most recent call last): File "/opt/buildagent/work/a8b2d36194b9264b/webtest/functions/alerts/test_alerts.py", line 65, in test_002_scenario home_page.screenshot(self.id() + "_home_page") File "/opt/buildagent/work/a8b2d36194b9264b/webtest/functions/home/home.py", line 107, in screenshot self.driver.save_screenshot(tmp) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 1031, in save_screenshot return self.get_screenshot_as_file(filename) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 1008, in get_screenshot_as_file png = self.get_screenshot_as_png() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 1040, in get_screenshot_as_png return base64.b64decode(self.get_screenshot_as_base64().encode('ascii')) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 1050, in get_screenshot_as_base64 return self.execute(Command.SCREENSHOT)['value'] File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute s…
type: UnansweredQuestion
tagged with: selenium-firefoxdriver
has comment: http://stackoverflow.com/comment/91493182
tagged with: python
tagged with: selenium-webdriver
score: 2
answer count: 0
upvote count: 2
tagged with: marionette
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/86688066
has comment: http://stackoverflow.com/comment/86692865
favorite count: 0
type: Question

http://stackoverflow.com/q/49805800
has comment: http://stackoverflow.com/comment/86632751
has comment: http://stackoverflow.com/comment/86745825
has answer: http://stackoverflow.com/a/69757751
has comment: http://stackoverflow.com/comment/86630980
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: windows-7
has title: Muting/Unmuting speakers in Python
type: UnansweredQuestion
has body: I'm trying to create a piece of Malware that plays an audio file and doesn't allow the user to easily cancel play of the file. I've tested some code from https://python-forum.io/Thread-How-to-change-the-sound-volume-with-python and ran into an issue. The following code does change the volume levels of the computer but it doesn't unmute it. EX: from ctypes import cast, POINTER from comtypes import CLSCTX_ALL from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume devices = AudioUtilities.GetSpeakers() interface = devices.Activate( IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) # Control volume volume.SetMasterVolumeLevel(-0.0, None) #max volume.SetMasterVolumeLevel(-5.0, None) #72% volume.SetMasterVolumeLevel(-10.0, None) #51% I'm creating this malware as a student project so would appreciate some help (I'm also not incredibly familiar with libraries past some very basic Python libraries.)
tagged with: python
tagged with: audio
score: 3
has comment: http://stackoverflow.com/comment/86744699
upvote count: 3
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49801117
tagged with: python
score: 2
tagged with: selenium-chromedriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49804725
has comment: http://stackoverflow.com/comment/86623903
has body: I made some minor modifications to the Chromium browser and built a custom version that does some logging on stderr. I would like to control this browser with Selenium (Python version) and read these stderr logs. The following is a minimal example of what I am doing: from selenium import webdriver from selenium.webdriver.chrome.options import Options import os.path options = Options() options.binary_location = '/home/phani/chromium/src/out/Default/chrome' options.add_argument('--user-data-dir=/tmp/') driver = webdriver.Chrome(executable_path=os.path.abspath("chromedriver"), chrome_options=options) driver.get('http://www.facebook.com') Can someone tell me how I can read the logs produced by the Chromium browser? For Firefox, there is an argument called "log_file" which allows us to direct output from the browser to stdout/stderr if we prefer. https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.firefox_binary.html#module-selenium.webdriver.firefox.firefox_binary Is there something similar for Chromium?
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/86618580
favorite count: 0
type: Question
upvote count: 2
has title: Read stdout and stderr logs from selenium controlled chrome browser
accepted answer: http://stackoverflow.com/a/49804725
has comment: http://stackoverflow.com/comment/86624142
answer count: 1

http://stackoverflow.com/a/49893238
has comment: http://stackoverflow.com/comment/86802245
score: 0
answers question: http://stackoverflow.com/q/49893143
has comment: http://stackoverflow.com/comment/86803034
has comment: http://stackoverflow.com/comment/86802334
has comment: http://stackoverflow.com/comment/86802858
type: Answer
has body: For points as, Training my neural network in Tensorflow is running in python consuming all my CPU In my opinion issue happen more with CPU (if I consider it a normal CPU system) , and thats why they gave support for GPU (so Tenserflow execution could not load CPU more) It would be best to say, Tenserflow library (or package) is running (or being used) in Python language. Its like, Tenserflow is giving you some support for creating Neural Network (with ease) , so it can be portrayed as " Neural Network created using Tenserflow library is executing under Python language. " Collectively it can be best written as , " Training my Neural Network using supportive NN from Tenserflow is executing in Python language that is consuming almost my system's complete CPU resources. " Note: Please ignore my grammar mistakes. :P

http://stackoverflow.com/comment/86912766
has text: Did this help you? Could you get it working? If so, I would appreciate if you marked the answer as accepted.
type: Comment
comment on: http://stackoverflow.com/a/49797987
score: 0
type: AnswerComment

http://stackoverflow.com/q/49896242
answer count: 2
has answer: http://stackoverflow.com/a/49896411
upvote count: 0
downvote count: 1
favorite count: 0
has title: whole DNA file Slice to a fixed length substring by index/location
type: Question
possible better answer: http://stackoverflow.com/a/49896411
accepted answer: http://stackoverflow.com/a/49896551
tagged with: python
has answer: http://stackoverflow.com/a/49896551
tagged with: slice
has body: I am new to python, I am writing code to slice a DNA sequence. the idea is to : firstly to count the sequence length in the text file, secondly, to slice the sequence into substrings with length of 5. and finally to write each substring in a line in output text file. I couldn't figure out how to split the sequence from each character with the same length, let us say the text file contain [ACTGTATGCATACACGTA...] the results should be like ACTGT , CTGTA, TGTAT, ... I need help with the incremental loop function that can help to split/slice by index/location
score: -1
type: AnsweredQuestion
tagged with: sequences

http://stackoverflow.com/a/49811269
has comment: http://stackoverflow.com/comment/86637276
has body: I think there are Nones in tuples, so need filter it out col = [tuple([str.replace(i, "\x1c"," ") for i in tup if pd.notnull(i)]) for tup in col] Or replace non Nones values only: col=[tuple([str.replace(i, "\x1c"," ") if pd.notnull(i) else i for i in tup ]) for tup in col] EDIT: Thank you @Paul Cornelius for suggestion use string.replace: col = [tuple([i.replace("\x1c"," ") for i in tup if pd.notnull(i)]) for tup in col] col = [tuple([i.replace("\x1c"," ") if pd.notnull(i) else i for i in tup ]) for tup in col]
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86637248
downvote count: 0
answers question: http://stackoverflow.com/q/49811130
upvote count: 1

http://stackoverflow.com/comment/86844730
score: 0
type: AnswerComment
has text: I searched google many times for this and maybe I tried somethings like your link about setuptools. The tutorial in your link is quite long. Maybe I missed something so I cannot resolve the issue.
comment on: http://stackoverflow.com/a/49913004
type: Comment

http://stackoverflow.com/a/49833549
answers question: http://stackoverflow.com/q/49833313
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has body: I'm going to start out assuming that you can import the data without any issues, and you have already separated the x-data into Image and Features, and you have the y data as the labels of each image. You can use the keras functional api to have a neural network take multiple inputs. from keras.models import Model from keras.layers import Conv2D, Dense, Input, Embedding, multiply, Reshape, concatenate img = Input(shape=(64, 64, 3)) features = Input(shape=(14,)) embedded = Embedding(input_dim=14, output_dim=60*32)(features) embedded = Reshape(target_shape=(14, 60,32))(embedded) encoded = Conv2D(32, (3, 3), activation='relu')(img) encoded = Conv2D(32, (3, 3), activation='relu')(encoded) x = concatenate([embedded, encoded], axis=1) x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) main_output = Dense(1, activation='sigmoid', name='main_output')(x) model = Model([img, features], [main_output])
type: Answer
has comment: http://stackoverflow.com/comment/86703028
accepted answer of: http://stackoverflow.com/q/49833313
has comment: http://stackoverflow.com/comment/86693450

http://stackoverflow.com/a/49768294
accepted answer of: http://stackoverflow.com/q/49764862
score: 1
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/49764862
has body: from conllu import parse with open('conllu_text', 'r') as txt: data = txt.read() children = [] parents = [] grandparents = [] for i in range(len(parse(data)[0])): children.append(i+1) parents.append(parse(data)[0][i]['head']) grandparents.append(parse(data)[0][parse(data)[0][i]['head'] -1]['head']) result = list(zip(grandparents, parents, children))
downvote count: 0
type: Answer

vectorization
tags question: http://stackoverflow.com/q/49765382
tags question: http://stackoverflow.com/q/49880927
tags question: http://stackoverflow.com/q/49903830
tags question: http://stackoverflow.com/q/49798451
tag name: vectorization
type: Tag
tags question: http://stackoverflow.com/q/49759832
tags question: http://stackoverflow.com/q/49762199
tags question: http://stackoverflow.com/q/49877436
tags question: http://stackoverflow.com/q/49890820

http://stackoverflow.com/comment/86552228
type: QuestionComment
type: Comment
has text: This is not a promming but a database administration question. There are sibling sites if SO which are better suited for this topic.
score: 0
comment on: http://stackoverflow.com/q/49768475

http://stackoverflow.com/a/49903333
has comment: http://stackoverflow.com/comment/86825762
has comment: http://stackoverflow.com/comment/86834819
type: Answer
has comment: http://stackoverflow.com/comment/86830086
score: 1
has comment: http://stackoverflow.com/comment/86827689
has comment: http://stackoverflow.com/comment/86827536
has comment: http://stackoverflow.com/comment/86829616
has comment: http://stackoverflow.com/comment/86825841
has comment: http://stackoverflow.com/comment/86829227
answers question: http://stackoverflow.com/q/49902650
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86830802
has body: You can, still using http.server, but using a custom handler... class MockHandler(http.server.BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' def do_GET(self): if 'text/html' not in self.headers['Accept']: self.send_response(406) else: self.send_response(200) self.end_headers() self.wfile.write(b'some data') class ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer): pass server_address = ('localhost', 8888) server = ThreadedHTTPServer(server_address, MockHandler) server.daemon_threads = True thread = threading.Thread(target=server.serve_forever) thread.daemon = True thread.start() (Note: it's a HTTP 1.1 server, since most servers are these days, and it's thread/multiple request-safe, but you can probably simplify if you would like...) A full example in a small test-suite-of-one along with an example "production" function that you might want to test is below. import http.server import socketserver import threading import unittest import urllib.request def example_production_function(accept_header): req = urllib.request.Request('http://localhost:8888', headers={'Accept': accept_header}); try: urllib.request.urlopen(req) return 'Allowed' except urllib.error.HTTPError as e: return 'Not allowed' class TestServer(unittest.TestCase): def test(self): class MockHandler(http.server.BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' def do_GET(self): if 'text/html' not in self.headers['Accept']: self.send_response(406) else: self.send_response(200) self.end_headers() self.wfile.write(b'some data') class ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer): pass server_address = ('localhost', 8888) server = ThreadedHTTPServer(server_address, MockHandler) server.daemon_threads = True thread = threading.Thread(target=server.serve_forever) thread.daemon = True thread.start() result = example_production_function('text/html') self.assertEqual(result, 'Allowed') result = example_production_function('application/json') self.assertEqual…

http://stackoverflow.com/comment/86690777
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49837765
has text: Nice, forgot numpy could test the truthiness of ints (unlike pandas which _needs_ a boolean mask).
type: Comment

logging
tags question: http://stackoverflow.com/q/49796701
tags question: http://stackoverflow.com/q/49820264
tags question: http://stackoverflow.com/q/49864698
tag name: logging
tags question: http://stackoverflow.com/q/49871041
tags question: http://stackoverflow.com/q/49834712
tags question: http://stackoverflow.com/q/49870451
tags question: http://stackoverflow.com/q/49760576
tags question: http://stackoverflow.com/q/49782180
tags question: http://stackoverflow.com/q/49882433
tags question: http://stackoverflow.com/q/49851074
type: Tag
tags question: http://stackoverflow.com/q/49781573
tags question: http://stackoverflow.com/q/49880267

http://stackoverflow.com/q/49821763
accepted answer: http://stackoverflow.com/a/49822196
has title: django query to retrieve dictionary of children values keyed by parent name?
has comment: http://stackoverflow.com/comment/86659848
has body: With the following models with a one-to-many relationship, where a kid can have some collection of toys: class Kid(models.Model): name = models.CharField(max_length=200) class Toy(models.Model): name = models.CharField(max_length=200) material = models.CharField(max_length=200) owner = models.ForeignKey(Kid) I would like to generate a dictionary with kid names as keys and a list of tuples as values. The following query gets me the list of tuples as shown: kids = Kid.objects.all() kids.filter( toy__name__in[ some list of names ] ).\ values_list( 'name', 'toy__name', 'toy__material' ) [ ( 'billy', 'hotwheelscar', 'metal' ), ( 'billy', 'actionFigure', 'plastic' ), ( 'sam', 'hotwheelscar', 'metal' ), ( 'sam', 'doll', 'plastic' ), ( 'sam', 'dollHouse', 'plastic' ), ( 'jimmy', 'hotwheelscar', 'metal' ), ( 'jimmy', 'actionFigure', 'plastic' ) ] But is there a way I could get these results in a form like the following: { 'billy': [ ( 'hotwheelscar', 'metal' ), ( 'actionFigure', 'plastic' ) ], 'sam': [ ( 'hotwheelscar', 'metal' ), ( 'doll', 'plastic' ), ( 'dollhouse', 'plastic' ) ], 'jimmy': [ ( 'hotwheelscar', 'metal' ), ( 'actionFigure', 'plastic' ) ] } Without having to first retrieve the values_list of tuples as I have done and then iterate over them creating a dictionary myself? The structure of the values being represented in a list of tuples is not important, it could be a nested dictionary or something else but I just want to have all the toys for a kid available by keying the resulting dictionary by kid name. Thanks in advance.
type: Question
downvote count: 0
answer count: 1
tagged with: django
linked to: http://stackoverflow.com/q/38017076
upvote count: 1
has comment: http://stackoverflow.com/comment/86659649
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49822196
tagged with: dictionary

http://stackoverflow.com/a/49904426
has comment: http://stackoverflow.com/comment/86826284
has comment: http://stackoverflow.com/comment/86827860
has comment: http://stackoverflow.com/comment/86825857
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86826114
type: Answer
answers question: http://stackoverflow.com/q/49903991
has comment: http://stackoverflow.com/comment/86825713
has comment: http://stackoverflow.com/comment/86825994
has comment: http://stackoverflow.com/comment/86827688
has comment: http://stackoverflow.com/comment/86827991
score: 0
accepted answer of: http://stackoverflow.com/q/49903991
has comment: http://stackoverflow.com/comment/86827770
has comment: http://stackoverflow.com/comment/86824844
has comment: http://stackoverflow.com/comment/86829689
has comment: http://stackoverflow.com/comment/86827572
has body: From what i read, you want to have a Robot Class that has multiple Motor's class or something like that, maybe this could work as a hint on how that could be done: class Motor: def __init__(self, motor): self.motor = motor def go_slow(self): self.motor.setval = 100 def go_fast(self): self.motor.setval = 255 class Robot: def ___init___(self, reference_motor1, reference_motor2): self.motor1 = Motor(reference_motor1) self.motor2 = Motor(reference_motor1) def go_straight_slow(): self.motor1.go_slow() self.motor2.go_slow() def go_straight_fast(): self.motor1.go_fast() self.motor2.go_fast() here's a dummy example on how your code maybe look like if you wanna do it object oriented. Edit: assuming that you already got the class that "MotorController" class MotorController: def __init__(self): pass def goStraight(): pass class Robot: def ___init___(self): self.motor_controllers = [] #List for storing all motors def add_motor_reference(self, reference): self.motor_controllers.append(MotorController(reference)) #Appends new motors to the list def go_straight(self): for motor_controller in self.motor_controllers: motor_controller.goStraight() #Executes for the "goStraight" function on every motor in the list Edit: If you want to add the motors on the constructor of the class you could do something like: class Robot: def ___init___(self, *args): self.motor_controllers = [] #List for storing all motors for motor in args: self.motor_controllers.append(MotorController(motor)) #Here every motor reference you pass will be automatically added in the list of motor controllers.
has comment: http://stackoverflow.com/comment/86828051

folium
tags question: http://stackoverflow.com/q/49760098
tag name: folium
tags question: http://stackoverflow.com/q/49866021
type: Tag

http://stackoverflow.com/comment/86587672
has text: Glad to help! Notice this method will merely truncate the float at a given position and not perform true "rounding"
type: AnswerComment
comment on: http://stackoverflow.com/a/49785808
score: 0
type: Comment

http://stackoverflow.com/comment/86785260
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49883681
has text: Your solution doesn't work. `ValueError: too many values to unpack (expected 2)`

http://stackoverflow.com/q/49908004
tagged with: aggregate
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49909795
downvote count: 0
linked to: http://stackoverflow.com/q/40710811
score: 4
favorite count: 0
has body: I am grouping by item-date pairs in a PD dataframe and would like to add some custom conditional functions using lambda to a larger aggregation function. Using the tip here, I can do the following, which works properly and counts positive and negative values in the given column. item_day_count=item_day_group['PriceDiff_pct'].agg({'Pos':lambda val: (val &gt; 0).sum(),'Neg':lambda val: (val &lt;= 0).sum()}).reset_index() And I can also do a different aggregate that contains both pre-built aggregations and a custom percentile function that returns proper stats: item_day_count_v2=item_day_group['PriceDiff_pct'].agg(['count','min',percentile(25),'mean','median',percentile(75),'max']).reset_index() But I cannot figure out how to combine these into one larger function - I get the error : AttributeError: 'DataFrameGroupBy' object has no attribute 'name' when I try the below: item_day_count_v3=item_day_group['PriceDiff_pct'].agg(['count',{'Pos_Return':lambda val: (val &gt; 0).sum(),'Neg_Return':lambda val: (val &lt;= 0).sum()},'min',percentile(25),'mean','median',percentile(75),'max']).reset_index() Does anyone know how to combine these functions? Seems like it I am close considering both work separately. Thanks for your help!
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/49908718
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/49908873
has title: Pandas Groupby: Aggregate and Conditional

http://stackoverflow.com/a/49820132
score: 2
has body: Use a positive lookbehind to ensure the dot is preceded by a digit - sep='(?&lt;=\d)\.|\t' For example: import pandas as pd import io columns = ["Rank", "ID", "Description"] sighits_section = '''1. NC_002523_1\tSerratia entomophila plasmid pADAP, complete sequence. 2. NZ_CM003366_0\tPantoea ananatis strain CFH 7-1 plasmid CFH1-7plasmid2, whole genome shotgun sequence. 3. NZ_CP014491_0\tEscherichia coli strain G749 plasmid pG749_3, complete sequence. 4. NC_015062_0\tRahnella sp. Y9602 plasmid pRAHAQ01, complete sequence.'''.splitlines() tab = pd.read_table(io.StringIO(u'\n'.join([row.rstrip('.') for row in sighits_section])), sep='(?&lt;=\d)\.|\t', engine='python', names=columns) print(tab) prints Rank ID Description 0 1 NC_002523_1 Serratia entomophila plasmid pADAP, complete s... 1 2 NZ_CM003366_0 Pantoea ananatis strain CFH 7-1 plasmid CFH1-7... 2 3 NZ_CP014491_0 Escherichia coli strain G749 plasmid pG749_3, ... 3 4 NC_015062_0 Rahnella sp. Y9602 plasmid pRAHAQ01, complete ... For extra safety, you might want to add the space in as your separator alongside the dot - sep='(?&lt;=\d)\.\s|\t' - to mitigate in case you have e.g. 10.1 in your descriptions somewhere. This isn't bombproof by any means. Safer yet - seeing as you're processing your data one line at a time, you can add in an assertion that the digit is the first character in the string too with sep='(?&lt;=^\d)\.\s|\t'. However, this will crash on digits higher than 10.
has comment: http://stackoverflow.com/comment/86655435
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49819880
answers question: http://stackoverflow.com/q/49819880
has comment: http://stackoverflow.com/comment/86655623
type: Answer
has comment: http://stackoverflow.com/comment/86655722

http://stackoverflow.com/q/49883623
has title: Implementing for loop in an if statement
tagged with: python
type: AnsweredQuestion
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/49883722
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86784964
has comment: http://stackoverflow.com/comment/86783561
favorite count: 0
has comment: http://stackoverflow.com/comment/86783475
type: Question
has comment: http://stackoverflow.com/comment/86784872
has answer: http://stackoverflow.com/a/49883813
possible better answer: http://stackoverflow.com/a/49883813
has answer: http://stackoverflow.com/a/49883682
has body: Am trying to solve project euler question : 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? I've come up with the python solution below, but is there any way to loop the number in the if instead of having to write all of them. def smallest_m(): start=1 while True: if start%2==0 and start%3==0 and start%4==0 and start%5==0 and start%5==0 and start%6==0 and start%7==0 and start%8==0 and start%9==0 and start%10==0 and start%11==0 and start%12==0 and start%13==0 and start%14==0 and start%15==0 and start%16==0 and start%17==0 and start%18==0 and start%19==0 and start%20==0: print(start) break else: start+=1 smallest_m()
tagged with: algorithm
has answer: http://stackoverflow.com/a/49883722
has comment: http://stackoverflow.com/comment/86783625
has comment: http://stackoverflow.com/comment/86783304
tagged with: range

http://stackoverflow.com/comment/86597488
type: Comment
has text: what do you mean by "is different to `[0, 0]`"? just replace the line `row += [0, 0]` with what you want to start with :) please accept as well!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49781417

http://stackoverflow.com/q/49899351
possible better answer: http://stackoverflow.com/a/66259485
has body: I am trying to do some multiprocessing with functions that I dynamically create within other functions. It seems I can run these if the function fed to ProcessPoolExecutor is module-level: def make_func(a): def dynamic_func(i): return i, i**2 + a return dynamic_func f_dyns = [make_func(a) for a in range(10)] def loopfunc(i): return f_dyns[i](i) with concurrent.futures.ProcessPoolExecutor(3) as executor: for i,r in executor.map(loopfunc, range(10)): print(i,":",r) output: 0 : 0 1 : 2 2 : 6 3 : 12 4 : 20 5 : 30 6 : 42 7 : 56 8 : 72 9 : 90 However I can't do it if the multiprocessing is launched by a class function: class Test: def __init__(self,myfunc): self.f = myfunc def loopfunc(self,i): return self.f(i) def run(self): with concurrent.futures.ProcessPoolExecutor(3) as executor: for i,r in executor.map(self.loopfunc, range(10)): print(i,":",r) o2 = Test(make_func(1)) o2.run() output: Traceback (most recent call last): File "/home/farmer/anaconda3/envs/general/lib/python3.6/multiprocessing/queues.py", line 234, in _feed obj = _ForkingPickler.dumps(obj) File "/home/farmer/anaconda3/envs/general/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) AttributeError: Can't pickle local object 'make_func.&lt;locals&gt;.dynamic_func' On the other hand, I can run the multiprocessing on a class function just fine if I don't use a dynamically generated function in there. Is there some way around this? I tried adding the dynamically generated function to the 'globals' dictionary but that didn't seem to help: def make_func_glob(a): def dynamic_func(i): return i, i**2 + a globals()['my_func_{0}'.format(a)] = dynamic_func make_func_glob(1) print("test:", my_func_1(3)) o3 = Test(my_func_1) o3.run() output: test: (3, 10) Traceback (most recent call last): File "/home/farmer/anaconda3/envs/general/lib/python3.6/multiprocessing/queues.py", line 234, in _feed obj = _ForkingPickler.dumps(obj) File "/home/farmer/anaconda3/envs/general/lib/python3.6/m…
has answer: http://stackoverflow.com/a/66259485
answer count: 2
downvote count: 0
tagged with: pickle
tagged with: python
accepted answer: http://stackoverflow.com/a/49900573
type: Question
has answer: http://stackoverflow.com/a/49900573
type: AnsweredQuestion
upvote count: 3
score: 3
has title: Restrictions on dynamically created functions with concurrent.futures.ProcessPoolExecutor
favorite count: 0
tagged with: multiprocessing

http://stackoverflow.com/comment/86687022
has text: it is going on else statement i have also switched from text to enter widget and it is working ...thinking why it is not working on it
type: Comment
comment on: http://stackoverflow.com/a/49835928
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86635604
has text: I added the code and the output in the question. The question that I need answer to is : I see a lot of procedural methods that correspond to C callable library, but I am not able to use them. I am assuming these functions will be much faster than the stock cplex.Cplex.variables.add() functions ( sorry, cannot shake my c callable library experience).
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49800726

http://stackoverflow.com/comment/86568039
has text: @Hatshepsut Yeah, you can do `i['1'] = i['1'].radd('*')` before the `combine_first` step.
type: Comment
comment on: http://stackoverflow.com/a/49776209
type: AnswerComment
score: 0

http://stackoverflow.com/comment/87146543
comment on: http://stackoverflow.com/a/49824566
type: Comment
type: AnswerComment
score: 0
has text: You probably don't need to reinstall Python itself. Just the IronPython extension since it's the package that is throwing the error. If you can't use pip, you can download the package from pythonhosted, save it to your site-packages directory and then manually run it's setup.py instead.

http://stackoverflow.com/comment/86648361
has text: Very good catch on **cpname** error. This does display the two plots together...
type: AnswerComment
comment on: http://stackoverflow.com/a/49816197
type: Comment
score: 0

http://stackoverflow.com/comment/86740269
comment on: http://stackoverflow.com/q/49861233
has text: Alright, Glad it worked out at the end :)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49856803
has comment: http://stackoverflow.com/comment/86729786
has comment: http://stackoverflow.com/comment/86728956
answers question: http://stackoverflow.com/q/49856748
type: Answer
has comment: http://stackoverflow.com/comment/86728731
has comment: http://stackoverflow.com/comment/86730062
upvote count: 2
has comment: http://stackoverflow.com/comment/86733144
has comment: http://stackoverflow.com/comment/86730939
score: 1
has comment: http://stackoverflow.com/comment/86729222
has comment: http://stackoverflow.com/comment/86729072
has comment: http://stackoverflow.com/comment/86734657
downvote count: 1
has comment: http://stackoverflow.com/comment/86737169
has body: EDIT: You can simplify your code using a single view, using the submit value to differentiate the handling of the first form and the second one. The modified code is: class PerfectForm(Form): inputNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')]) class PerfectRangeForm(Form): startNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')]) endNumber = IntegerField('input a number', default=1, validators=[InputRequired(message='Please input an integer')]) aliquot = StringField('input a kind', default='perfect') @app.route('/', methods=['GET', 'POST']) def index(): form1 = PerfectForm(request.form, prefix="form1") form2 = PerfectRangeForm(request.form, prefix="form2") num = 1 Classify = classify(num) startNumber = 1 endNumber = 1 aliquot = 'abundant' ListInRange = listInRange(startNumber, endNumber, aliquot) if request.form.get('submit') == 'submit-1': if form1.validate_on_submit() and form1.data: num = form1.data['inputNumber'] Classify = classify(num) elif request.form.get('submit') == 'submit-2': if form2.validate_on_submit() and form2.data: startNumber = form2.data['startNumber'] endNumber = form2.data['endNumber'] aliquot = form2.data['aliquot'] ListInRange = listInRange(startNumber, endNumber, aliquot) return render_template('index.html', num=num, classify=Classify, startNumber=startNumber, endNumber=endNumber, aliquot=aliquot, ListInRange=ListInRange, form1=form1, form2=form2) if __name__ == '__main__': app.run(debug=True) and the modified template index.html is: {% from "_formhelpers.html" import render_field %} WTForms {{ form1.csrf_token }} {{ render_field(form1.inputNumber) }} {% if num %} {{ num }} is {{ classify }} {% endif %} {{ form2.csrf_token }} Input a start number and an end number to return a list of... Abundant Perfect Deficient ...numbers within that range {{ render_field(form2.startNumber) }} {{ render_field(form2.endNumber) }} T…
has comment: http://stackoverflow.com/comment/86731419
has comment: http://stackoverflow.com/comment/86731577

http://stackoverflow.com/comment/86670617
comment on: http://stackoverflow.com/q/49827567
score: 0
type: QuestionComment
has text: What are you trying to do? What is the expected output? You can use `type(var) is str` for type matching.
type: Comment

http://stackoverflow.com/comment/86584847
comment on: http://stackoverflow.com/q/49783757
has text: I think , that won't work. I am trying to solve a maze and so, for each cell I am trying to find the best move using value iteration. For value iteration , I need to find Utility for each cell. For each cell, I have 4 actions : Move Left, Move Right , Move Up and Move Down. The above code just shows one such function. But in actual problem, my utility will be max of values of each action. Hence for each cell I will have to apply 4 such functions as shown above One such calculation for a matrix will be a single iteration. I need to iterate over new matrix again.This process is repeated.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49890866
has title: Different accuracy between python keras and keras in R
score: 7
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86811535
upvote count: 7
has comment: http://stackoverflow.com/comment/86799030
has comment: http://stackoverflow.com/comment/86845135
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86797594
accepted answer: http://stackoverflow.com/a/50164666
linked to: http://stackoverflow.com/q/42022950
has comment: http://stackoverflow.com/comment/86799422
has answer: http://stackoverflow.com/a/50164666
has comment: http://stackoverflow.com/comment/87365073
tagged with: python
tagged with: keras
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
has body: I build a image classification model in R by keras for R. Got about 98% accuracy, while got terrible accuracy in python. Keras version for R is 2.1.3, and 2.1.5 in python following is the R model code: model=keras_model_sequential() model=model %&gt;% layer_conv_2d(filters = 32,kernel_size = c(3,3),padding = 'same',input_shape = c(187,256,3),activation = 'elu')%&gt;% layer_max_pooling_2d(pool_size = c(2,2)) %&gt;% layer_dropout(.25) %&gt;% layer_batch_normalization() %&gt;% layer_conv_2d(filters = 64,kernel_size = c(3,3),padding = 'same',activation = 'relu') %&gt;% layer_max_pooling_2d(pool_size = c(2,2)) %&gt;% layer_dropout(.25) %&gt;% layer_batch_normalization() %&gt;% layer_flatten() %&gt;% layer_dense(128,activation = 'relu') %&gt;% layer_dropout(.25)%&gt;% layer_batch_normalization() %&gt;% layer_dense(6,activation = 'softmax') model %&gt;%compile( loss='categorical_crossentropy', optimizer='adam', metrics='accuracy' ) I try to rebuild a same model in python, with same input data. While, got totally different performance. The accuracy even less than 30% Because R keras is calling python for run keras. With same model architecture, they should get similar performance. I wonder if this issue caused by preprocess, but still show my python code: model=Sequential() model.add(Conv2D(32,kernel_size=(3,3),activation='relu',input_shape=(187,256,3),padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(BatchNormalization()) model.add(Conv2D(64, (3, 3), activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(BatchNormalization()) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.25)) model.add(BatchNormalization()) model.add(Dense(len(label[1]), activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) This is a simple classification. I just do as same as most instruction. Can not find others fa…
has comment: http://stackoverflow.com/comment/86801281

http://stackoverflow.com/comment/86724743
score: 0
type: AnswerComment
has text: Cheers that fixed the problem, but I have come across another. Any ideas as to what this is? https://pastebin.com/s8rrQRzC
comment on: http://stackoverflow.com/a/49854836
type: Comment

http://stackoverflow.com/comment/86541734
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49762947
has text: @MatheusMohr from my understanding OrderedDict is for dictionaries not for list

http://stackoverflow.com/comment/86693262
has text: Also check if `data-amount` is set correctly on the rendered HTML
score: 0
comment on: http://stackoverflow.com/q/49839106
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49876334
has body: A basic approach for the sentiment analysis, involves making a vocabulary out of training corpus and use it for making feature vectors for your data. A vocabulary as large as few hundred thousand words is quite common and nothing to worry about. The main challenge in this approach is actually opposite of what you are thinking. You should find ways of increasing the size of your vocabulary rather than decreasing it. You can try to enhance the vocabulary by using other sentiment analysis lexicons like SentiWordNet too. As far as implementation of your approach is concerned you can build a scikit pipeline envolving CountVectorize to build vocabulary and feature vector. One advantage of using CountVectorize() for building vocabulary is that it uses a sparse matrix for building the vector which handles your concern of large size. Then using TfIdf Vectorizer for calculating term frequencies and inverse term frequencies, and then finally a model for training. Consider adding some more features to your vector apart from pure bag of words. Be sure to perform a GridSearch on your model and preprocessing stages to fine-tune the parameters for best accuracy. I recently did a similar project for sentiment analysis of stocktwits data. I used a Naive Bayes classifier and got an accuracy of 72%. Naive Bayes proved to be better than even some deep learning models like RNN/DNN classifiers. The model selection, though independent of your question, is an integral part of building your project so keep tweaking it till you get good results. Check out my project if you want some insights on my implementation. Be mindful of following points while doing your project: Some researchers believe that stop words actually add meaning to sentiment so I would recommend not removing them during the preprocessing phase. See this paper Always use domain knowledge while doing sentiment analysis. A negative sentiment in one domain like "predictable movie" can be positive in other like "predictable share…
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49871737
has comment: http://stackoverflow.com/comment/86799278
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49871737
has comment: http://stackoverflow.com/comment/86796337

http://stackoverflow.com/q/49774174
tagged with: for-loop
type: UnansweredQuestion
has title: Iterate over list by index
has comment: http://stackoverflow.com/comment/86563064
tagged with: python
tagged with: indexing
has answer: http://stackoverflow.com/a/49774307
score: 0
answer count: 1
tagged with: loops
type: Question
has body: For an experiment I want to create multiple rectangles, one of which is a target rectangle. Therefore I have created a list with x, y coordinates xy_list = xy_circle(8, 200) random.shuffle(xy_list) And the code for the rarget rectangle, with x, y coordinates xy_list[0] target_rectangle = visual.Rect(win=mywin4, width=45, height=90, pos(xy_list[0]), lineColor='white', fillColor='blue', ori=orientations_list[1]) target_rectangle.draw() And to save me some time and space I want to create a for loop for the distractor rectangles, using the indexes 1-7 of the xy_list. But I'm new to Python so I am not sure how to do this. Could anyone maybe give me a hint? It would be greatly appreciated. for x, y in xy_list: distractor_rectangle = visual.Rect(win=mywin4, width=45, height=90, pos=(x, y), fillColor='white') distractor_rectangle.draw()

http://stackoverflow.com/comment/86715855
comment on: http://stackoverflow.com/q/49850625
has text: Also, have you explored dictionaries? This data looks like it wants to be in a dictionary.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86697090
type: QuestionComment
has text: You have [compiled it](http://cython.readthedocs.io/en/latest/src/quickstart/build.html), right?
score: 0
comment on: http://stackoverflow.com/q/49837155
type: Comment

http://stackoverflow.com/q/49881000
score: 0
has body: I have a HTML document that uses CSS files and a around a dozen PNG files generated out of matplotlib. To convert this HTML document into a PDF, I installed wkhtmltopdf, on a AWS EC2 Linux instance, in a manner described here. On the command line, this works wkhtmltopdf http://www.google.com output.pdf However, the following Python snippet does not work. reportCss = pathlib.Path(os.path.join(cssDir, 'report.css')) w3Css = pathlib.Path(os.path.join(cssDir, 'w3.css')) # options = { 'page-size': 'A4', 'dpi': 720, 'margin-bottom': 5 } css = [str(reportCss), str(w3Css)] pdfkit.from_file(htmlFilePath, pdfFilePath, options=options, css=css) I get this error: QPainter::begin(): Returned false Traceback (most recent call last): File "dailyemail.py", line 55, in &lt;module&gt; main() File "dailyemail.py", line 44, in main pdfFileName = pdfgen.buildPdfDoc() File "/home/ubuntu/demo/py/pdfgen.py", line 58, in buildPdfDoc pdfkit.from_file(htmlFilePath, pdfFilePath, options=options, css=css) File "/home/ubuntu/.local/lib/python2.7/site-packages/pdfkit/api.py", line 49, in from_file return r.to_pdf(output_path) File "/home/ubuntu/.local/lib/python2.7/site-packages/pdfkit/pdfkit.py", line 181, in to_pdf '%s ' %(' '.join(args)),e) TypeError: not enough arguments for format string Can you please advise what am I missing?
tagged with: pdfkit
tagged with: http://stackoverflow.com/tag/html
answer count: 1
accepted answer: http://stackoverflow.com/a/49889962
has title: Unable to generate PDF with wkhtmltopdf on a headless server
has answer: http://stackoverflow.com/a/49889962
type: Question
tagged with: python
tagged with: wkhtmltopdf
type: AnsweredQuestion

http://stackoverflow.com/q/49832708
has comment: http://stackoverflow.com/comment/86681863
has answer: http://stackoverflow.com/a/49881148
has comment: http://stackoverflow.com/comment/86681409
downvote count: 0
tagged with: pandas
upvote count: 1
type: UnansweredQuestion
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86681245
has comment: http://stackoverflow.com/comment/86687790
favorite count: 0
has title: plot legend in multi_index figure plot
type: Question
has comment: http://stackoverflow.com/comment/86681727
has comment: http://stackoverflow.com/comment/86698923
linked to: http://stackoverflow.com/q/31419388
has comment: http://stackoverflow.com/comment/86757496
has body: I am working to plot a mulit_index data for below table, which each line in the figure is related to data in columns{10,11,12,21,26,27} my data as "temp" after I am plotting a multi_index figure : multi_index figure plot I want to add the legend to my plot as well but as "temp" is multi_index pandas.DataFrame, I could access to values {10,11,12,21,26,27}, which will change in each query. below is my code, please help me to what should I put in legend ? p=figure(x_axis_type="datetime") table=pivot_table(data,index=['SDATE','SUBRACK_NO'],columns=['SLOT_NO'],values='ID_73393960',aggfunc={'mean'}) temp=table.query('SUBRACK_NO=="2"') temp=temp.dropna(axis=1,how='all') # to remove all nan values from data temp.reset_index(level=1, drop=True, inplace=True) # to drop index Subrack_no as it make problem for plotting numlines=len(temp.columns) mypalette=Spectral11[0:numlines] p.multi_line(xs=[temp.index.values]*numlines, ys=[temp[name].values for name in temp], line_color=mypalette, line_width=2,legend="**temp.columns.levels[1]**") show(p) #show(gridplot(p, p_filtered)) My "temp" data is as follw : mean SLOT_NO 10 11 12 21 26 27 SDATE 2018-04-12 01:00:00 30.178571 30.214286 29.107143 28.571429 28.714286 29.250000 2018-04-12 02:00:00 23.500000 24.250000 22.928571 25.214286 23.642857 22.785714 2018-04-12 03:00:00 18.642857 19.107143 18.678571 17.535714 17.857143 17.785714 2018-04-12 04:00:00 13.071429 13.178571 14.500000 13.214286 14.000000 14.142857 2018-04-12 05:00:00 12.321429 11.928571 13.464286 12.535714 12.785714 13.678571
tagged with: pivot-table
tagged with: python
has comment: http://stackoverflow.com/comment/86694451

http://stackoverflow.com/comment/86695949
comment on: http://stackoverflow.com/a/49839406
type: AnswerComment
has text: @Abhishek: Yes, it’s because it’s immutable.
score: 0
type: Comment

http://stackoverflow.com/q/49823714
type: Question
has title: how to add four lists into one dictionary
has answer: http://stackoverflow.com/a/49824854
tagged with: for-loop
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86663258
upvote count: 1
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/13704860
has answer: http://stackoverflow.com/a/49823811
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/66094539
tagged with: list
has answer: http://stackoverflow.com/a/49823762
has body: In Python, I am having 4 lists one and want one of them to become my dictionary key and the rest become my key value, but the list length is different Employee_ManagerDic = {} EmployeeID_List = [111,222,333,444,555] EmployeeFirstName_List = ['a','b','c','d','e'] managerID_List = [888,777,666] managerFirstName_List = ['f','g','h'] and the output I want is in this format: Employee_ManagerDic = {EmployeeID_List:[EmployeeFirstName_List,managerID_List, managerFirstName_List]} and something like this Employee_managerDic = { 111:['a',888,'f'], 222:['b',777,'g'], 333:['c',666,'h'], 444:['d',null,null], 555:['e',null,null]} I know I may need to use for loop for this but I don't know how to structure the logic of the loop. Thank you
has answer: http://stackoverflow.com/a/49823757
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/86565286
has text: @aleroot inserted this code in a spider which is stored in /spiders directory. Also m running using command line . Scrapy crawl spidername
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49766710

http://stackoverflow.com/comment/124671940
comment on: http://stackoverflow.com/a/49761410
score: 0
type: Comment
type: AnswerComment
has text: Hi there, I'm in a similar situation right now. I've installed mod_wsgi using `pip install mod_wsgi` in my virtualenv, there by ensuring that both use the same python version. yet my requests are getting timed out and I get an error exactly like you were getting.

http://stackoverflow.com/a/49788742
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49788464
type: AcceptedAnswer
downvote count: 1
has body: You can use collections.Counter instead to calculate union and intersection &gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; c = Counter(setA + setB) &gt;&gt;&gt; [a[0] for a in c.items() if a[1] &gt; 1] #Intersection &gt;&gt;&gt; [1,5,9] &gt;&gt;&gt; list(c.keys()) #Union &gt;&gt;&gt; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Counter object hold the data in format: &gt;&gt;&gt; c &gt;&gt;&gt; Counter({1: 2, 5: 2, 9: 2, 0: 1, 2: 1, 3: 1, 4: 1, 6: 1, 7: 1, 8: 1}) The key is the elements in the list and the value is the occurrence of the element in the list.
answers question: http://stackoverflow.com/q/49788464
score: 0
type: Answer

http://stackoverflow.com/q/49901928
favorite count: 0
tagged with: selection
has body: I'm writing a Python program that is basically the Snipping Tool. I'd like to be able to run my program, select the area for my screenshot using my mouse to click and drag, and then have the program save this image. I was trying it out with the code found here: http://pyscreenshot.readthedocs.io/en/latest/ #-- include('examples/showgrabfullscreen.py') --# import pyscreenshot as ImageGrab if __name__ == '__main__': # grab fullscreen im = ImageGrab.grab() # save image file im.save('screenshot.png') # show image in a window im.show() #-# (under "grab and show part of the screen"), but this doesnt let the user click and drag. Does anyone know how I could do this? I found some examples online but they're all hundreds of lines long and I don't think this simple program should be that long (but I could be wrong). Thanks!
has answer: http://stackoverflow.com/a/61603758
has comment: http://stackoverflow.com/comment/86819332
type: Question
tagged with: screenshot
answer count: 2
has answer: http://stackoverflow.com/a/79166810
score: 5
linked to: http://stackoverflow.com/q/204017
type: UnansweredQuestion
downvote count: 1
upvote count: 6
has comment: http://stackoverflow.com/comment/86819297
has title: How to take a screenshot with Python using a click and drag method like Snipping Tool?
has comment: http://stackoverflow.com/comment/86820177
tagged with: python

http://stackoverflow.com/comment/86542127
type: QuestionComment
comment on: http://stackoverflow.com/q/49763225
type: Comment
score: 0
has text: We may need a canonical duplicate for these kinds of questions... I swear this gets asked about 3 times a week...

http://stackoverflow.com/a/49882175
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86780714
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49882131
answers question: http://stackoverflow.com/q/49882131
has body: This: url(r'^create/$', views.goal_create, name='create'), Should be: url(r'^create/$', views.goal_create, name='goal_create'),
type: Answer

http://stackoverflow.com/a/49816225
answers question: http://stackoverflow.com/q/49812478
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86838130
has comment: http://stackoverflow.com/comment/86838952
has comment: http://stackoverflow.com/comment/86804082
has comment: http://stackoverflow.com/comment/86802901
has comment: http://stackoverflow.com/comment/86801768
score: 1
has comment: http://stackoverflow.com/comment/86802624
has comment: http://stackoverflow.com/comment/86807423
type: Answer
accepted answer of: http://stackoverflow.com/q/49812478
has body: There's no way to tell which one is the input or output tensor from a graph. You should use the SavedModel functions. Part of it is to generate a signature of the model that says exactly which tensor is the input and which one is the output. You can take the same model and export it with different signatures. For example one would take a protocol buffer and give you a probability back, and another would take a string and give you a space embedding.
has comment: http://stackoverflow.com/comment/86815445
has comment: http://stackoverflow.com/comment/86710985
has comment: http://stackoverflow.com/comment/86651832

http://stackoverflow.com/a/49843861
answers question: http://stackoverflow.com/q/49842165
type: Answer
has body: You can add additional variables. For example: def swap(a, i, j): a[i], a[j] = a[j], a[i] def permute(a, i, n): if (a == b): global flag flag = True print('String matched') elif not flag: if i == n: print(a) for j in range(i, n + 1): swap(a, i, j) permute(a, i + 1, n) swap(a, i, j) def main(): string = "ABCD" n = len(string) a = list(string) global flag global b flag = False b = list("ABDC") permute(a, 0, n - 1) if __name__ == '__main__': main()
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49842165
score: 0
upvote count: 1

http://stackoverflow.com/comment/86807281
has text: @PanosAngelopoulosm I tried that but still same issue
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49894471

http://stackoverflow.com/a/49833588
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86683463
has body: You can't return a file to an ajax request and expect it to be downloaded. What you need is to separate into a few steps: Your ajax request triggers the file creation process Django puts that file somewhere where it can be downloaded and returns the URL to the file as ajax response Your js response handler can now do two things: Generate a button in the HTML for the user to click and download the file (using the URL from the response) Create the button and auto-click it (call .click() on it) and then delete it again. A bit like in this example
accepted answer of: http://stackoverflow.com/q/49832606
type: Answer
has comment: http://stackoverflow.com/comment/86683365
answers question: http://stackoverflow.com/q/49832606

http://stackoverflow.com/q/49840355
tagged with: python
tagged with: memcached
has answer: http://stackoverflow.com/a/57690228
type: AnsweredQuestion
has title: Does django hits the database when you request for an object's attribute from a cached query?
has answer: http://stackoverflow.com/a/49841314
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/57690228
tagged with: caching
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49841314
has body: I'm having trouble to understand how to properly use the Caches Framework. lets say I have this code: class Book(models.Model): title = models.CharField() author = models.ForeignKey(User) @classmethod: def get_all_books(cls): query = cache.get_or_set( 'all_books', cls.objects.all() ) return query now I know that every time I run Book.get_all_books() it returns the already cached result. but what if I run this code in shell: &gt;&gt;&gt; list = Book.get_all_books() &gt;&gt;&gt; list[0].title # does this line hits the database? &gt;&gt;&gt; list[0].author # does this line hits the database? &gt;&gt;&gt; list.filter(title='for dummies') # does this line hits the database? what have I missed to study? can you please guid me? thank you in advance.
answer count: 2
downvote count: 0
tagged with: database
tagged with: django

http://stackoverflow.com/a/77993689
upvote count: 2
answers question: http://stackoverflow.com/q/49883236
downvote count: 0
has body: In addition to other answers - simple and fast checksum: checksum = pandas.util.hash_pandas_object(df).sum()
score: 2
type: Answer

http://stackoverflow.com/q/49798269
tagged with: scikit-learn
tagged with: python
has title: Scikit's Average Precision Score bad input shape
accepted answer: http://stackoverflow.com/a/49798815
has body: I'm trying to plot a precision/recall score curve. This is the code I have: lbl_enc = preprocessing.LabelEncoder() labels = lbl_enc.fit_transform(test_tags) y_score = clf.predict_proba(test_set) average_precision = average_precision_score(labels, y_score) print('Average precision-recall score: {0:0.2f}'.format(average_precision)) precision, recall, _ = precision_recall_curve(labels, y_score) plt.step(recall, precision, color='b', alpha=0.2, where='post') plt.fill_between(recall, precision, step='post', alpha=0.2, color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('2-class Precision-Recall curve: Average P-R = {0:0.2f}'.format( average_precision)) At the point I'm calculating the average_precision_score, I get this "ValueError: bad input shape (119, 2)" that is caused by the "y_score" variable. y_score is in this format: array([[0.45953712, 0.54046288], [0.78289908, 0.21710092], [0.13488789, 0.86511211], [0.56162583, 0.43837417], (...) [0.4595595 , 0.5404405 ]]) while labels is in this: array([0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) How can I make this work for calculating avg precision score? Thanks in advance.
type: AnsweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49798815
type: Question

http://stackoverflow.com/q/49819029
has body: I want to use Python to move .xlsx files if they are in a certain folder. Is there a generic rule for this? What I am looking for is basically code for this: if there is a file that is an excel document in /user/documents/folder: move it to trash. I'm happy with the shutil.move bit but what can I use to classify .xlsx files as a group?
tagged with: excel
has title: Python - How to detect a file of given type in a folder
score: 0
has comment: http://stackoverflow.com/comment/86652902
tagged with: operating-system
answer count: 1
tagged with: directory
type: Question
has comment: http://stackoverflow.com/comment/86652849
has comment: http://stackoverflow.com/comment/86652948
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49854564

http://stackoverflow.com/comment/133354157
has text: @PavelKarateev I don't see "Python Scientific" under "Tools". Searching settings for `plots` or `scientific` doesn't show anything either.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49844189
type: QuestionComment

http://stackoverflow.com/comment/86670927
type: Comment
type: QuestionComment
has text: Looks like you are looking for someone to do your homework for you. Please show what you've actually tried...
score: 0
comment on: http://stackoverflow.com/q/49827727

http://stackoverflow.com/a/50118140
answers question: http://stackoverflow.com/q/49863520
type: Answer
has body: For anyone else: from nltk.sentiment.vader import SentimentIntensityAnalyzer new_words = { 'foo': 2.0, 'bar': -3.4, } SIA = SentimentIntensityAnalyzer() SIA.lexicon.update(new_words)
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/49830344
downvote count: 2
has comment: http://stackoverflow.com/comment/87058152
has title: I don't know why I cannot import the .ods file
favorite count: 0
type: Question
tagged with: python-3.x
has body: I cannot use Python package "xlrd". I wanted to deal with an excel data and prepared ods file and save in the directory where there is this python's file. I was trying to import an ods file, but an error below occurred. Python code import xlrd book = xlrd.open_workbook("lung.ods") ERROR In [21]: runfile('/home/****/Desktop/working/survival10.py', wdir='/home/****/Desktop/working') Traceback (most recent call last): File "&lt;ipython-input-21-7a27e6491452&gt;", line 1, in &lt;module&gt; runfile('/home/****/Desktop/working/survival10.py', wdir='/home/****/Desktop/working') File "/home/****/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/home/****/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/home/****/Desktop/working/survival10.py", line 16, in &lt;module&gt; book = xlrd.open_workbook("lung.xlsx") File "/home/****/anaconda3/lib/python3.6/site-packages/xlrd/__init__.py", line 150, in open_workbook raise XLRDError('Openoffice.org ODS file; not supported') # in the xlsx's case XLRDError: Openoffice.org ODS file; not supported Then I changed the file from ods type to xlsx type and coded this. book = xlrd.open_workbook("lung.xlsx") but the same error occurred. The file's pass is "/home/****/Desktop/working" I'm using Anaconda3, Python 3.6 and the module "xlrd" has already been installed. Please tell me what the problem is with this.
has answer: http://stackoverflow.com/a/63186230
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/xlsx
has comment: http://stackoverflow.com/comment/86777713
tagged with: python
has answer: http://stackoverflow.com/a/49860442
tagged with: ods
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/86675896
tagged with: xlrd
upvote count: 2

http://stackoverflow.com/q/49785509
accepted answer: http://stackoverflow.com/a/49785627
has comment: http://stackoverflow.com/comment/86586537
has comment: http://stackoverflow.com/comment/86586549
has answer: http://stackoverflow.com/a/49785627
tagged with: python
has comment: http://stackoverflow.com/comment/86586573
has comment: http://stackoverflow.com/comment/86586569
has comment: http://stackoverflow.com/comment/86586529
has title: How to get the most matched value from a python dictionary
tagged with: string-matching
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86600694
upvote count: 2
score: 1
answer count: 1
has body: I have a dictionary of job category keywords looks like this: {'01': ['advertising, representatives, financial, miscellaneous, other, sales'], '02': ['musicians, workers, officials, entertainers, actors, singers, competitors, dancers'], '03': ['movers, station, gas, of, stock, pumping, workers, hoist, mining, freight, truck'], '04': ['child, support, children, disable, supplemental, security, income']} I also have a list of job titles: child support art director driver assistant specialist I am wondering if there is a way to find the most matched job category for each job title. So what I want is a new column of a key from the dictionary for each in the job title list. job title category child support 04 art director 23 truck driver 03 assistant specialist 17 The key is representing a broad job category. The value in this dictionary is split unique words of more detailed subcategory names. A problem is the words in job title may not exist in any category names. And the words may exist in many categories.
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49891074
has comment: http://stackoverflow.com/comment/86797848
linked to: http://stackoverflow.com/q/1663807
score: 0
has body: I have three files and i want to cross join (or combine) each line of one file with other. EX) File1 contains a,b,c d,e,f File2 : 1,2,3 4,5,6 so i want output like : a,b,c,1,2,3 a,b,c,4,5,6 d,e,f,1,2,3 d,e,f,4,5,6 I could do this in python with loops one inside other , but if we have more than 4 files there would be multiple loops . Is there any other way in python to resolve this in efficient way?
answer count: 0
linked to: http://stackoverflow.com/q/11174745
tagged with: scipy
type: Question
tagged with: numpy
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86797885
type: UnansweredQuestion
tagged with: python
has title: Cross joining(combine each line of one file with other file) files in python
duplicate of: http://stackoverflow.com/q/11174745

http://stackoverflow.com/a/71860792
upvote count: 1
answers question: http://stackoverflow.com/q/49879465
type: Answer
has body: I can't tell you what you are doing incorrectly. But, the python program sagemath has an implementation of miller's algorithm, and all the pairings, weil, tate, and ate. If you install it, you can find the source code for miller and weil in the file ell_point.py. The algorithm is more general, and so more complex, than your implementation, but you should be able to translate to get what you want. Or, you can just import sagemath and use its implementations.
score: 1
downvote count: 0

http://stackoverflow.com/comment/86670578
score: 4
has text: I downvoted because this question was easily answered by simply reading the [documentation](https://docs.python.org/3/library/gc.html#gc.collect)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49827518

http://stackoverflow.com/q/49866788
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86749902
accepted answer: http://stackoverflow.com/a/49867152
has comment: http://stackoverflow.com/comment/86774365
has comment: http://stackoverflow.com/comment/86775551
type: Question
has comment: http://stackoverflow.com/comment/86775919
upvote count: 0
tagged with: tkinter
has title: Strange behavior of frames in tkinter
downvote count: 2
has body: I have a project I am working on and it requires me to update a frame with new page information depending on what button is clicked. I have 2 frames in the main page. One frame holds the buttons and the other frame is to be updated on button click. However when I click on a button it seams to remove both buttons and set up the new page on the first frame. I don't see how this is possible as I have check each frame and they should be separate. When I run the test1.py page I get this window as expected: However this is what I get when I press one of the buttons: I should expect to see the 2 buttons still there and the label now to the right of the buttons. I really cant see how this could be happening. Here are my example pages. test1.py contains: import tkinter as tk import test2 import test3 class TestApp(tk.Frame): def __init__(self, master, *args, **kwargs): tk.Frame.__init__(self, master, *args, **kwargs) self.button_frame = tk.Frame(self) self.button_frame.grid(row=0, column=0) self.working_frame = tk.Frame(self) self.working_frame.grid(row=0, column=1) tk.Button(self.button_frame, text="Test 2", command=lambda: self.update_main_frame("test2")).grid(row=0, column=0) tk.Button(self.button_frame, text="Test 3", command=lambda: self.update_main_frame("test3")).grid(row=1, column=0) def update_main_frame(self, window_name): if window_name == "test2": self.reset_working_frame() x = test2.TestFrame2(self.working_frame) x.grid(row=0, column=0, sticky="nsew") if window_name == "test3": self.reset_working_frame() x = test3.TestFrame3(self.working_frame) x.grid(row=0, column=0, sticky="nsew") def reset_working_frame(self): self.working_frame.destroy() self.working_frame = tk.Frame(self) self.working_frame.grid(row=0, column=1) if __name__ == "__main__": root = tk.Tk() TestApp(root).grid(row=0, column=0, sticky="nsew") tk.mainloop() test2.py contains: import tkinter as tk class TestFrame2(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self) self.parent = parent s…
score: -2
has answer: http://stackoverflow.com/a/49867152
has comment: http://stackoverflow.com/comment/86775709
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86749245
has comment: http://stackoverflow.com/comment/86749149
has comment: http://stackoverflow.com/comment/86775625
tagged with: tkinter-layout

http://stackoverflow.com/comment/86704066
has text: edited my question, please check
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49843914
type: QuestionComment

http://stackoverflow.com/q/49916467
tagged with: scikit-learn
tagged with: class
has comment: http://stackoverflow.com/comment/86851003
has title: In Sklearn, how can I pass an arbitrary number of models to a class?
score: 0
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/86849651
has body: If I write something like class test_class(BaseEstimator, ClassifierMixin): def __init__(self, model = LogisticRegression()): self.model = model # ... # Then I can do this test = test_class() test.get_params() And I get the parameters of LogisticRegression() as part of the parameters of my class, in the format "model__". This would let me use the class with something like GridSearchCV and easily access the arguments of LogisticRegression. Is there any way of doing this for an arbitrary number of models? I have tried a few things, including using a **kwargs argument like this: class test_class(BaseEstimator, ClassifierMixin): def __init__(self, model = LogisticRegression(), **kwargs): self.model = model for key in kwargs: setattr(self, key, kwargs[key]) # ... # And then if I do test = test_class(model_2 = RandomForestClassifier()) test.get_params() I just get the same as before (although model_2 is added as an attribute). I feel like this should be pretty straightforward but I'm not getting anywhere - maybe what I am trying to do doesn't even make sense. The goal of my class would be some sort of model ensembler that I can use with GridSearchCV. Does anyone have any ideas? edit: An example of the parameter grid I would like to give to GridSearchCV is, considering the second example: { model__C : [1, 10], model_2__n_estimators : [10, 100] } The first line works as expected (considering how Pipelines work with GridSearchCV), but the second does not (as the parameters are not found in get_params()). My fit, predict and score methods are all working fine, it is just an issue of passing the arguments to the additional models I want to pass to my class.
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86851564
has comment: http://stackoverflow.com/comment/86852843
has comment: http://stackoverflow.com/comment/86852351
tagged with: machine-learning

http://stackoverflow.com/comment/86624619
has text: @Bryan Oakley player is a dictionary object and weapon is another. it refers to the dictionary object (weapon) that is currently "equipped".
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49804510
score: 0

http://stackoverflow.com/comment/86783304
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49883623
type: Comment
has text: you can use a range to enumerate all the value between 2 and 20: `for divisor in range(2,20+1):`

http://stackoverflow.com/comment/86625041
comment on: http://stackoverflow.com/a/49784987
type: AnswerComment
score: 0
type: Comment
has text: I have a couple of questions about your answer - I normally code in C or C++ and am new to Python. You have `arr = np.random.randint(0,255...` but as far as I can tell that will never generate 255, only up to 254. Am I mistaken, or is there some reason for that please?

http://stackoverflow.com/comment/86586727
comment on: http://stackoverflow.com/q/49778057
has text: Also you really do want to take a look at the per-function compiler directive decorators I mentioned. You will almost certainly see speedups if you turn off autowrap and bounds checking.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49896064
has answer: http://stackoverflow.com/a/51552443
score: 0
has body: I have installed tensorflow for the GPU from a whl file I found. It is version 1.5.0. I also installed keras and matplotlib. I think numpy was installed from one of the modules. Almost nothing works when I try to run python from within spyder or jupyter, but everything works running python from console. When importing tensorflow spyder doesn't know what is this module. runfile('D:/LearnANN/untitled2.py', wdir='D:/LearnANN') Traceback (most recent call last): File "&lt;ipython-input-1-ecb61dbb011d&gt;", line 1, in &lt;module&gt; runfile('D:/LearnANN/untitled2.py', wdir='D:/LearnANN') File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "D:/LearnANN/untitled2.py", line 8, in &lt;module&gt; import tensorflow ModuleNotFoundError: No module named 'tensorflow' When importing numpy or keras or matplotlib runfile('D:/LearnANN/untitled2.py', wdir='D:/LearnANN') Traceback (most recent call last): File "&lt;ipython-input-2-ecb61dbb011d&gt;", line 1, in &lt;module&gt; runfile('D:/LearnANN/untitled2.py', wdir='D:/LearnANN') File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "D:/LearnANN/untitled2.py", line 8, in &lt;module&gt; import numpy File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\__init__.py", line 142, in &lt;module&gt; from . import add_newdocs File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\__init__.py", line 8, in &lt;module&gt;…
answer count: 2
has comment: http://stackoverflow.com/comment/86808674
tagged with: spyder
has answer: http://stackoverflow.com/a/49898241
tagged with: jupyter
has title: Keras, numpy, tensorflow don't work from spyder, juptyer, works fine from console with python
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86808214
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86810589
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86811647
linked to: http://stackoverflow.com/q/10729116
tagged with: python
has comment: http://stackoverflow.com/comment/86811375

http://stackoverflow.com/q/49770465
accepted answer: http://stackoverflow.com/a/49830106
tagged with: gpu
has answer: http://stackoverflow.com/a/49830106
tagged with: python
has body: I have installed TensorFlow 1.7 on an Ubuntu 16.04 with Cuda 9.0 and CuDNN 7.0.5 and vanilla Python 2.7 and although they samples for both CUDA and CuDNN run fine, and TensorFlow sees the GPU (so some TensorFlow examples run), those that use CuDNN (like most CNN examples) do not. They fail with these Informational messages: 2018-04-10 16:14:17.013026: I tensorflow/stream_executor/plugin_registry.cc:243] Selecting default DNN plugin, cuDNN 25428 2018-04-10 16:14:17.013100: E tensorflow/stream_executor/cuda/cuda_dnn.cc:403] could not create cudnn handle: CUDNN_STATUS_NOT_INITIALIZED 25429 2018-04-10 16:14:17.013119: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:369] driver version file contents: """NVRM version: NVIDIA UNIX x86_64 Kernel Module 384.130 Wed Mar 21 03:37:26 PDT 2018 25430 GCC version: gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.9) 25431 """ 25432 2018-04-10 16:14:17.013131: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:112] version string "384.130" made value 384.130.0 25433 2018-04-10 16:14:17.013135: E tensorflow/stream_executor/cuda/cuda_dnn.cc:411] possibly insufficient driver version: 384.130.0 25434 2018-04-10 16:14:17.013139: E tensorflow/stream_executor/cuda/cuda_dnn.cc:370] could not destroy cudnn handle: CUDNN_STATUS_BAD_PARAM 25435 2018-04-10 16:14:17.013143: F tensorflow/core/kernels/conv_ops.cc:712] Check failed: stream-&gt;parent()-&gt;GetConvolveAlgorithms( conv_parameters.ShouldIncludeWinogradNonfusedAlgo&lt;T&gt;(), &amp;algorithms) Turning on a flood of VLOG messages (see my link below for how to do this) did not produce any additional relevant messages. The key message here might be "Selecting default DNN plugin, cuDNN", because looking at the code I might think that it can't load the cuDNN library modules, but for all I know it is actually normal (so not a warning) and the problem could be something else. For example the "CUDNN_STATUS_NOT_INITIALIZED" message seems to have been caused in an earlier version…
upvote count: 6
type: Question
answer count: 1
downvote count: 0
score: 6
has title: CUDNN_STATUS_NOT_INITIALIZED when trying to run TensorFlow
tagged with: cudnn
linked to: http://stackoverflow.com/q/44853059
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/86645980
score: 1
type: Comment
type: AnswerComment
has text: It is yesterday dupe :(
comment on: http://stackoverflow.com/a/49815884

http://stackoverflow.com/a/49861824
score: 2
upvote count: 2
downvote count: 0
has body: You need to move return res back one level, because at the moment you're returning on the first run through the loop, and thus getting an empty list. i.e. you should have: def intersect(s1,s2): res=[] for x in s1: if x in s2: res.append(x) return res # note this is unindented
answers question: http://stackoverflow.com/q/49861772
type: Answer

http://stackoverflow.com/comment/133292692
score: 0
has text: @Kos How would you do this using a [`CheckConstraint`](https://docs.djangoproject.com/en/4.1/ref/models/constraints/#checkconstraint)? I'd like to push more validation into the database itself, but using a `ManyToMany` relationship as in @etene's solution below is not an option. The problem I'm finding with `CheckConstraint`'s is they seem to be limited to the data in the row being inserted.
comment on: http://stackoverflow.com/q/49816979
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49783960
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/86583451
has comment: http://stackoverflow.com/comment/86583461
has body: It gets evaluated depending if meets the condition. For example: condition = True print(2 if condition else 1/0) #Output is 2 print((1/0, 2)[condition]) #ZeroDivisionError is raised No matter if 1/0 raise an error, is never evaluated as the condition was True on the evaluation. Sames happen in the other way: condition = False print(1/0 if condition else 2) #Output is 2
type: Answer
answers question: http://stackoverflow.com/q/49783902
score: 4

http://stackoverflow.com/q/49827806
has title: How do I add the numbers in a few list with same index?
tagged with: indexing
score: 0
tagged with: list
answer count: 2
has body: this is what i have for the lists broken from a 2d list: [0, 0, 0, 0, 0, 3, 3, 3] [0, 0, 0, 0, 2, 0, 0, 0, 2] [0, 0, 0, 1, 0, 0, 0, 0, 0, 1] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0, 0, -2] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3, -3, -3] and because they are broken from the same list, I don't know how to add them into a new list. Do I append them into a new list and zip them? But how do I append them(because they are from the same list, if I use index[3], it will only come out with the number in each line(for example, 0 for index[3],line1)) This is what I expect: [ 0, 0, 0, 1, 2, 3, 3, 3, 2, 1, 0, -1, -2, -3, -3, -3, -2, -1, 0, 0, 0 ] that is , all the numbers with the same index got add together. Please give me some hint. Thank you!
has comment: http://stackoverflow.com/comment/86671095
has answer: http://stackoverflow.com/a/49827995
type: Question
tagged with: http://stackoverflow.com/tag/zip
type: UnansweredQuestion
tagged with: arrays
tagged with: python
has answer: http://stackoverflow.com/a/49828078

http://stackoverflow.com/comment/130801967
has text: For those having the `requires PEP 517 and cannot be installed directly` error, this will help too
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49908862
type: Comment

http://stackoverflow.com/q/49782230
upvote count: 1
tagged with: pip
tagged with: amazon-web-services
has title: Elastic Beanstlak CLI Installation Error
favorite count: 0
accepted answer: http://stackoverflow.com/a/49786475
type: Question
has answer: http://stackoverflow.com/a/49786475
tagged with: python
has body: I downloaded the EBCLI with sudo pip install awsebcli --upgrade --user When running eb --version I get the following error. Traceback (most recent call last): File "/home/andrew/.local/bin/eb", line 6, in &lt;module&gt; from pkg_resources import load_entry_point File "/usr/local/google-cloud-sdk/platform/google_appengine/lib/setuptools-0.6c11/pkg_resources.py", line 2603, in &lt;module&gt; working_set.require(__requires__) File "/usr/local/google-cloud-sdk/platform/google_appengine/lib/setuptools-0.6c11/pkg_resources.py", line 666, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/local/google-cloud-sdk/platform/google_appengine/lib/setuptools-0.6c11/pkg_resources.py", line 565, in resolve raise DistributionNotFound(req) # XXX put more info here pkg_resources.DistributionNotFound: awsebcli==3.12.4 Any ideas? Edit: Here is my pip --version: pip 9.0.3 from /usr/local/lib/python2.7/dist-packages (python 2.7)
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49829307
tagged with: tesseract
type: AnsweredQuestion
score: 0
tagged with: python-tesseract
tagged with: anaconda
has body: Problem My tesseract (tesserocr) is not found by the emacs python interpreter, but I am able to use tesseract on the terminal as well as in my Spyder installation. Emacs python interpreter is able to import pytesseract, but not find tesserocr. I get the following error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/eghx/agent18/project-gym/tests/thresholding.py", line 34, in image_to_string2 print(image_to_string(img_open)) File "/home/eghx/anaconda3/lib/python3.6/site-packages/pytesseract-0.1.7-py3.6.egg/pytesseract/pytesseract.py", line 122, in image_to_string File "/home/eghx/anaconda3/lib/python3.6/site-packages/pytesseract-0.1.7-py3.6.egg/pytesseract/pytesseract.py", line 46, in run_tesseract File "/home/eghx/anaconda3/lib/python3.6/subprocess.py", line 709, in __init__ restore_signals, start_new_session) File "/home/eghx/anaconda3/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'tesseract': 'tesseract' when I run pytesseract.image_to_string(img) However I don't get this error when I open EMACS from a terminal instead of the desktop. It appears that the path variable is inherited differently in the desktop version and terminal version of emacs. ODD! Explanation I have anaconda installation here:/path/to/anaconda3 I have added this line to my init file to run this particular python installation (setq python-shell-interpreter "/path/to/anaconda3/bin/python") I installed both pytesseract and tesserocr using conda install which tesseract gives: /path/to/anaconda3/bin/tesseract $ echo $PATH gives: /path/to/anaconda3/bin:/usr/local/sbin:/usr/lo.... What I did I copied the sys.path from the working Spyder IDE to emacs python interpreter and still didn't work. I looked around and found this but the top answer does not pertain to my case, as my $PATH variable contains the necessary path. Can some…
answer count: 1
has answer: http://stackoverflow.com/a/49866388
type: Question
accepted answer: http://stackoverflow.com/a/49866388
has title: Emacs python not able to find package/module
linked to: http://stackoverflow.com/q/35609773
tagged with: emacs
tagged with: python

http://stackoverflow.com/q/49850861
possible better answer: http://stackoverflow.com/a/49851293
linked to: http://stackoverflow.com/q/3862310
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86716487
has answer: http://stackoverflow.com/a/49851290
has answer: http://stackoverflow.com/a/49851293
tagged with: python
duplicate of: http://stackoverflow.com/q/18296653
type: AnsweredQuestion
score: 0
has title: How to display the built-in exception hierarchy in Python?
answer count: 2
has body: I need to have a view of the the exception hierarchy and get it displayed nicely as shown here. On Terminal, I get those built-in exceptions (among other things) displayed in their alphabetical order instead: &gt;&gt;&gt; import pprint &gt;&gt;&gt; pprint.pprint(dir(__builtins__)) Do you know how to achieve this goal knowing that BaseException is the base class of all the existing exceptions? EDIT: If needed: How to find all the subclasses of a class given its name?
linked to: http://stackoverflow.com/q/18296653
accepted answer: http://stackoverflow.com/a/49851290
upvote count: 1

http://stackoverflow.com/q/49788934
score: 0
answer count: 0
type: Question
tagged with: pyramid
tagged with: pdf.js
type: UnansweredQuestion
has title: How to load a pdf in pdf.js from a database object (blob)?
tagged with: python
has comment: http://stackoverflow.com/comment/86645966
has body: I am using Pyramid framework with Zope Object Database, my pdf files are not stored anywhere physically but are present in my Database in the form of objects, and even after many days of research I am not able to find out how can I display it using pdf.js? Please help.
has comment: http://stackoverflow.com/comment/86602414

http://stackoverflow.com/comment/86713908
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49849494
has text: Can you tell me what you're trying to achieve here? I think I already know, but once you confirm maybe I can help you better.
type: Comment

http://stackoverflow.com/comment/86631332
score: 34
has text: Requires sudo to work: `curl https://bootstrap.pypa.io/get-pip.py | sudo python`
type: Comment
comment on: http://stackoverflow.com/a/49769015
type: AnswerComment

http://stackoverflow.com/comment/87831968
type: Comment
comment on: http://stackoverflow.com/q/49894329
type: QuestionComment
score: 0
has text: @zipa - Added to the question

http://stackoverflow.com/comment/86615968
has text: You can use the zoom feature in the lower right corner of the figure window to zoom in on any of the plots manually. If you are intending to change the x and y axis limits, then that can be done inside of the for loop as you create each of the subplots. If I have answered your question, please feel free to click the green check mark to accept my answer, thanks!
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49783891

http://stackoverflow.com/comment/96747977
comment on: http://stackoverflow.com/a/49899756
score: 0
type: AnswerComment
has text: how did you initializes the scheduler to a singleton?
type: Comment

http://stackoverflow.com/comment/86821418
type: AnswerComment
has text: @jpp I know, the best answer is to do a real loop.
comment on: http://stackoverflow.com/a/49902782
type: Comment
score: 0

microphone
tag name: microphone
tags question: http://stackoverflow.com/q/49867553
type: Tag

http://stackoverflow.com/comment/86763631
score: 0
comment on: http://stackoverflow.com/q/49874001
type: Comment
type: QuestionComment
has text: deck already contains unique values, all you need to do is just split it into 3 piles. Currently you are just shuffling the deck and printing the first 7 cards of the shuffled deck for three times...

decode
tag name: decode
type: Tag
tags question: http://stackoverflow.com/q/49833879

build
tag name: build
type: Tag
tags question: http://stackoverflow.com/q/49850815

http://stackoverflow.com/comment/86821630
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49891708
has text: Yeah!! Finally got it fixed. The problem was when it is loaded into the database. After the hash has been completed the hashed password needs to be decoded prior to loading into the database. So the new password load needs to be: Password.objects.create(pwd = password.decode('utf-8'), user = User.objects.get(id = new_user.id)). Still not sure why exactly but it works.
score: 0

http://stackoverflow.com/comment/86576124
type: Comment
type: QuestionComment
has text: @max9111 I have execution time issues, so need a faster solution
score: 0
comment on: http://stackoverflow.com/q/49765382

http://stackoverflow.com/a/49792225
has comment: http://stackoverflow.com/comment/86600381
downvote count: 0
upvote count: 1
score: 1
has body: Your Pycharm has a hard time determining the path to the installed Python interpreter. Normally it automatically can, but if not, here are the steps: Expand the environment Then you will be asked for the path where Python is installed Navigate to the directory where Python is installed and select the Python executable This section from the Pycharm docs will help you: https://www.jetbrains.com/help/pycharm/configuring-python-interpreter.html
has comment: http://stackoverflow.com/comment/86600150
answers question: http://stackoverflow.com/q/49792127
type: Answer
has comment: http://stackoverflow.com/comment/86599665
has comment: http://stackoverflow.com/comment/86599856

http://stackoverflow.com/comment/90199171
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49876656
score: 0
has text: I had the same problem: https://stackoverflow.com/a/51616840/901444

http://stackoverflow.com/comment/86558920
score: 2
comment on: http://stackoverflow.com/q/49771837
has text: You have an indentation error in your plot function. Also you will need to call the `update_figure()` method afterwards in order to update your graph.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49825551
type: UnansweredQuestion
has title: Data structure: advanced string splitting to return a list
tagged with: python
has body: I'm writing a function called get_coords(item) that takes as input a single string in the expected format of the Location 1 column in a data file. The function should return a list with two entries: the latitude and longitude as floating point values. If the latitude and longitude are missing, it should return numpy.nan (NaN) to indicate a missing value. An example succesfull implementation would be: text = '1533 Bridle Creek Blvd\nVirginia Beach, VA 23464-7907\n(36.787392, -76.15761)' print(get_coords(text)) [36.787392, -76.15761] I feel like I need to use some form of string splitting, however, the longitude and latitude coordinates can be of different lengths which makes me feel like I need to use something like the re module and use something like re.search; how do I extract the coordinates and return them as a list, given different lengths of the coordinates as well as the initial string?
has answer: http://stackoverflow.com/a/49825846
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/49825597
downvote count: 0
score: 1
upvote count: 1
tagged with: string
favorite count: 0
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/49825586

http://stackoverflow.com/comment/86778036
score: 0
has text: I must say, i you just implement the `__setitem__` most of the behavior you except won't work. Look at my edits in the answer above.
type: Comment
comment on: http://stackoverflow.com/a/49866080
type: AnswerComment

http://stackoverflow.com/a/49814270
answers question: http://stackoverflow.com/q/49813577
score: 3
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49813577
downvote count: 0
has body: You can make a model with only MaxPooling2D and do predict (with no fit): model = Sequential() model.add(MaxPooling2D(pool_size=(2, 2), input_shape=input_shape)) model.compile('adadelta') pooled = model.predict(image) The compile doesn't affect at all. Full code Example from @Hitesh comment: from keras.models import Sequential from keras.layers import MaxPooling2D import numpy as np image=np.random.rand(1, 56, 64, 1) input_shape=(56,64,1) model = Sequential() model.add(MaxPooling2D(pool_size=(2, 2), input_shape=input_shape)) model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) pooled = model.predict(image)
type: Answer
has comment: http://stackoverflow.com/comment/86644770
has comment: http://stackoverflow.com/comment/86643973

http://stackoverflow.com/comment/86548305
comment on: http://stackoverflow.com/a/49766405
score: 0
type: Comment
has text: I am using it. How will I do it?
type: AnswerComment

http://stackoverflow.com/comment/86733686
comment on: http://stackoverflow.com/q/49859335
type: Comment
type: QuestionComment
score: 2
has text: Group first then apply value counts. `df.groupby('Product group').Comment.value_counts()`

http://stackoverflow.com/comment/86736553
type: AnswerComment
comment on: http://stackoverflow.com/a/49860627
score: 0
has text: I'm just incorporating the column back in to your dataframe in a single chained assignment. Wen's answer produces the same series, but it still needs to be added to your dataframe.
type: Comment

http://stackoverflow.com/q/49804691
type: Question
has body: I have a tennis dataframe called atp_main with 50 columns and about 160,000 rows. I have a column called winner_age (and a corresponding loser_age column). At first, these ages showed up as long decimal points e.g. 22.321234342..., 25.23345565665..., etc. The dtypes of this column is 'object'. I cleaned the data by adjusting these columns to print the ages similar to ints i.e. 22, 25, 31, etc. I did this by converting the column dtype to a float as there appeared to be issues with converting to an int: atp_data['winner_age'] = pd.to_numeric(atp_data['winner_age'], errors='coerce') This column's dtype is now a float.I then formatted this column to show nothing after the decimal point i.e. 23 rather than 23.123212432... pd.options.display.float_format = '{:,.0f}'.format When I call this column and print its values: atp_main['winner_age] it prints a list of the ages like so 23 22 21 31 18 However, when I apply a function like mean(), it returns a value with a big, long decimal: atp_main['winner_age'].mean() 23.4353423354545 Ideally, I would like the winner_age column to be an int and not a float. I tried to convert like so: atp_main['winner_age'].astype(int) But got this error: ValueError: Cannot convert non-finite values (NA or inf) to integer The dataframe has quite a number of NaN values in the first portion of the dataset, just to be aware of. Many thanks in advance!
has comment: http://stackoverflow.com/comment/86624502
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/21287624
duplicate of: http://stackoverflow.com/q/21287624
has comment: http://stackoverflow.com/comment/86624316
score: 0
has title: Converting column dtypes as 'objects' to 'floats or 'ints
tagged with: pandas
tagged with: dataframe
tagged with: python
tagged with: nan

http://stackoverflow.com/comment/86658467
type: Comment
type: AnswerComment
has text: I need one CSV row per Global ID(sample is 1 row). It must all columns like ID, Price, Order_id, etc. And 2 jobs ID, 2 jobs approx_time and 2 job_type (or more jobs, in some rows there are more jobs than 2)
score: 0
comment on: http://stackoverflow.com/a/49821104

http://stackoverflow.com/a/49830538
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/88266554
answers question: http://stackoverflow.com/q/49820878
has body: thanks i have a solution now and it is a mix of openpyxl + pandas + matplotlib workbook = load_workbook(excel_file,read_only=False) worksheet = workbook['Sheet2'] # make sure this sheet exist e.g. create it before df = pd.read_excel(excel_file, "Sheet1") #sheet 1 contains the data see above # combine these different collections into a list data_to_plot = [df._series['val_1']] # Create a figure instance fig = plt.figure(1, figsize=(8, 8)) # Create an axes instance ax = fig.add_subplot(111) # Create the boxplot bp = ax.boxplot(data_to_plot) for flier in bp['fliers']: flier.set(marker='o', color='#e7298a', alpha=0.5) # Save the figure fig.savefig('val_1.png', bbox_inches='tight') # load the created boxplot image and insert in sheet2 img = openpyxl.drawing.image.Image('val_1.png') worksheet.add_image(img,'D3') workbook.save(excel_file) just one last thing i try to add the x labels as diagonal like shown here: https://matplotlib.org/examples/pylab_examples/boxplot_demo2.html i added these lines before : bp = ax.boxplot(data_to_plot) xtickNames = plt.setp(ax, xticklabels="Label_1") plt.setp(xtickNames, rotation=45, fontsize=10) but with this i only see a single character "L" in the x axis not "Label_1" instead of these two lines i tried this one: ax.set_xticklabels( ['Label_1'], rotation=45 ) but it also doesnt work now i see a diagonal '1' ???
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88446109
downvote count: 1
upvote count: 0
accepted answer of: http://stackoverflow.com/q/49820878

http://stackoverflow.com/comment/86807762
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49895654
has text: @vishu after `select_related` you can access `record.tableBID.Name` without additional query.
type: Comment

http://stackoverflow.com/a/66255565
answers question: http://stackoverflow.com/q/49900117
score: 2
has body: # instead of driver.find_elements_by_xpath() use driver.find_element_by_xpath() to get the individual element of the table from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import time # Google Chrome driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get("https://testautomationpractice.blogspot.com/") # Get Number of Rows rows = len(driver.find_elements_by_xpath("//*[@id='HTML1']/div[1]/table/tbody/tr")) # Get Number of Columns columns = len(driver.find_elements_by_xpath("//*[@id='HTML1']/div[1]/table/tbody/tr[1]/th")) print("Number of Rows:", rows) print("Number of Columns:", columns) # In web table index starts with 1 instead of 0 for row in range(2, rows+1): for col in range(1,columns+1): value = driver.find_element_by_xpath("//*[@id='HTML1']/div[1]/table/tbody/tr["+str(row)+"]/td["+str(col)+"]").text print(value, end=' ') print() time.sleep(5) # Close the Browser driver.close()
upvote count: 2
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86666387
has text: If what gets printed is exactly right there isn't any need to put it through the csv writer. Can you give an example of the output you want?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49825186

http://stackoverflow.com/comment/86666004
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49818404
has text: @methuselah Yes my bad, got confused as I've been working a lot with JS recently, I'll update my answer with the correct way of accessing a Python dict.
type: Comment

http://stackoverflow.com/comment/86702817
has text: Have you tried `xtest.loc[(xtest['SportYes'] == 200) & (xtest['stateYes'] == 200), 'k'] = 3` ?
comment on: http://stackoverflow.com/q/49844117
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/49781417
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86598780
has comment: http://stackoverflow.com/comment/86597488
accepted answer of: http://stackoverflow.com/q/49780698
has comment: http://stackoverflow.com/comment/86597984
has comment: http://stackoverflow.com/comment/86598883
has comment: http://stackoverflow.com/comment/86597217
downvote count: 0
answers question: http://stackoverflow.com/q/49780698
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/86598148
has body: Your code is on the right track but doesn't quite work in that you don't accumulate the download budget as you traverse through the list and are overlooking the end case. And as a result of not accumulating the download_budget, you while loop is only met for the second row (i == 1) and so nothing else works as it should. As well as fixing these problems, you could simplify it by using modulo (%) to get the third column and integer division / remainder (//) to get the last column entries. So, the code for that would look something like: download_total = 5000 budget = 0 for i, row in enumerate(my_lst): if i == 0: row += [0, 0] else: target = min(budget, download_total) row += [target % 2047 + my_lst[0][2], target // 2047 + my_lst[0][3]] budget += row[1] which gives our expected output of: [['A', 2312, 0, 0], ['B', 2000, 265, 1], ['C', 1312, 218, 2], ['D', 3000, 906, 2]] If you are stuck with anything just drop a comment but something that may be slight confusing is the use of the min() function. On this line, are goal is to assign a value - target - which is our goal for what the number for what this row should be (the third and fourth columns). So we want this target to be as big as possible: all of our budget. However, in the case where are budget exceeds the download_total (the last row) we want this row to be the download total rather than are budget which would be larger.
has comment: http://stackoverflow.com/comment/86599488
has comment: http://stackoverflow.com/comment/86597603
has comment: http://stackoverflow.com/comment/86599687
has comment: http://stackoverflow.com/comment/86600018
has comment: http://stackoverflow.com/comment/86606544
has comment: http://stackoverflow.com/comment/86598270
score: 1

http://stackoverflow.com/a/49798292
type: Answer
has body: scrapy.Spider is the simplest spider that would, basically, visit the URLs defined in start_urls or returned by start_requests(). CrawlSpider when you need a "crawling" behavior - extracting the links and following them: This is the most commonly used spider for crawling regular websites, as it provides a convenient mechanism for following links by defining a set of rules. It may not be the best suited for your particular web sites or project, but it’s generic enough for several cases, so you can start from it and override it as needed for more custom functionality, or just implement your own spider. By this "scrapy.spider" don't follow rules and "crawlspider" is the one that follows rules ,Thus the problem is not with those two So please check your xpath selector.
accepted answer of: http://stackoverflow.com/q/49797957
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86642285
answers question: http://stackoverflow.com/q/49797957

http://stackoverflow.com/comment/86732745
score: 0
type: Comment
type: QuestionComment
has text: @ikolim Thanks for the link but I won't be doing any changes suggested in similar topics where it's very unclear whether the proposed solution actually works. I see that the questioner has identical problem as me but the developer who proposed the solution got no feedback whether it works.
comment on: http://stackoverflow.com/q/49856958

http://stackoverflow.com/comment/86823711
has text: I believe it is uWSGI, how do I restart it?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49903965
type: Comment

http://stackoverflow.com/a/49779904
type: Answer
has comment: http://stackoverflow.com/comment/86616656
answers question: http://stackoverflow.com/q/49779430
has comment: http://stackoverflow.com/comment/86576347
has comment: http://stackoverflow.com/comment/86576957
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86577424
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49779430
has comment: http://stackoverflow.com/comment/86599122
has body: If you want to convert all the images in dataset to float point grayscale format, while keeping the three channels, you can just do: # (39000, 64, 64, 1) gray_dataset_1c = np.sum((dataset / 255.) * [0.299, 0.587, 0.114], axis=-1, keepdims=True) # (39000, 64, 64, 3) gray_dataset = np.tile(gray_dataset_1c, (1, 1, 1, 3)) Or with np.dot: # (39000, 64, 64) gray_dataset_1c = np.dot((dataset / 255.), [0.299, 0.587, 0.114]) # Since Python 3.5 this can be written like this: gray_dataset_1c = (dataset / 255.) @ [0.299, 0.587, 0.114] # (39000, 64, 64, 3) gray_dataset = np.tile(gray_dataset_1c[..., np.newaxis], (1, 1, 1, 3)) After a quick benchmark, it seems that np.dot is actually significantly faster for this use.

http://stackoverflow.com/q/49848575
favorite count: 0
has comment: http://stackoverflow.com/comment/86720961
type: Question
score: 3
type: UnansweredQuestion
tagged with: matplotlib
has title: How to edit table data with interactive event in matplotlib
tagged with: python
upvote count: 3
has comment: http://stackoverflow.com/comment/88869463
answer count: 1
has comment: http://stackoverflow.com/comment/86839774
downvote count: 0
linked to: http://stackoverflow.com/q/49893460
has comment: http://stackoverflow.com/comment/86720009
has body: A table is created in a figure. Now I want to edit the table after double click at the cell, adding, deleting or revising the data in this cell. Just like the edit function in Excel. My python version is 3.64. Codes are following: import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() # Hide axes ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) # Table from Ed Smith answer clust_data = [[1,1,7]] collabel=("col 1", "col 2", "col 3") ax.table(cellText=clust_data,colLabels=collabel,loc='center') plt.show()
linked to: http://stackoverflow.com/q/50932614
tagged with: interactive
has answer: http://stackoverflow.com/a/49848738

http://stackoverflow.com/a/49898412
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49897168
type: Answer
score: 3
has body: the google repo script option --config-name is broken (not working as supposed to be) as for the moment on version: ` repo version v1.12.37 (from https://gerrit.googlesource.com/git-repo) repo launcher version 1.23 (from /usr/bin/repo) git version 2.14.1 Python 2.7.14 (default, Sep 23 2017, 22:06:14) [GCC 7.2.0] ` but there is a work-around: immediately after repo init command but before following repo sync command to modify already existing file (repo will generate this file automatically): .repo/manifests.git/config by adding identity as following lines to the bottom of the file: ` [user] email = user@yourdomain.com name = User Name `

http://stackoverflow.com/comment/86814822
score: 0
has text: @BearBrown I tried this in the first time, but it gives me the same error,
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49898084

http://stackoverflow.com/comment/86730429
comment on: http://stackoverflow.com/a/49857764
type: Comment
score: 0
type: AnswerComment
has text: Nope. It is only to reduce the number of lines to make the code more readable.

http://stackoverflow.com/comment/86585679
has text: I tried with one only by slicing the array. It didnt work unfortunately
type: Comment
comment on: http://stackoverflow.com/q/49784969
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86614711
type: AnswerComment
comment on: http://stackoverflow.com/a/49799613
has text: @MarcoDeVirgilis See my updated answer for a working solution and a more efficient code as a bonus
type: Comment
score: 0

http://stackoverflow.com/a/49906534
type: Answer
answers question: http://stackoverflow.com/q/49905351
has comment: http://stackoverflow.com/comment/86830688
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49905351
type: AcceptedAnswer
downvote count: 0
score: 4
has body: You're very close! Instead of boolean indexing, you can use xarray.where() with three arguments: &gt;&gt;&gt; xr.where(ds.coords['q-index'] == 0, 'gamma', ds['q-kinds']) &lt;xarray.DataArray (layer: 2, q: 6)&gt; array([['gamma', 'other', 'other', 'other', 'other', 'other'], ['other', 'other', 'other', 'other', 'gamma', 'gamma']], dtype=object) Coordinates: q-index (layer, q) int64 0 1 2 3 4 5 1 5 3 2 0 4 Dimensions without coordinates: layer, q Or equivalently, instead of using .isel() for assignment, you can use a dictionary inside [], e.g., &gt;&gt;&gt; indexer = dict(layer=xr.DataArray([1, 0]), q=xr.DataArray([5, 0])) &gt;&gt;&gt; ds['q-kinds'][indexer] = 'gamma' Note that it's important to create the DataArray objects explicitly inside the dictionary, because they are created with the same new dimension name dim_0: &gt;&gt;&gt; indexer {'layer': &lt;xarray.DataArray (dim_0: 2)&gt; array([1, 0]) Dimensions without coordinates: dim_0, 'q': &lt;xarray.DataArray (dim_0: 2)&gt; array([5, 0]) Dimensions without coordinates: dim_0} If you pass lists or 1D numpy arrays directly, they are assumed to along independent dimensions, so you would end up with "outer" style indexing instead: &gt;&gt;&gt; indexer = dict(layer=[1, 0], q=[5, 0]) &gt;&gt;&gt; ds['q-kinds'][indexer] = 'gamma' &gt;&gt;&gt; ds['q-kinds'] &lt;xarray.DataArray 'q-kinds' (layer: 2, q: 6)&gt; array([['gamma', 'other', 'other', 'other', 'other', 'gamma'], ['gamma', 'other', 'other', 'other', 'other', 'gamma']], dtype=object) Coordinates: q-index (layer, q) int64 0 1 2 3 4 5 1 5 3 2 0 4 Dimensions without coordinates: layer, q

http://stackoverflow.com/q/49795529
type: Question
has answer: http://stackoverflow.com/a/49800314
accepted answer: http://stackoverflow.com/a/49800314
tagged with: python
has body: Hope someone can help as i'm getting myself tied in knots here. Trying to copy a table and output it as a CSV using python, psycopg2 and postgresql. I need to have the table name and output file name as variables because I will be later changing tablename to an array so it can loop through multiple tables. My code is below, but I keep getting the following error, seems an extra set of quote marks are being added. Anyone know how to get round this please? fullTempBaseURL is: C:\Administrator Files\Worksorders.csv fullRawCSVURL is: G:\Team Drives\RawCSV\Worksorders.csv syntax error at or near ""C:\Administrator Files\Worksorders.csv"" LINE 1: copy (SELECT * FROM "Worksorders" ) to "C:\Administrator Fil... import psycopg2 from config import config from psycopg2 import sql import os tablename = 'Worksorders' tempBaseURL = 'C:\Administrator Files' RawCSVBaseURL = 'G:\Team Drives\RawCSV' fileType = '.csv' global fullTempBaseURL global fullRawCSVURL fullTempBaseURL = tempBaseURL + '\\' + tablename + fileType fullRawCSVURL = RawCSVBaseURL + '\\' + tablename + fileType print "fullTempBaseURL is: " + fullTempBaseURL print "fullRawCSVURL is: " + fullRawCSVURL ########################### #Copy table to CSV ########################### def tabletoCSV(): conn = None try: # read database configuration params = config() # connect to the PostgreSQL database conn = psycopg2.connect(**params) # create a new cursor cur = conn.cursor() # execute the SQL statement cur.execute("SET search_path TO dbo") cur.execute(sql.SQL("""copy (SELECT * FROM {tbl} ) to {url} with csv""").format(tbl = sql.Identifier(tablename), url = sql.Identifier(fullTempBaseURL))) # commit the changes to the database conn.commit() # close communication with the database cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() def moveFile(): os.rename(fullTempBaseURL, fullRawCSVURL) tabletoCSV() Thanks in advance, Jon
tagged with: psycopg2
upvote count: 2
tagged with: postgresql
type: AnsweredQuestion
has title: Python .format adding extra quotes to string when using psycopg2
has comment: http://stackoverflow.com/comment/86605732
score: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86606212
favorite count: 0
has comment: http://stackoverflow.com/comment/86605946
tagged with: string

http://stackoverflow.com/q/49818994
tagged with: ibm-cloud
has body: So I have a path structure that looks like this: ~/Dropbox/Coding/Python/Chessbotslack/scripts/Flask_interface.py ~/Dropbox/Coding/Python/Chessbotslack/database/spreadsheets.py The first line of the Flask_interface.py is: from Chessbotslack.database.spreadsheets import add_game If I run this from my IDE (PyCharm) it runs just fine; but if I run it from my terminal it throws the error: Traceback (most recent call last): File "Flask_interface.py", line 1, in &lt;module&gt; from Chessbotslack.database.spreadsheets import add_game ModuleNotFoundError: No module named 'Chessbotslack' To solve this I did two things: 1) Adding __init__.py to the directories This did seem to accomplish anything 2) Adding the directory to $PYTHONPATH In terminal I ran export PYTHONPATH=$PYTHONPATH:~/Dropbox/Coding/Python This solved the problem for running it from my terminal, but as expected it did not solve it for my IBM-Cloud. Perhaps it has something to do with the requirements.txt file? 2018-04-16T09:08:45.30+0200 [APP/PROC/WEB/0]ERR File "scripts/Flask_interface.py", line 1, in &lt;module&gt; 2018-04-16T09:08:45.30+0200 [APP/PROC/WEB/0]ERR from Chessbotslack.database.spreadsheets import add_game 2018-04-16T09:08:45.30+0200 [APP/PROC/WEB/0]ERR ImportError: No module named Chessbotslack.database.spreadsheets
tagged with: python
tagged with: module
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49854006
tagged with: pycharm
accepted answer: http://stackoverflow.com/a/49854006
answer count: 1
has title: "ImportError: No module" after uploading to IBM-Cloud
tagged with: macos
linked to: http://stackoverflow.com/q/2325923
type: Question
linked to: http://stackoverflow.com/q/3402168

http://stackoverflow.com/comment/86691930
type: AnswerComment
score: 0
has text: ..How do I download get-pip.py?
comment on: http://stackoverflow.com/a/49838201
type: Comment

http://stackoverflow.com/comment/86840554
score: 0
comment on: http://stackoverflow.com/a/49815956
has text: I can't think of any way to optimise it. Regardless of how you try to "optimise" it, you would still have to check if the JSON is a list, and if it is, iterate through those items.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86650229
type: QuestionComment
has text: [This discussion](https://stackoverflow.com/a/38236445/567620) about 'spawn' vs. 'fork' for new processes in Windows vs. Linux is probably relevant.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49817726

http://stackoverflow.com/q/49834380
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/49834968
favorite count: 0
has comment: http://stackoverflow.com/comment/86683985
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49834968
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/86685073
possible better answer: http://stackoverflow.com/a/55162207
has comment: http://stackoverflow.com/comment/86684861
linked to: http://stackoverflow.com/q/50310063
has comment: http://stackoverflow.com/comment/86684698
tagged with: python
has comment: http://stackoverflow.com/comment/86684787
has answer: http://stackoverflow.com/a/62169654
has title: K.gradients(loss, input_img)[0] return "None". (Keras CNN visualization with tensorflow backend)
has comment: http://stackoverflow.com/comment/86684567
type: Question
has comment: http://stackoverflow.com/comment/86685086
score: 12
answer count: 3
has comment: http://stackoverflow.com/comment/86684880
has body: I have CNN models trained using Keras with Tensorflow backend. And I want to visualize my CNN filters with this tutorial: https://blog.keras.io/how-convolutional-neural-networks-see-the-world.html from keras import backend as K from keras.models import load_model import numpy as np model = load_model('my_cnn_model.h5') input_img = np.load('my_picture.npy') # get the symbolic outputs of each "key" layer (we gave them unique names). layer_dict = dict([(layer.name, layer) for layer in model.layers]) layer_name = 'block5_conv3' filter_index = 0 # can be any integer from 0 to 511, as there are 512 filters in that layer # build a loss function that maximizes the activation # of the nth filter of the layer considered layer_output = layer_dict[layer_name].output loss = K.mean(layer_output[:, :, :, filter_index]) # compute the gradient of the input picture wrt this loss grads = K.gradients(loss, input_img)[0] # normalization trick: we normalize the gradient grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5) # this function returns the loss and grads given the input picture iterate = K.function([input_img], [loss, grads]) However, when the code execute to this line: grads = K.gradients(loss, input_img)[0] I found it returns nothing but None object, so the program fail to progress after that. I search for some solution. Some people say theinput_img should be tensorflow's Tensor type: https://github.com/keras-team/keras/issues/5455 But when I tried to convert the img to Tensor, the problem is still exist. I tried the solution in the link above, but still fail. There is also someone say that this problem exists because your CNN model is not differentiable. https://github.com/keras-team/keras/issues/8478 But my model use only the activate function of ReLU and Sigmoid(at output layer). Is this problem really caused by nondifferentiable problem? Can anyone help me? Thank you very much!
upvote count: 12
tagged with: neural-network
downvote count: 0
has answer: http://stackoverflow.com/a/55162207
tagged with: keras

http://stackoverflow.com/comment/86613748
has text: I don't know if it helps but I am using spyder on an anaconda distribution
comment on: http://stackoverflow.com/q/49799470
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49896559
has body: I studied a document talking about it, actually you will find a lot of articles on google if you search for "representative users" or even "seed users" terms
answers question: http://stackoverflow.com/q/49896402
type: Answer
score: 0

http://stackoverflow.com/comment/86583186
comment on: http://stackoverflow.com/a/49762466
type: Comment
has text: @HarshaVardhan try casting it and see, it may not be possible because of nans in your data.
type: AnswerComment
score: 0

http://stackoverflow.com/q/49901079
tagged with: python
has body: I have to write a function that takes in three parameters and returns True is the first two parameters are close in value to each other (they are within +/- the third parameter. def assert_within_tolerance(num1,num2,close): num1=float(num1) num2=float(num2) while close&gt;=0: if num1-num2&lt;=close: return True elif num2-num1&lt;=close: return True else: return False This code isn't returning True or False correctly and I'm not sure why
has answer: http://stackoverflow.com/a/49901136
accepted answer: http://stackoverflow.com/a/49901136
type: AnsweredQuestion
upvote count: 0
has title: Determining if two numbers are close in value by defining a function
has comment: http://stackoverflow.com/comment/86817894
favorite count: 0
type: Question
downvote count: 8
answer count: 2
has answer: http://stackoverflow.com/a/49901127
possible better answer: http://stackoverflow.com/a/49901127
tagged with: function
score: -8

http://stackoverflow.com/comment/86708251
score: 0
comment on: http://stackoverflow.com/a/49845506
type: Comment
has text: Yes, I've been toying with it a bit now and there are just so many ways to make Python crash or throw senseless errors that I don't think it's worth digging deeper.
type: AnswerComment

http://stackoverflow.com/comment/86618226
type: Comment
comment on: http://stackoverflow.com/q/49777905
type: QuestionComment
has text: Thanks for the comments, I edited my question to respond to them.
score: 0

xlwt
tags question: http://stackoverflow.com/q/49852474
tags question: http://stackoverflow.com/q/49763957
tag name: xlwt
type: Tag

http://stackoverflow.com/comment/86785161
score: 0
has text: Thank you so much. But why is there a permission error while I am running it as the root?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49884433

http://stackoverflow.com/a/49896551
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49896242
has body: Try this one : st = "ACTGTATGCATACACGTA" for i in range(0,len(st[:-4])): print(st[i:i+5]) O/P will be like : ACTGT CTGTA TGTAT GTATG TATGC ATGCA TGCAT GCATA CATAC ATACA TACAC ACACG CACGT ACGTA
answers question: http://stackoverflow.com/q/49896242
score: 0
has comment: http://stackoverflow.com/comment/86835657

http://stackoverflow.com/a/49817129
downvote count: 1
answers question: http://stackoverflow.com/q/49816348
accepted answer of: http://stackoverflow.com/q/49816348
type: AcceptedAnswer
type: Answer
score: -1
has body: Of course it is possible, as mentioned by @Dunno you need to run them in separate threads. Use threading module. from tkinter import * import cv2 import tkinter as tk import threading ui = Tk() ui.state('normal') canvas = tk.Canvas() canvas.pack(fill = 'both', expand = True) def video_stream(): video = cv2.VideoCapture(0) a = 0 while True: a+= 1 check, frame = video.read() cv2.imshow('Video', frame) key = cv2.waitKey(1) if key == 27: break video.release() cv2.destroyAllWindows th= threading.Thread(target=video_stream) #initialise the thread th.setDaemon(True) th.start() #start the thread ui.mainloop() #Run your UI
upvote count: 0

http://stackoverflow.com/comment/86585169
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49784543
type: Comment
has text: Wait, what error do you get on graph size? I have models that push 10GB. But perhaps not in variables. This is surprising to me though.

http://stackoverflow.com/a/49771117
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49770929
score: 2
downvote count: 0
has body: You can create MultiIndex first and then unstack with sort_index: N = 3 a = np.arange(len(df)) df.index = [a % N, a // N] df = df.unstack().sort_index(axis=1, level=1) df.columns = np.arange(len(df.columns)) print (df) 0 1 2 3 4 5 0 1.0 11.0 4.0 14.0 7.0 17.0 1 2.0 12.0 5.0 15.0 NaN NaN 2 3.0 13.0 6.0 16.0 NaN NaN
accepted answer of: http://stackoverflow.com/q/49770929
upvote count: 2

http://stackoverflow.com/a/49817487
answers question: http://stackoverflow.com/q/49813237
score: 0
has body: You can use cx_Freeze to create a desktop app from a python program. There's a guide to packaging a PyQt application: cxfreeze-quickstart # generates a creation script On OSX, you have the option of building a .dmg or a .app, by executing one of these at the prompt: python setup.py bdist_dmg python setup.py bdist_mac On Windows: python setup.py bdist_msi There's a comparison of deployment tools here.
type: Answer

http://stackoverflow.com/comment/86661679
type: Comment
type: QuestionComment
has text: @prune do you mean where I write to file 3?
score: 0
comment on: http://stackoverflow.com/q/49820587

http://stackoverflow.com/comment/86798259
comment on: http://stackoverflow.com/q/49888741
score: 0
type: QuestionComment
type: Comment
has text: Another short answer: if it's *close* to symmetric, but off by machine precision, then just force it, `x = (x + x.T) / 2`, and be done with it. But do check this carefully, if the values are very small or very large, then very bad things can happen…

http://stackoverflow.com/comment/86748269
comment on: http://stackoverflow.com/a/49866217
score: 0
type: Comment
type: AnswerComment
has text: FWIW, `ABS(STRFTIME("%s", mt1.date) - STRFTIME("%s", mt2.date)) < 7200` seems to be a little bit slower than the `JULIANDAY` condition. Does anyone know how to optimize these queries?

http://stackoverflow.com/comment/86830804
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49906127
has text: @user8212173 Thanks! But the string is so long that it has already exceeds the character limit on posting a question... So can't really do that. Thanks anyway!
type: Comment

http://stackoverflow.com/comment/86595195
comment on: http://stackoverflow.com/q/49789902
type: Comment
has text: @HrvojeT: The encoding that your Python script file itself uses and the encoding your `myFile.txt` uses are two completely different things.
score: 1
type: QuestionComment

cythonize
tags question: http://stackoverflow.com/q/49793671
type: Tag
tag name: cythonize

http://stackoverflow.com/comment/86815895
type: Comment
score: 0
type: AnswerComment
has text: I tried that and it sill shows sequentially. I have updated my original post to help understand what i am trying to do
comment on: http://stackoverflow.com/a/49876963

http://stackoverflow.com/comment/86571809
type: QuestionComment
comment on: http://stackoverflow.com/q/49765019
has text: See also [What is the difference between a function, an unbound method and a bound method?](https://stackoverflow.com/q/11949808/1222951)
score: 1
type: Comment

http://stackoverflow.com/comment/86550746
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49766004
type: Comment
has text: Indeed, I tried it as well and forgot to mention it. It has the same issue as `cython` or `C`, `Sum` is not implemented. Edited for completeness

http://stackoverflow.com/a/49817485
answers question: http://stackoverflow.com/q/49817025
type: Answer
has body: Use the row indices directly on A and then search for 138: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; A = np.array([[0, 0, 0, 138], ... [0, 8, 0, 0], ... [0, 1, 0, 0], ... [131, 0, 0, 138], ... [0, 0, 138, 0], ... [0, 0, 0, 0], ... [0, 115, 0, 8]]) &gt;&gt;&gt; &gt;&gt;&gt; idx = np.array([2, 4, 5]) &gt;&gt;&gt; &gt;&gt;&gt; y, x = np.where(A[idx]==138) &gt;&gt;&gt; y = idx[y] &gt;&gt;&gt; y, x (array([4]), array([2]))
score: 0

http://stackoverflow.com/comment/86683559
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49833740
has text: i have another problem, values will be multiple 2 after 2 times running the code...
score: 0

http://stackoverflow.com/comment/86705468
type: AnswerComment
has text: Is it O(n) because you are considered amortized analysis as shown here where O(3n) simplifies to O(n)? https://www.interviewcake.com/concept/java/dynamic-array-amortized-analysis
comment on: http://stackoverflow.com/a/49832810
type: Comment
score: 0

data-science
tags question: http://stackoverflow.com/q/49841626
tags question: http://stackoverflow.com/q/49772772
tags question: http://stackoverflow.com/q/49807797
tags question: http://stackoverflow.com/q/49833649
tags question: http://stackoverflow.com/q/49888898
tags question: http://stackoverflow.com/q/49776490
tags question: http://stackoverflow.com/q/49811885
tags question: http://stackoverflow.com/q/49872386
type: Tag
tags question: http://stackoverflow.com/q/49887961
tags question: http://stackoverflow.com/q/49870879
tag name: data-science
tags question: http://stackoverflow.com/q/49772870
tags question: http://stackoverflow.com/q/49862211

http://stackoverflow.com/comment/86707697
has text: Actually, you should not have to use plt.plot() in your script, just plt.show() should be enough.
type: Comment
comment on: http://stackoverflow.com/a/49845409
type: AnswerComment
score: 1

http://stackoverflow.com/a/75319282
answers question: http://stackoverflow.com/q/49791526
has body: There is no function in class Spreadsheet to close a session. Together with the solution from @kshishkin, there are 3 possible ways to 'close' a Google Spreadsheet: Open the required spreadsheet from within a function. When the function is out of the scope, the spreadsheet object will be closed automatically by Python. Call del the_googlesheet_obj to delete it google sheet object directly. the_googlesheet_obj is the returned object of the googlesheet. Call Spreadsheet.client.session.close() object within a the googlesheet object. Here is an example: from google.colab import auth from google.auth import default import gspread # Open Google Sheet from within Google Colab auth.authenticate_user() gc = gspread.authorize(default()[0]) gs = gc.create('New Googlesheet') # Create a new Googlesheet document print(f'{gs.id=}') # Unique key of the Googlesheet document print(f'{gs.title=}') # Title of the Googlesheet document print(f'{gs.url=}') # URL of the Googlesheet document ws = gs.get_worksheet(0) # Get the first worksheet ws.update('A1', [[1,2], [3, 4]]) # Update from cell A1 ws.client.session.close() # Close the session
type: Answer
score: 0

http://stackoverflow.com/a/49900073
answers question: http://stackoverflow.com/q/49861009
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49861009
upvote count: 1
has body: The Problem with create_dataset When you get an element of the ndarray, you loose the rank associated with that element. This happens because if you are interested in that single element, then you don't need to retain the dimension 1: x = np.random.randn(4, 4) print(x, x.shape) array([[ 1.37938213, -0.10407424, -0.356567 , -1.5032779 ], [-0.53166922, 0.98204605, -0.62052479, 0.99265612], [ 0.23046477, -0.17742399, 0.38283412, 0.24104468], [-0.78093724, 1.06833765, -1.22112772, -0.78429717]]) (4, 4) print(x[0:3, 0], x[0:3, 0].shape) array([ 1.37938213, -0.53166922, 0.23046477]) (3,) So when you write a = dataset[i:(i + look_back), 0], you are taking a dataset of shape (samples, features) and getting a chunk of shape (look_back,). After adding all a's to dataX, it becomes an ndarray of shape (samples, look_back) = (len(dataset) - look_back - 1, look_back). However, the LSTM is expecting the shape (samples, look_back, features), which in your case (samples, look_back, 1). If you change it to a = dataset[i:(i + look_back)], then things will start to work. A better solution, however, is to use TimeseriesGenerator: from keras.preprocessing.sequence import TimeseriesGenerator batch_size = 4 look_back = 1 features = 1 d = np.random.randn(364, features) train = TimeseriesGenerator(d, d, length=look_back, batch_size=batch_size, end_index=282) test = TimeseriesGenerator(d, d, length=look_back, batch_size=batch_size, start_index=282) model = Sequential() model.add(LSTM(6, input_shape=[look_back, features], activation='relu')) model.add(Dense(1)) model.compile(loss='mse', optimizer='rmsprop') model.fit_generator(train, epochs=1, verbose=1) p_train = model.predict_generator(train) p_test = model.predict_generator(test) Further Comments on Other Sections model.add(LSTM(6, input_shape=(1, look_back),activation= 'relu')) - the input shape should conform with (length, features). In this case, where length == features, things would work out. You do need to update this code to input_sh…

http://stackoverflow.com/a/49816248
accepted answer of: http://stackoverflow.com/q/49815709
answers question: http://stackoverflow.com/q/49815709
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has body: Solution: data = pd.read_csv("test.csv", delim_whitespace=True)
type: Answer

http://stackoverflow.com/q/49843345
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
tagged with: keras
has body: I'm currently developing a model using Keras + Tensorflow for calculating sentence similarity based on the STS benchmark (http://ixa2.si.ehu.es/stswiki/index.php/STSbenchmark). How I did it was that I first created a pre-trained model that converts a list of word embedding vectors into a single sentence embedding vector. Now, what I want to do is incorporate this pre-trained model to a new model which uses this model to transform the input. The following is the code for that new model. sentence_encoder = load_model('path/to/model') input1 = Input(shape=(30, 300), dtype='float32') # 30 words, 300 dim embedding input2 = Input(shape=(30, 300), dtype='float32') x1 = sentence_encoder(input1) x2 = sentence_encoder(input2) abs_diff = Lambda(lambda x: abs(x[0] - x[1]))([x1, x2]) x = Dense(300, activation='relu', kernel_initializer='he_uniform')(abs_diff) result = Dense(1, activation='sigmoid')(x) model = Model([input1, input2], result) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) model.fit(...) When I run this, a model is produced and is correctly done so. What I want to know however, is if the sentence_encoder gets trained along with this new model or do its weights remain unchanged? If possible, I'd like the sentence_encoder's weights to be influenced by the training of this new model. If this doesn't achieve that, how do I go about doing it? Thank you in advance!
type: AnsweredQuestion
tagged with: deep-learning
score: 1
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49843371
tagged with: pre-trained-model
has title: Pre-trained Model on Multiple Inputs
has answer: http://stackoverflow.com/a/49843371

http://stackoverflow.com/comment/86781943
score: 0
type: Comment
type: QuestionComment
has text: As for the continuous movement, [these answers](https://stackoverflow.com/q/33537959/6220679) will be helpful to you. BTW, please ask only one specific question at a time and search for existing answers on Stack Overflow.
comment on: http://stackoverflow.com/q/49880016

http://stackoverflow.com/a/49849489
answers question: http://stackoverflow.com/q/49849433
downvote count: 0
type: AcceptedAnswer
has body: You can roll back the migration locally, and then re-apply it. The previous migration that this one depends on is 0021_auto_20180412_1215, so you can roll back to that state with: manage.py migrate 0021 When you then run manage.py migrate again it will apply this new migration afresh. From the documentation: migrate &lt;app_label&gt; &lt;migrationname&gt;: Brings the database schema to a state where the named migration is applied, but no later migrations in the same app are applied. This may involve unapplying migrations if you have previously migrated past the named migration.
type: Answer
accepted answer of: http://stackoverflow.com/q/49849433
score: 4
upvote count: 4

http://stackoverflow.com/comment/86821286
score: 0
comment on: http://stackoverflow.com/q/49902788
has text: I need to open many different files with different names, and i dont have the name of those files for the moment, i just have some 'training files' that ables to test if the code is correct, but i'll have to change one by one all of the files names i open in the code when i'll have the final files
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86773955
comment on: http://stackoverflow.com/a/49873639
type: AnswerComment
has text: @Basj - No, the index on `column2` does not necessarily need to be unique in order for the query optimizer to take advantage of it. However, depending on the index statistics it *might* decide that a non-unique index does not offer a significant advantage over a table scan. However, in the vast majority of cases the index will be helpful.
score: 0
type: Comment

http://stackoverflow.com/q/49789832
has title: difference between wilcox and mannwhitneyu test in python (in case of range difference)
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I need to do a wilcox test between 2 lists with uneven range. The link - Python wilcoxon: unequal N suggests to use the following from scipy.stats import mannwhitneyu mannwhitneyu(range(10), range(12)) As per my knowledge the hypothesis approach by both tests differ so can we do this in programming or do we have any other solution.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/33890367
tagged with: python
has answer: http://stackoverflow.com/a/49809813
score: -1
tagged with: statistics
upvote count: 0

http://stackoverflow.com/a/49862939
downvote count: 0
answers question: http://stackoverflow.com/q/49862853
has body: It is unclear why you want this behaviour, but you can achieve this with pd.DataFrame.iloc. If you only need specific columns, replace : with a list of column numbers. import pandas as pd, numpy as np df = pd.DataFrame(np.random.random((5, 5))) for i in range(len(df.index)): print(df.iloc[[i], :]) # 0 1 2 3 4 # 0 0.587349 0.947435 0.974285 0.498303 0.135898 # 0 1 2 3 4 # 1 0.292748 0.880276 0.522478 0.081902 0.187494 # 0 1 2 3 4 # 2 0.692022 0.908397 0.200202 0.099722 0.348589 # 0 1 2 3 4 # 3 0.041564 0.980425 0.899634 0.725757 0.569983 # 0 1 2 3 4 # 4 0.787038 0.000077 0.213646 0.444095 0.022923
score: 2
type: Answer
upvote count: 2

http://stackoverflow.com/q/49887198
tagged with: google-calendar-api
tagged with: python
tagged with: text
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: api
accepted answer: http://stackoverflow.com/a/49887234
has answer: http://stackoverflow.com/a/49887234
has title: Python save output as text file
tagged with: string
type: Question
has body: I'm using Python for a school project and I wanted to use the Google Calendar API for it. I just followed Google's guide for it and I added the last bit to try and save the outputs onto a text file, however, the problem I'm having is that it's only saving the very last event. I'm not very experienced in Python, so any explanation why and how I can make it do what I want would be super duper helpful! Thank you! """ Shows basic usage of the Google Calendar API. Creates a Google Calendar API service object and outputs a list of the next 10 events on the user's calendar. """ from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools import datetime # Setup the Calendar API SCOPES = 'https://www.googleapis.com/auth/calendar.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('calendar', 'v3', http=creds.authorize(Http())) # Call the Calendar API now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 10 events') events_result = service.events().list(calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) if not events: print('No upcoming events found.') for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) outFile = open('sample.txt' , 'w') outFile.write((start)) outFile.write( str(event['summary'])) outFile.close()
possible better answer: http://stackoverflow.com/a/49887236
has answer: http://stackoverflow.com/a/49887236

http://stackoverflow.com/comment/86669878
score: 1
type: Comment
has text: Well for one, you can't refer to `self` directly in the body of the class, it's only accessible in the body of the property function because `self` is declared as a parameter. Doing `id = user_id` would be syntactically correct, but I wouldn't recommend it because SQLAlchemy may not handle it the way you expect - for example it may think `id` is supposed to be a separate DB column, or get confused and throw an error. What I've recommended I'm sure will work, and has the added benefit of making the new properties read-only so you can control whether Flask-Security can change your values.
type: AnswerComment
comment on: http://stackoverflow.com/a/49819693

http://stackoverflow.com/q/49890639
has body: Right now I'm using PLY to implement a parser for a very small subset of English. For instance, I have a lists of names for nouns and small sets of intransitive verbs, transitive verbs, and dative verbs, and I can make sentences out of different combinations of these. However, in my lexer, I am having an issue with efficiently defining the elements belonging to each token. For instance, for the nouns, if the set of names I wish to include is [Harry, Ron, Hermione, Draco, Snape], the only way I could find to assign these values to the token "N" for noun is tokens = ['N', 'Vi', 'Vt', 'Vd', 'Conj'] t_N = r'Homer|Marge|Bart|Maggie|Lisa|SLH' But this seems like a very inefficient way of assigning these, and does not leave room for expansion. For instance if I want to add a list of names from a text file to this there is no clean way to do so. Is there a way to define a list as the specification of a token in PLY?
has title: How to specify elements of a list as a token's specifications in PLY
type: AnsweredQuestion
score: 0
tagged with: ply
accepted answer: http://stackoverflow.com/a/49891107
type: Question
has answer: http://stackoverflow.com/a/49891107
answer count: 1
tagged with: python

http://stackoverflow.com/comment/86699719
comment on: http://stackoverflow.com/a/49841062
score: 0
type: AnswerComment
has text: I meant within the code without openning the browser. e.g. I can see the available resolution from the page sourse too, so I was thinking I can get the page source, read the avilable resolutions, then again send the request with appropriate `rs` data
type: Comment

http://stackoverflow.com/comment/86690374
score: 0
type: AnswerComment
has text: yes, you'd just need to create a function that spits out all the combinations. Try it out and see what you come up with. Share what you did and post again if you get stuck. Also, @darxtrix's answer on this question should help: https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements
comment on: http://stackoverflow.com/a/49837502
type: Comment

http://stackoverflow.com/comment/86806489
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49895393
score: 0
has text: There is no csv file. I update the question to make it easier for you to backtest. 2 sec

http://stackoverflow.com/a/49810400
has comment: http://stackoverflow.com/comment/86635430
has body: I would use split two times: lines = string.split('\n') output = [line.split(',')[0] for line in lines]
has comment: http://stackoverflow.com/comment/86635898
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49810315
has comment: http://stackoverflow.com/comment/86635817
type: Answer
has comment: http://stackoverflow.com/comment/86635625
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/86635411
has comment: http://stackoverflow.com/comment/86635622
answers question: http://stackoverflow.com/q/49810315

http://stackoverflow.com/q/49830446
score: 1
has title: Divide the txt file into lists by symbol, python3
has comment: http://stackoverflow.com/comment/86676742
has answer: http://stackoverflow.com/a/49831154
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have a txt file, ~1-10MB, like this: "Type,int_data,ID,..., some data" I want to separate it by ID. For example do the following: list_1=[] list_2=[] list_3=[] .. list_7=[] with open(txt,'r', encoding='utf-8') as txt: for string in txt: string=string.rstrip().split(',') ID=int(string[2]) if ID==1: list_1.append(string) elif ID==2: list_2.append(string) .. But it's quite slow.. can it be better?
has answer: http://stackoverflow.com/a/49830945
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86676138
answer count: 2
accepted answer: http://stackoverflow.com/a/49831154
possible better answer: http://stackoverflow.com/a/49830945
has comment: http://stackoverflow.com/comment/86676068

http://stackoverflow.com/q/49805707
tagged with: python
upvote count: 0
type: UnansweredQuestion
has title: How to retrieve a login form written in simple html file when clicked on the login button using flask?
score: -3
answer count: 1
has body: After running the index.html file when we click on login button, the form needs to be displayed for which I have created a login.html file, now how do I link this file in flask? I have put all the html files in the templates folder. Obviously the info added by the user needs to be entered into the MySQL workbench database.
has comment: http://stackoverflow.com/comment/86627078
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/49808109
type: Question
tagged with: http://stackoverflow.com/tag/html
downvote count: 3

http://stackoverflow.com/a/49856987
answers question: http://stackoverflow.com/q/49816754
score: 1
downvote count: 0
upvote count: 1
has body: 1) score = model.predict(rb.fit_transform(testData)) When you do the above, you are re-fitting the RobustScaler to the new data. That means that it will be scaled to new data and will not match the scales of the training data. So the results will not be good. 2) score = model.predict(testData) In the above, you are not scaling the test data, so its different that what the SVC has learnt. Hence the results will be bad here also. What you need to do:- score = model.predict(rb.transform(testData)) Calling transform() will scale the supplied data based on training data scales, and hence the SVC can better predict the output.
type: Answer

http://stackoverflow.com/comment/86539385
score: 0
has text: Too much code. Please provide us a [mcve].
comment on: http://stackoverflow.com/q/49762019
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49778621
tagged with: python
answer count: 0
has body: The following code is the binary search function of a larger binary search problem. My understanding was that the lower bounds should be the minimum value in a sorted array, and the upper bound should be the highest index(or max value). Why is max() and sum() being used in this case? def binarySearch(A, max_block_cnt, M): lower_bound = max(A) upper_bound = sum(A) if max_block_cnt == 1: return upper_bound if max_block_cnt &gt;= len(A): return lower_bound while lower_bound &lt;= upper_bound: candidate_mid = (lower_bound + upper_bound) // 2 if blockSizeIsValid(A, max_block_cnt, candidate_mid): upper_bound = candidate_mid - 1 else: lower_bound = candidate_mid + 1 return lower_bound This problem is the MinMaxDivision problem. Please let me know if more detail is needed. Edit--appears more info needed. Here's the question I'm working on: You are given integers K, M and a non-empty zero-indexed array A consisting of N integers. Every element of the array is not greater than M. You should divide this array into K blocks of consecutive elements. The size of the block is any integer between 0 and N. Every element of the array should belong to some block. The sum of the block from X to Y equals A[X] + A[X + 1] + ... + A[Y]. The sum of empty block equals 0. The large sum is the maximal sum of any block. For example, you are given integers K = 3, M = 5 and array A such that: A[0] = 2 A[1] = 1 A[2] = 5 A[3] = 1 A[4] = 2 A[5] = 2 A[6] = 2 The array can be divided, for example, into the following blocks: [2, 1, 5, 1, 2, 2, 2], [], [] with a large sum of 15; [2], [1, 5, 1, 2], [2, 2] with a large sum of 9; [2, 1, 5], [], [1, 2, 2, 2] with a large sum of 8; [2, 1], [5, 1], [2, 2, 2] with a large sum of 6. The goal is to minimize the large sum. In the above example, 6 is the minimal large sum. Write a function: def solution(K, M, A) that, given integers K, M and a non-empty zero-indexed array A consisting of N integers, returns the minimal large sum. For example, given K = 3, M = 5 an…
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
has title: Why is the lower bound in this binary search function the max value instead of the min?
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/49762102
has comment: http://stackoverflow.com/comment/86539622
tagged with: python
has comment: http://stackoverflow.com/comment/86539619
has answer: http://stackoverflow.com/a/49762337
score: 2
has answer: http://stackoverflow.com/a/49762157
answer count: 2
upvote count: 2
downvote count: 0
has body: I am in Python and have a list of numbers that I want to write to a csv file. Say, my list is: [1 2 3 4 5 6 7 8 9], and within the csv file to which I am exporting this data, I want to begin a new line every three numbers. Meaning, when I open my output file in Excel, I want it to look like this. So, I essentially want to take a 9 element list and write it into a 3x3 matrix. I'm sure I must end up using the writerows command, but have not been able to find documentation of a problem similar enough to mine, so I am not sure exactly what to do with it. Any help would be greatly appreciated, and I'm sorry if this question has already been asked at some point.
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86539656
has title: Writing a list to a csv file in Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86539609

http://stackoverflow.com/comment/86698124
comment on: http://stackoverflow.com/q/49841147
type: QuestionComment
score: 0
has text: That’s not the problem. If it works outside setup.py it should work inside. So you have to ask, what am I doing different? Sudo is a difference. Run it all in a new folder without sudo and see if it builds.
type: Comment

http://stackoverflow.com/comment/86576371
has text: I am getting this now after I removed the '' around the value for portfolioValue _mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1")
type: Comment
comment on: http://stackoverflow.com/a/49780275
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86727700
has text: Great! I was asserting it incorrectly @Gang. In regards to to where I patched, I realized this simulated an `OverFlowError` not where I wanted it to, since at the end what I really want is to check that `radiation` is `np.nan`. But first I had to make sure the the overflow error was produced. Thanks for answering my question. I'm updating the above(with the right patches) for what I wanted to test(in case it helps anyone).
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49826584

http://stackoverflow.com/a/74903427
score: 0
answers question: http://stackoverflow.com/q/49842901
has body: I would recommend using String lib like the one below String command; void loop() { if (Serial.available()) { command = Serial.readStringUntil('\n'); command.trim(); command.equals("something"); /*your Implementation here*/ } } it works well for me
type: Answer

http://stackoverflow.com/a/49856846
has comment: http://stackoverflow.com/comment/123897085
type: Answer
has comment: http://stackoverflow.com/comment/86728176
answers question: http://stackoverflow.com/q/49853604
has comment: http://stackoverflow.com/comment/86734654
has comment: http://stackoverflow.com/comment/86728235
score: 1
downvote count: 0
upvote count: 1
has body: As the encryption and decryption is done at the client side, .NET framework 4.6 or above is needed. Version 1 of Always Encrypted only supported SQL Server Client driver but ODBC and JDBC drivers were not supported. It seems nothing have changed even for pyodbc as shown here.
has comment: http://stackoverflow.com/comment/123896102

http://stackoverflow.com/q/49828386
answer count: 2
tagged with: python
type: UnansweredQuestion
score: 0
has body: Given the following bokeh chart (this code must be run in a jupyter notebook): from bokeh.io import output_notebook, show from bokeh.plotting import figure from bokeh.palettes import Dark2_5 as palette from bokeh.layouts import widgetbox, row, column from bokeh.models.widgets import CheckboxButtonGroup import itertools import numpy as np output_notebook() # create a new plot (with a title) using figure p = figure(plot_width=800, plot_height=400, title="My Line Plot") start = 10.0 x = range(20) colors = itertools.cycle(palette) nseries = 50 # add a line renderer for n in range(nseries): y = np.cumsum(np.random.randn(1,20)) p.line(x, y, line_width=1, legend=str(n), color=next(colors)) p.legend.location = "top_left" p.legend.click_policy="hide" checkbox_button_group = CheckboxButtonGroup( labels=[str(n) for n in range(nseries)], active=[0, 1]) show(column([p, checkbox_button_group])) # show the results Which produces a chart like this: How can I connect up the checkbox buttons so that they show/hide the relevant series on the plot? Note: I know that I can click the legend to achieve this effect. However, I want to plot more series than the legend can show (e.g. it only shows 13 series in the screenshot). Obviously, people will only have maybe 10 series shown at any one time otherwise it becomes hard to see information.
tagged with: bokeh
has answer: http://stackoverflow.com/a/49829332
has answer: http://stackoverflow.com/a/49828740
type: Question
has title: Show/Hide Series in Bokeh Chart Based on Widget Selection

http://stackoverflow.com/q/49766058
type: Question
tagged with: debugging
has comment: http://stackoverflow.com/comment/86552312
has comment: http://stackoverflow.com/comment/86551387
has comment: http://stackoverflow.com/comment/86552046
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86551627
has comment: http://stackoverflow.com/comment/86550822
answer count: 0
has comment: http://stackoverflow.com/comment/86550230
has body: I've got a Django instance running nicely. An endpoint is secured using jwt . Naturally, I cannot use the browser as it don't know how to send jwt headers, so I use curl which works fine. Now, if something goes wrong, django dump ~2852 lines of html in to my terminal. Can I reduce this somehow? Ideally I would like to just return the same things that's logged when an error returns. Only in debug=True of course. Any pointers?
has title: Slick django debug error?
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86547901
has comment: http://stackoverflow.com/comment/86552565
favorite count: 0

http://stackoverflow.com/q/49861405
downvote count: 0
has body: I have a set of inputs. I am trying to write a regex to match the following pattern in the input: Day at Time on location Example input: Today at 12:30 PM on Sam's living room The bolded part of the text varies in each input. I wrote the following regex: import regex as re input_example = "Today at 12:30 PM on Rakesh's Echo" regexp_1 = re.compile(r'(\w+) at (\d+):(\d+) (\w+) on (\w+)') re_match = regexp_1.match(input_example) Which works, I am matching the correct patterns. I am now trying to extract groups from within the pattern. My desired output is: re_match.group(1) &gt;&gt; "Today" re_match.group(2) &gt;&gt; "12:30 PM" re_match.group(3) &gt;&gt; "Sam's living room" However, my current regular expression match does not give me this output. What is the correct regex that will give me the above outputs?
has answer: http://stackoverflow.com/a/49861571
score: 13
has comment: http://stackoverflow.com/comment/86738062
has answer: http://stackoverflow.com/a/49861585
accepted answer: http://stackoverflow.com/a/49861585
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49861569
upvote count: 13
tagged with: python
tagged with: regex
type: AnsweredQuestion
answer count: 3
has title: Extracting groups in a regex match
possible better answer: http://stackoverflow.com/a/49861569

http://stackoverflow.com/comment/86656206
score: 0
comment on: http://stackoverflow.com/q/49818842
type: Comment
type: QuestionComment
has text: after `dr = csv.DictReader(fin)`, if you insert a line `print(next(dr))`, what does it print out?

testing
tags question: http://stackoverflow.com/q/49884901
tags question: http://stackoverflow.com/q/49804304
type: Tag
tags question: http://stackoverflow.com/q/49847629
tags question: http://stackoverflow.com/q/49770559
tag name: testing
tags question: http://stackoverflow.com/q/49853949
tags question: http://stackoverflow.com/q/49853782
tags question: http://stackoverflow.com/q/49780547
tags question: http://stackoverflow.com/q/49800444
tags question: http://stackoverflow.com/q/49902650
tags question: http://stackoverflow.com/q/49790995

http://stackoverflow.com/comment/86645846
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49815749
has text: and what are you expecting as result? like the whole string after 10 days, only the data from each person etc.

http://stackoverflow.com/comment/86631240
comment on: http://stackoverflow.com/q/49801036
type: Comment
has text: You aren't hashing the file contents but rather the repr of the FileInput object. As the repr has the object ID in it which explains why it changes.
type: QuestionComment
score: 0

http://stackoverflow.com/q/49857892
downvote count: 0
has answer: http://stackoverflow.com/a/49912096
answer count: 1
favorite count: 0
tagged with: parallel-processing
type: Question
tagged with: popen
has comment: http://stackoverflow.com/comment/86807759
score: 3
has body: I have a Python helper function to run grunt commands in parallel, using Popen to handle subprocesses. The purpose is communication over CLI. The problem starts when any user input is required for all those processes, e.g. file path, password, 'yes/no' decision: Enter file path: Enter file path: Enter file path: Enter file path: Enter file path: Enter file path: Enter file path: Everything up-to-date Grunt task completed successfully. User provides input once, one process completes successfully and all others never finish executing. Code: from subprocess import check_output, Popen def run_grunt_parallel(grunt_commands): return_code = 0 commands = [] for command in grunt_commands: with tempfile.NamedTemporaryFile(delete=False) as f: app = get_grunt_application_name(' '.join(command)) commands.append({'app': app, 'process': Popen(command, stdout=f)}) while len(commands): sleep(5) next_round = [] for command in commands: rc = command['process'].poll() if rc == None: next_round.append(command) else: if rc == 0: else: return_code = rc commands = next_round return return_code Is there a way to make sure that user can provide all necessary input for each process?
tagged with: python
type: UnansweredQuestion
has title: How can I handle user input for subprocesses ran in parallel in Python?
has comment: http://stackoverflow.com/comment/86742983
tagged with: python-3.x
upvote count: 3
has comment: http://stackoverflow.com/comment/86773820
tagged with: multithreading
has comment: http://stackoverflow.com/comment/86762828

rx-py
tag name: rx-py
type: Tag
tags question: http://stackoverflow.com/q/49797475
tags question: http://stackoverflow.com/q/49803754

http://stackoverflow.com/comment/86588832
score: 0
comment on: http://stackoverflow.com/q/49785149
type: QuestionComment
type: Comment
has text: You lost me. You always set `time.sleep(1)` why is that?

http://stackoverflow.com/comment/86786252
type: QuestionComment
comment on: http://stackoverflow.com/q/49884903
score: 0
has text: You don't edit the output file, you import it in your main file
type: Comment

http://stackoverflow.com/q/49872844
has body: This shall be a quite simple question but indeed caught me. My purpose is to load a trained TF model, then create a session to run the predict/inference, and evaluate an appropriate batch_size for my device environment. I prepared two types of model: frozen model and saved model. For the frozen model, I successfully loaded and get the GraphDef by .ParseFromString(), and optimized the GraphDef by TensorRT, but the batch_size of input node is fixed to 1 (1*299*299*3). Seems like the batch_size can't be configured when exporting then freeze model, and can't be changed afterwards because it's append-only. For the saved model, the dimension of input node is ? (?*299*299*3). Seems it shall be able to accept any size of batch. But after I loaded the saved model, then input a 299*299*3 image, and get below ERROR: ValueError: Cannot feed value of shape (299, 299, 3) for Tensor u'input:0', which has shape '(?, 299, 299, 3)' I tried to expand a axis=0 to the input image, but still get error: InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'import/input' with dtype float and shape [?,299,299,3] [[Node: import/input = Placeholder[dtype=DT_FLOAT, shape=[?,299,299,3], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]] Overall, this is supposed to be a quite simple question, but I'm not sure how to solve it. Any idea will be welcome. Thanks, The script with frozen model, the placeholder is fixed to (1*299*299*3), so it only accepts "args.batch_size" to be 1. g = ops.Graph() with g.as_default(): inp, out = importer.import_graph_def(graph_def=f32_graph, return_elements=['Placeholder','InceptionV3/Logits/SpatialSqueeze']) inp = inp.outputs[0] out = out.outputs[0] print tf.shape(inp) if args.image: import numpy as np func = TestKit.preprocess_func['tensorflow'][args.network] img = func(args.image) img = np.expand_dims(img, axis = 0) batch_input = img for i in range(int(args.batch_size)-1): batch_input = np.concatenate((batch_input, …
score: 1
has comment: http://stackoverflow.com/comment/86761955
has title: How to load trained TensorFlow model to predict with different batch size?
tagged with: tensorflow
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49899119

http://stackoverflow.com/comment/86751000
has text: I liked the explanation and it helped me understand class methods better. I up-voted either way for your outside-the-box solution, but I find the other answers more cleaner.
comment on: http://stackoverflow.com/a/49867547
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86699571
type: QuestionComment
type: Comment
has text: You also aren't writing anything in the loop
score: 0
comment on: http://stackoverflow.com/q/49842440

http://stackoverflow.com/comment/86684509
has text: @WillemVanOnsem It was just pasting issue, it should be fixed now. However, I am getting error on those lines: line 28, in <module> sentence() line 5, in wrapper for items in func(): TypeError: 'NoneType' object is not iterable
type: QuestionComment
comment on: http://stackoverflow.com/q/49834617
score: 0
type: Comment

http://stackoverflow.com/comment/86761413
type: Comment
comment on: http://stackoverflow.com/q/49872752
score: 0
type: QuestionComment
has text: Your strings contain spaces at the end, there are no substrings of others in your list. To remove the spaces do `lst = list(map(str.strip, lst))`

http://stackoverflow.com/comment/86537742
comment on: http://stackoverflow.com/a/49760059
has text: much cleaner answer than mine. I didn't know about groupby (outside pandas), so good
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/q/49758489
upvote count: 8
possible better answer: http://stackoverflow.com/a/49763457
has comment: http://stackoverflow.com/comment/122957443
has title: Running Python code in Vim without saving
has answer: http://stackoverflow.com/a/49763457
has answer: http://stackoverflow.com/a/54817758
tagged with: python
answer count: 4
tagged with: vim
score: 8
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/87288937
has answer: http://stackoverflow.com/a/49758653
has comment: http://stackoverflow.com/comment/122957474
downvote count: 0
accepted answer: http://stackoverflow.com/a/49759464
linked to: http://stackoverflow.com/q/40289706
has body: Is there a way to run my current python code in vim without making any changes to the file? Normally, when I want to test my code from within vim, I would execute this: :w !python However, this overrides the current file I am editing. Often, I add print statements or comment stuff out to see why my code isn't working. I do not want such changes to overwrite a previous version of whatever .py file I'm currently working on. Is there a way to do so? Perhaps a combination of saving to a temporary file and deleting it afterwards?
has comment: http://stackoverflow.com/comment/86537444
favorite count: 0
has answer: http://stackoverflow.com/a/49759464
type: Question

http://stackoverflow.com/comment/86811107
has text: @Aran-Fey: I edited your code. Let me know if you accept the edit
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49896671
type: AnswerComment

http://stackoverflow.com/comment/123445131
score: 0
type: AnswerComment
has text: how to run all cells of a notebook from a different notebook
comment on: http://stackoverflow.com/a/51573381
type: Comment

http://stackoverflow.com/comment/86619400
has text: When you do these steps: `df_b = pd.DataFrame(raw_data, columns = ['type', 'id', 'name_2' ])` you can change the colnames after like `df_a.columns = ['type_2','id_2','name_2']`...with the right column names for each dataframe, you should get your desired merge result.
comment on: http://stackoverflow.com/q/49801805
score: 0
type: Comment
type: QuestionComment

database
tags question: http://stackoverflow.com/q/49769131
tags question: http://stackoverflow.com/q/49816092
tags question: http://stackoverflow.com/q/49883144
tags question: http://stackoverflow.com/q/49840355
tags question: http://stackoverflow.com/q/49861144
tags question: http://stackoverflow.com/q/49795791
type: Tag
tags question: http://stackoverflow.com/q/49852825
tags question: http://stackoverflow.com/q/49826012
tags question: http://stackoverflow.com/q/49833346
tags question: http://stackoverflow.com/q/49778278
tag name: database

http://stackoverflow.com/q/49824788
tagged with: python
has comment: http://stackoverflow.com/comment/86677091
has title: Sklearn Tfidf Vectorizer norm=None norm-l2
has body: Hi I'm trying to understand how scikit-learn works out the TFIDF score in the matrix: document 1, feature 6, "wine": test_doc = ['The wine was lovely', 'The red was delightful', 'Terrible choice of wine', 'We had a bottle of red'] # Create vectorizer vec = TfidfVectorizer(stop_words='english') # Feature vector tfidf = vec.fit_transform(test_doc) feature_names = vec.get_feature_names() feature_matrix = tfidf.todense() ['bottle', 'choice', 'delightful', 'lovely', 'red', 'terrible', 'wine'] [[ 0. 0. 0. 0.78528828 0. 0. 0.6191303 ] [ 0. 0. 0.78528828 0. 0.6191303 0. 0. ] [ 0. 0.61761437 0. 0. 0. 0.61761437 0.48693426] [ 0.78528828 0. 0. 0. 0.6191303 0. 0. ]] I was using the answer to a very similar question to calculate it for myself: How areTF-IDF calculated by the scikit-learn TfidfVectorizer However in their TFIDFVectorizer, norm=None. As I'm using the default setting of norm=l2, how does this differ to norm=None and how can I calculate it for myself?
score: 3
has comment: http://stackoverflow.com/comment/86677865
tagged with: tfidfvectorizer
answer count: 1
linked to: http://stackoverflow.com/q/36966019
linked to: http://stackoverflow.com/q/42440621
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/74088386
linked to: http://stackoverflow.com/q/43091235
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86675719
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/86669933
tagged with: tf-idf
tagged with: normalization
type: UnansweredQuestion

http://stackoverflow.com/comment/86570033
comment on: http://stackoverflow.com/q/49776109
has text: Just a guess, but it might be because you didn't explain how the `**kwargs` should be handled, or because you didn't post your own attempt at writing `product_function`.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49855476
has title: Checking for unique maps in csv file using pandas python
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86728205
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86728504
upvote count: 1
has answer: http://stackoverflow.com/a/49857325
favorite count: 0
type: Question
tagged with: logic
has body: I am attaching a screen shot of an excel file. It contains x,y and z values in three columns. What i want to check is how many functional loops are present, meaning "(x>x),(x>y, y>x), (x>y,x>y1), (x>y,y>x1)". I want to write a sample code to check the number of functional loops present in this excel file. I wrote a sample code to check for (x>x), but i am not able to write a code for the other loops. Any help will be appreciated. what it means by x>x is both elements in column 1 and 2 are equal What it means by (x>y, y>x) is element in column 1 maps to an element in column 2 and the same element in column 2 maps to the same element in column 1 import pandas as pd df = pd.read_csv('/home/amit/Desktop/playing_with_pandas.csv') xy_data = df.iloc[:,0:2] x&gt;x = xy_data[xy_data.nunique(1).eq(1)] print("the number of x&gt;x are",x&gt;x) Screen shot of csv
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49857325
score: 1

http://stackoverflow.com/comment/86755930
type: AnswerComment
comment on: http://stackoverflow.com/a/49870315
has text: thanks for the answer, it will generate only one url right ?
score: 0
type: Comment

http://stackoverflow.com/comment/86816041
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of ['list' object has no attribute 'get\_attribute' while iterating through WebElements](https://stackoverflow.com/questions/47735375/list-object-has-no-attribute-get-attribute-while-iterating-through-webelemen)
comment on: http://stackoverflow.com/q/49900117

if-statement
tags question: http://stackoverflow.com/q/49834671
tags question: http://stackoverflow.com/q/49834317
tags question: http://stackoverflow.com/q/49883194
tags question: http://stackoverflow.com/q/49852622
tags question: http://stackoverflow.com/q/49835155
tag name: if-statement
tags question: http://stackoverflow.com/q/49764248
tags question: http://stackoverflow.com/q/49914779
type: Tag
tags question: http://stackoverflow.com/q/49913211
tags question: http://stackoverflow.com/q/49804580
tags question: http://stackoverflow.com/q/49860379
tags question: http://stackoverflow.com/q/49800701
tags question: http://stackoverflow.com/q/49865790
tags question: http://stackoverflow.com/q/49838146
tags question: http://stackoverflow.com/q/49916212
tags question: http://stackoverflow.com/q/49767101
tags question: http://stackoverflow.com/q/49881114
tags question: http://stackoverflow.com/q/49908828
tags question: http://stackoverflow.com/q/49834650
tags question: http://stackoverflow.com/q/49906794
tags question: http://stackoverflow.com/q/49834849
tags question: http://stackoverflow.com/q/49879874
tags question: http://stackoverflow.com/q/49876618
tags question: http://stackoverflow.com/q/49821100
tags question: http://stackoverflow.com/q/49860435

http://stackoverflow.com/a/49838467
type: Answer
accepted answer of: http://stackoverflow.com/q/49838401
has body: When documentation fails, look into the code (python 3.6.4): At the _pysqlite_query_execute function end: if (PyErr_Occurred()) { self-&gt;rowcount = -1L; return NULL; } else { Py_INCREF(self); return (PyObject*)self; } } PyObject* pysqlite_cursor_execute(pysqlite_Cursor* self, PyObject* args) { return _pysqlite_query_execute(self, 0, args); } So, unless an error occurred, the method returns self. However, according to PEP 249 (for DB API 2) return values are not defined, which means you are on your own, and possibly the code you write in that way will not be portable among different DB API 2 implementations. And indeed, according to psycopg docs .execute returns None. The answer is, one can't safely chain methods in a broader sense, because doing so limits future code reuse possibilities.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86692415
score: 1
answers question: http://stackoverflow.com/q/49838401

http://stackoverflow.com/a/49914104
score: 1
has body: As you are asking for regular expressions, try this: import pandas data = [{'ID': 1, 'Text': 'Dear Mr. Alpha Terra, your food is delivered'}, {'ID': 2, 'Text': 'Dear Mrs. Betta Irina Viruva, your drink is delivered'}] df = pandas.DataFrame(data) df['Name'] = df.Text.str.extract(r'\.(.*?),') print(df) Here is a repl for you to try this out.
upvote count: 1
has comment: http://stackoverflow.com/comment/86843712
type: Answer
answers question: http://stackoverflow.com/q/49913887
downvote count: 0

http://stackoverflow.com/comment/89623728
comment on: http://stackoverflow.com/q/49909957
score: 0
type: Comment
type: QuestionComment
has text: Did you ever get this working?

http://stackoverflow.com/comment/86569982
has text: I don't see any use, except perhaps to have an integer (although casting would be much simpler), or perhaps it was written in a Python version that didn't have that method. You might want to write a PR to fix it
comment on: http://stackoverflow.com/q/49777115
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86623835
type: QuestionComment
score: 0
has text: @9000, it uses the paramiko module to ssh into remote hosts, execute commands, grab output, uses regex against the output to get a value, then write the result to a file. Each host connected to has their own file, and when all of the hosts are complete I will combine the content from all the files to a super file that will comprise the report. Not sure if this answers you question.
type: Comment
comment on: http://stackoverflow.com/q/49804474

http://stackoverflow.com/comment/86721661
comment on: http://stackoverflow.com/q/49852972
type: QuestionComment
has text: Please include some example data and samples of erronous results compared to what you expected. In other words produce a [mcve]. What database are you using?
score: 0
type: Comment

http://stackoverflow.com/comment/86684215
type: QuestionComment
comment on: http://stackoverflow.com/q/49833200
type: Comment
score: 0
has text: @NilsWerner there are typically 2 to 4 matrices and one vector for each function call (and there are a lot of function calls). Each matrix is small : 3x3. They are rotation matrices in 3d space. If I summarize the other comments, there is no easy way to do what I wanted and anyway it might not be worth the shot.

http://stackoverflow.com/comment/86582119
type: QuestionComment
has text: Sure, I mean, did you try `plt.plot([1,2,3], [4,5,6]); plt.plot([2,5],[1,2])`?!
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49760712

http://stackoverflow.com/q/49887545
tagged with: list
answer count: 3
score: 0
has answer: http://stackoverflow.com/a/49887718
has body: import imgcompare ... for filename in os.listdir(myPath): if filename.endswith(".png"): listIm1.append(filename) for filename2 in os.listdir(myPath2): if filename2.endswith(".png"): listIm2.append(filename2) so i fill my two lists with images,now I would like to compare the images of the two lists one by one following the same index, for example: listIm1[0] with listImg2[0] listIm1[1] with listImg2[1] and so on... and that's the code: for item in listIm1: ifSame = imgcompare.is_equal(listIm1[item],listIm2[item],tolerance=2) print ifSame but get the error: same = imgcompare.is_equal(listIm1[item], listIm2[item], tolerance=2) TypeError: list indices must be integers, not str it seems that imgcompare.is_equal() does not work with lists, is there some pythonic expedient to make it works?
type: Question
accepted answer: http://stackoverflow.com/a/49887721
tagged with: image-comparison
has answer: http://stackoverflow.com/a/49887721
possible better answer: http://stackoverflow.com/a/49887734
has answer: http://stackoverflow.com/a/49887734
has title: work with image: imgcompare does not support list?
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/49868445
has title: Pandas: Compute sum of values for each unique element ('ID') in a given timeframe and then compute the median across all 'ID's
tagged with: python
has comment: http://stackoverflow.com/comment/86752948
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49870113
downvote count: 0
answer count: 1
has body: I am working on a dataset containing data from taxi rides in the city of Chicago. The data contains information per trip such as Taxi ID, Timestamp, Fare etc. among others. A sample of the data is shown below from df.head() with the timestamps in pandas datetime: Taxi ID Pickup Community Area Trip Total Trip End Timestamp 2016-04-25 18:00:00 bfec2c659fcbed3b508dc6caaf6f7ef39e17801e8ca0cc... 8.0 16.00 2016-11-16 15:45:00 f45c4bfa9d6c445eb03ab69093f7ec1e9cdecef83cb2ce... 32.0 9.75 2016-01-15 17:45:00 ecfb6f2cdce5d4c4e80218f58070ae719060ee47e648f4... 32.0 14.75 2016-01-20 21:30:00 7d8179131ea9952793af4cda8635e94b56c2b92d3c376c... 32.0 7.25 2016-02-11 09:15:00 d5c4fbae1c0c510364404a90fd477b19f7f03408ce40ff... 35.0 18.75 Assuming I have data for one week, I want to achieve this: Consider a user-chosen binning choice: e.g.: hour. Group the data by taxi ID, and sum up the amount made by each taxi within that one hour. Compute the median of all such 'hourly revenues' between all taxis according to taxi ID (still within that one hour). Repeat for each hour in the timeframe. For a week, this is 24*7 = 168 times. Plot the median per hour across all hours in the week. This can be extended to hours in a week, weeks in a year etc. As of now, I am able to use pivot_table to, say, obtain the median revenue per hour of the day over the whole timeframe (but this is not for every hour in the week), or resample to obtain the median fare over time (but this is not 'hourly revenue' of the taxis, this is the median fare per trip). Neither of those would achieve exactly what I want, how should I implement this?
has comment: http://stackoverflow.com/comment/86752375
type: AnsweredQuestion
tagged with: median
accepted answer: http://stackoverflow.com/a/49870113
tagged with: pandas
upvote count: 1
score: 1

http://stackoverflow.com/a/63587520
answers question: http://stackoverflow.com/q/49900340
has comment: http://stackoverflow.com/comment/112448981
upvote count: 2
has body: While looking for a problem, which I try to solve I found your question. For a solution that includes full code (with py and 2 HTML files) you can see my repl.it : https://repl.it/@AlperenAtik/NaturalShortActivecell#main.py The problems are: In the first function, you routed your loop to "/send" page. This is why your send page did not appear. The route of the first function needs to be "/" In the index file, the source route was shown as '/send'. Whenever I changed it to / the script worked without a problem The other commentators already mentioned your triggering function has an indentation mistake. When host and port added appropriately, your script would work. for ones who love the harder way- seeing things in stackoverflow- not in action, I am adding the codeblocks. Enjoy. for main.py from flask import Flask, render_template,request app = Flask(__name__) @app.route('/',methods = ['GET','POST']) def send(): if request.method == 'POST': age = request.form['age'] return render_template('age.html',age=age) return render_template('index.html') if __name__ == '__main__': app.run(host = '0.0.0.0', port = 8080 I left the host as '0.0.0.0' and port as 8080. If you are running Python on a terminal, you may try (host = '127.0.0.1', port:5000'). for templates/index.html How old are you? for templates/age.html Your age is {{age}}
score: 1
downvote count: 1
type: Answer

http://stackoverflow.com/comment/97115796
type: Comment
comment on: http://stackoverflow.com/q/49797287
type: QuestionComment
score: 0
has text: You could try np.savez_compressed also. For me the size went from 200MB to 3MB on switching to this from np.savez

http://stackoverflow.com/a/49807477
has comment: http://stackoverflow.com/comment/86629930
score: 0
answers question: http://stackoverflow.com/q/49807373
has body: Your top-level JSON dict has a single key-value pair, widgets, which itself is a dict with a single key-value pair, widget, which is a list with a single object, which, finally, contains the objects you actually want. This is easier to see if you pretty-print it: { "widgets": { "widget": [ { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images\/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": 36, "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity \/ 100) * 90;" } } ] } } So, obviously, iterating for k, v in a.items(): just loops one time, with k set to widgets and v set to the widgets dict. If you want to loop over all of the elements of that list, you need to do that explicitly: for k, v in a['widgets']['widget'][0].items(): Alternatively, there are a few standards for searching JSON in a more direct way (JSONPath, a simpler one I forget the name of, one based on CSS selectors, Apple's KVC, …), and libraries for all of them on PyPI. One of those libs would let you do something like: for k, v in jsonsearch(a, 'widgets/widget/0/*').items(): … which, if you later find examples with multiple things in the list, could be changed trivially to: for k, v in jsonsearch(a, 'widgets/widget/*/*').items(): However, I don't know any of these standards, or libraries, well; you'll have to do your own research to pick one that works for you.
type: Answer
has comment: http://stackoverflow.com/comment/86630052
has comment: http://stackoverflow.com/comment/86629959

http://stackoverflow.com/a/49888306
answers question: http://stackoverflow.com/q/49888276
type: Answer
has comment: http://stackoverflow.com/comment/86793057
score: 0
has body: Your startet function in aldd.py is not returning anything. Try adding this line at the end of the startet function return 'testing testing .. 123'

http://stackoverflow.com/comment/86620006
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49802662
has text: (Actually *trying* your proposed solution -- of having multiple supervisors and seeing if the same effect takes place -- would similarly provide a useful datapoint).

http://stackoverflow.com/comment/86737797
has text: Oh, I thought the x->y correspondence should have been maintained. You understood it differently, I see.
type: AnswerComment
comment on: http://stackoverflow.com/a/49861287
type: Comment
score: 0

http://stackoverflow.com/comment/124730506
has text: This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/30717078)
type: Comment
comment on: http://stackoverflow.com/a/70550573
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86678533
has text: Ah right, so it's on the `GET`. The `data-key` attr to the script should be your public key. But your example doesn't match the key you've put in the view.
comment on: http://stackoverflow.com/q/49829777
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/86686938
has text: alright then, let's see more of your code then because it's too less to figure out something
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49835647

http://stackoverflow.com/q/49902843
answer count: 1
downvote count: 0
type: Question
has body: I am using SQLALchemy to execute queries on Teradata. One of the queries I execute is a DDL statement to replace a stored procedure: REPLACE PROCEDURE DEV_MIGRATION_TOOL.UNIT_TEST_NEW_STORED_PROCEDURE() UNIT_TEST_NEW_STORED_PROCEDURE: BEGIN DECLARE V_VAR VARCHAR(50); SELECT 'Hello World!' INTO :V_VAR; END; This SQL statement is assigned to a variable query and is executed by SQLALchemy with the session execute method: def execute_sql_statement(self, query): """Generic method to execute a SQL statement on target environment.""" self.target_environment.db_session.execute(query) self.target_environment.db_session.commit() The problem I have it that SQLAlchemy assumes the :V_VAR variable is a parameter which should be supplied with a dictionary. See documentation here: http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.execute result = session.execute("SELECT * FROM user WHERE id=:param", {"param":5}) In the current configuration, it triggers the error message: 2018-04-18 19:09:27,874 - migration_script - INFO - Execute object DDL statement on UAT environment. 2018-04-18 19:09:27,875 - migration_script - ERROR - (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter 'V_VAR' [SQL: "()\rUNIT_TEST_NEW_STORED_PROCEDURE:\rBEGIN\r DECLARE V_VAR VARCHAR(50);\r SELECT 'Hello World!'\r INTO ?;\rEND;"] [parameters: [{}]] Would you know a way to avoid this error message so that my DDL statement above is executed without error?
tagged with: binding
score: 10
tagged with: executequery
tagged with: teradata
tagged with: python
upvote count: 10
tagged with: sqlalchemy
favorite count: 0
accepted answer: http://stackoverflow.com/a/49913328
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49913328
has title: Avoid Parameter Binding When Executing Query with SQLAlchemy

http://stackoverflow.com/a/49891785
accepted answer of: http://stackoverflow.com/q/49891727
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49891727
has body: You can use list comprehensions: P= [[3.2, 3.7, 2.1], [4.5, 2.1, 2.3], [3.1, 2.5]] P2 = [[int(round(x,0)) for x in y] for y in P] # P is your list of lists # y is each inner list # x is each element in y # rounding logic is as yours print(P2) Output: [[3, 4, 2], [5, 2, 2], [3, 3]] Edit: 2.7 and 3.6 behave differently - I used a 2.7 shell. See round() Note The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information. You can fix it by creating your own round-Method: def myRounder(num): return int(num)+1 if num - int(num) &gt;= 0.5 else int(num) P= [[3.2, 3.7, 2.1], [4.5, 2.1, 2.3], [3.1, 2.5]] P2 = [[int(myRounder(x)) for x in y] for y in P] # P is your list of lists # y is each inner list # x is each element in y # rounding logic is as yours print(P2) This will lead to the same results on 2.7 and 3.x.
has comment: http://stackoverflow.com/comment/86801149
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/86799449

http://stackoverflow.com/comment/86785584
score: 0
comment on: http://stackoverflow.com/a/49884553
type: Comment
has text: would this require data to be sorted by columns `emp, vendor, date, amounts, rounds`?
type: AnswerComment

http://stackoverflow.com/a/49815287
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49814896
accepted answer of: http://stackoverflow.com/q/49814896
type: Answer
has body: The issue is you are assuming column-major ordered values, which is not the case with NumPy/Python. So, for a general case of using a mask to assign values with the column-major ordered values, we need to transpose both the input array and mask and assign those, like so - B.T[mask.T] = C.flatten() Sample run for explanation on getting the right order and assigning - In [36]: B = np.arange(1,10).reshape(3,3) In [37]: B Out[37]: array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) In [38]: mask = np.tril(np.ones(3, dtype=bool)) In [39]: mask Out[39]: array([[ True, False, False], [ True, True, False], [ True, True, True]]) In [40]: B.T[mask.T] Out[40]: array([1, 4, 7, 5, 8, 9]) # right order (col major) obtained # Finally assign into masked positions In [41]: B.T[mask.T] = C.flatten() In [42]: B Out[42]: array([[1, 2, 3], [0, 1, 6], [0, 0, 1]])

http://stackoverflow.com/a/49953725
type: Answer
has comment: http://stackoverflow.com/comment/87000851
has comment: http://stackoverflow.com/comment/87033134
has comment: http://stackoverflow.com/comment/87112213
has body: Python3 makes lot of things easier by using the default encoding as unicode. But in Python2 you get a default str and different unicode representation Now consider the case of en-dash = –, looks similar to a normal - but is not. Let's fire up a python 2.7 console and see the difference &gt;&gt;&gt; val_str = '–' &gt;&gt;&gt; val_str '\xe2\x80\x93' Above is how an en-dash is represented by a str. While for unicode &gt;&gt;&gt; val_unicode = u'–' &gt;&gt;&gt; val_unicode u'\u2013' Now let's try and write these to a csv file using different combinations # -*- coding: utf-8 -*- import csv import io val_str = '–' val_unicode = u'–' def try_writing_csv(filename, data, mode='w', **kwargs): try: with io.open(filename, mode=mode, **kwargs) as f: c = csv.writer(f, dialect='excel') c.writerow([data]) except Exception, ex: print("failed to write - " + filename) try_writing_csv("ascii1.csv", val_str) try_writing_csv("ascii2.csv", val_str, encoding="utf8") try_writing_csv("ascii3.csv", val_str.decode('utf8'), encoding="utf8") try_writing_csv("unicode1.csv", val_unicode) try_writing_csv("unicode2.csv", val_unicode, encoding="utf8") try_writing_csv("unicode3.csv", val_unicode.encode('utf8'), encoding="utf8") And now let's run the same failed to write - ascii1.csv failed to write - ascii2.csv failed to write - ascii3.csv failed to write - unicode1.csv failed to write - unicode2.csv failed to write - unicode3.csv The results are overwhelming as all the method fails. So we need look at what is wrong with it. Let's make some more trials try_writing_csv("ascii4.csv", val_str.decode('utf8'), mode="wb") try_writing_csv("ascii5.csv", val_str, mode="utf8") try_writing_csv("ascii6.csv", val_str.decode('utf8').encode('utf8'), mode="wb") try_writing_csv("unicode4.csv", val_unicode, mode="wb") try_writing_csv("unicode5.csv", val_unicode.encode('utf8'), mode='wb') And now out run would give an output failed to write - ascii1.csv failed to write - ascii2.csv failed to write - ascii3.csv failed to…
has comment: http://stackoverflow.com/comment/87003463
has comment: http://stackoverflow.com/comment/87033019
answers question: http://stackoverflow.com/q/49882234
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/49882926
has comment: http://stackoverflow.com/comment/86821975
answers question: http://stackoverflow.com/q/49882030
downvote count: 0
upvote count: 1
has body: Try making a WCS object with the correct WCS parameters for your image, and then call header = wcs.to_header, and store the image data and header in the FITS file. See example here. Usually you don't create WCS or headers yourself, it's something you read from FITS files. In that case you do wcs = WCS(header) to create a WCS object from the FITS header. See example here.
has comment: http://stackoverflow.com/comment/86812473
score: 1
has comment: http://stackoverflow.com/comment/86830786
type: Answer
has comment: http://stackoverflow.com/comment/86823016

http://stackoverflow.com/comment/86794497
comment on: http://stackoverflow.com/q/49889173
has text: Don't just say "I am getting a Key error", give us the actual error. It tells you, among other things, which line the error was on and what the key was. You also need to show us what's in `percentage`—ideally by just replacing the first two lines of your code with a simple `percentage = <some pandas expression using nothing but constants>`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49883875
has answer: http://stackoverflow.com/a/49884687
has answer: http://stackoverflow.com/a/49884218
tagged with: dataframe
tagged with: python
has title: Mapping columns of two data frames and adding a value from the list
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/49884687
tagged with: pandas
has body: I have two data frames, df1 contains Id and Items, the representation of that list looks like below . ITEM ID - [(itemid, weight, 3)] Using the below data frames, we need to add up the weight of itemID of every value in a list using the item data frame value. ID - DF1 ID ITEMS 11 [(123, 2.12,3),(234, 1.2,3)] 22 [(567, 2.3, 3),(245, 1.9,3)] 33 [(999,4.5, 3),(222, 2.0,3)] 44 [(223, 2.34,3),(234,3.5,3)] ITEM - DF2 ITEMS WEIGHT 123 2.5 234 1.8 567 19 245 3 999 2 222 2.9 223 4.2 Expected output : ID Items 11 [(123, 2.12+2.5,3),(234, 1.2+1.8,3)] 22 [(567,4.2,3),(245,4.9,3)] 33 [(999, 6.5, 3), (222, 4.9,3)] 44 [(223, 6.54,3),(234,5.3,3)] The first row is shown as example, [(123, 2.12+2.5,3),(234, 1.2+1.8,3)].
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86783940
accepted answer: http://stackoverflow.com/a/49884218

http://stackoverflow.com/q/49833649
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
score: -2
has answer: http://stackoverflow.com/a/49833688
tagged with: python
has title: How to get Specific Cell Value from CSV With Respect To Row And Column Value using python
has comment: http://stackoverflow.com/comment/86682582
has answer: http://stackoverflow.com/a/49833719
answer count: 2
tagged with: pandas
downvote count: 3
upvote count: 1
tagged with: data-science
favorite count: 0
type: Question
has body: sample data: user,hotel_name,city,review adam,hotel1,chennai,"Wow, what charm! As a Travel Agent. john,hotel2,pune,Great location for sporting events. mike,hotel3,mumbai,Its the best of the best. george,hotel4,delhi,Ok hotel in a bad location. Hello all, I would like to print the review given by mike from csv file. I am new to python can some one help me?
tagged with: anaconda

http://stackoverflow.com/comment/86776472
has text: What would you expect `intc` to be when running a 32-bit version of Python?
comment on: http://stackoverflow.com/q/49880203
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86777601
type: AnswerComment
has text: @tgtrmr I'd ask a new question for that task. If you do so, feel free to ping me in a comment and I'll send a reply!
comment on: http://stackoverflow.com/a/49866802
score: 1
type: Comment

http://stackoverflow.com/q/49807032
has comment: http://stackoverflow.com/comment/86628938
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86629159
has title: Python Script Invalid Syntax error on a downloaded script
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86628917
tagged with: python
accepted answer: http://stackoverflow.com/a/49807188
has answer: http://stackoverflow.com/a/49807188
has body: i want to try a script from a GameStateIntegration def sendHealthStatus(health): # Send health status to arduino if health == 100: arduino.write('h') arduino.write(str(health)) if health &lt; 100 and &gt;= 10: arduino.write('h0') arduino.write(str(health)) if health &lt; 10 and &gt;= 0: arduino.write('h00') arduino.write(str(health))` but i get an invalid syntax for if health &lt; 100 and &gt;= 10: in fact of the '=' sign, when I remove it , it tells me that the '>' is the error what is wrong with that script ? Greetings from Germany Björn
type: Question
has comment: http://stackoverflow.com/comment/86629023
score: 0

http://stackoverflow.com/comment/86836260
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49908058
has text: Fitting with lmfit uses many Python features that are not pickleable. You might try the `dill` package..

http://stackoverflow.com/comment/86633158
has text: Thanks for your help, when I run your code `pytest test_hello.py` it gives me the error: "ModuleNotFoundError: No module named 'test_hello'".
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49808218

group-by
tags question: http://stackoverflow.com/q/49904400
tags question: http://stackoverflow.com/q/49865790
tags question: http://stackoverflow.com/q/49822003
tag name: group-by
tags question: http://stackoverflow.com/q/49868282
tags question: http://stackoverflow.com/q/49889312
tags question: http://stackoverflow.com/q/49846343
type: Tag
tags question: http://stackoverflow.com/q/49898955

http://stackoverflow.com/q/49799998
has title: Tensorflow Dataset - How to build batchs given a generator outputting X inputs for 1 label?
has answer: http://stackoverflow.com/a/49801051
tagged with: deep-learning
upvote count: 2
answer count: 1
downvote count: 0
tagged with: machine-learning
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
type: Question
tagged with: python
has body: Short Version Given a generator sampling e.g. 3 inputs and 1 label, how can I define my Tensorflow Dataset pipeline to obtain batches of K * 3 inputs and K * 1 labels? Longer Version Context I am using a Triplet network, and want to adapt my current input pipeline to use Tensorflow Dataset. In my case, a batch consists of N (e.g. images) and N // 3 labels (supposing N % 3 == 0), with each label applied to 3 consecutive inputs, e.g. labels = [compute_label(inputs[3*i], inputs[3*i+1], inputs[3*i+2]) for i in range(N // 3)] with compute_label(*args) a simple function, which can be implemented either with Tensorflow operations or basic Python. To make things a bit more complicated, the input elements must be sampled 3 by 3 (e.g. we want inputs[3*i] to be similar to inputs[3*i+1] and dissimilar to inputs[3*i+2]): for i in range(N // 3): inputs[3*i], inputs[3*i+1], inputs[3*i+2] = sample_triplet(i) Question Reformulating the shorter question to my particular case: Given these two functions sample_triplet() and compute_label(), how can I build my input pipeline using Tensorflow Dataset, to build batches with N inputs and N // 3 labels? I tried several combinations of tf.data.Dataset.from_generator() and tf.data.Dataset.flat_map() but couldn't find a way to both flatten the batch inputs from N // 3 triplets to N samples, and output only N // 3 batch labels. A solution I found was to "cheat" by computing my labels inside tf.data.Dataset.from_generator() and tiling each label 3 times, to be able to use tf.data.Dataset.flat_map() over the triplet inputs + labels. As a batch-postprocessing step, I am then "squeezing" the N duplicated labels back to N // 3. Example with Current Solution import tensorflow as tf import numpy as np def sample_triplet(): # Sampling our elements, here as [class, random_val] elements: anchor_class = puller_class = pusher_class = np.random.randint(0, 10) while pusher_class == anchor_class: # we want the pusher to be of a different class pusher_class = …
linked to: http://stackoverflow.com/q/48471926
accepted answer: http://stackoverflow.com/a/49801051
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/49864917
has body: I have a large file that I need to parse - and since it will be regenerated from external queries every time script runs so there is no way to parse it once and cache the results. I want to save memory footprint and read and parse only logical "chunks" of that file everything between open 'product' and closing curly bracket. Not sure what is the canonical way in Python but I tried the following: def read_chunk(file_name, pattern_open_line, pattern_close_line): with open(file_name,"r") as in_file: chunk = [] in_chunk = False open_line = re.compile(pattern_open_line); close_line = re.compile(pattern_close_line) try: for line in in_file: line = line.strip() if in_chunk: chunk.append(line) if close_line.match(line): yield chunk if open_line.match(line): chunk = [] chunk.append(line) in_chunk = True continue except StopIteration: pass def get_products_buffered(infile): chunks = read_chunk(infile, '^product\s*$', '^\s*\}\s*') products = [] for lines in chunks: for line in lines: if line.startswith('productNumber:'): productNumber = line[len('productNumber:'):].strip().rstrip(';').strip('"') products.append(productNumber) continue return products def get_products_unbuffered(infile): with open(infile) as f: lines = f.readlines() f.close() products = [] for line in lines: if line.startswith('productNumber:'): productNumber = line[len('productNumber:'):].strip().rstrip(';').strip('"') products.append(productNumber) continue return products I profiled both runs and while unbuffered reading is faster: Buffered reading Found 9370 products: Execution time: 3.0031037185720177 Unbuffered reading Found 9370 products: Execution time: 1.2247122452647523 it also incurs a much bigger memory hit when file is essentially read into memory: Line # Mem usage Increment Line Contents ================================================ 29 28.2 MiB 0.0 MiB @profile 30 def get_products_buffered(infile): 31 28.2 MiB 0.0 MiB chunks = read_chunk(infile, '^product\s*$', '^\s*\}\s*') 32 28.2 MiB 0.0 MiB …
has comment: http://stackoverflow.com/comment/86747032
tagged with: python
tagged with: generator
type: Question
tagged with: large-files
answer count: 0
has comment: http://stackoverflow.com/comment/86745302
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86745221
score: 0
has title: Using generator for buffered parsing of large file

http://stackoverflow.com/q/49793652
favorite count: 0
type: Question
has body: I have 2 dataframes df1 and df2 of different size. df1 = pd.DataFrame({'A':[np.nan, np.nan, np.nan, 'AAA','SSS','DDD'], 'B':[np.nan,np.nan,'ciao',np.nan,np.nan,np.nan]}) df2 = pd.DataFrame({'C':[np.nan, np.nan, np.nan, 'SSS','FFF','KKK','AAA'], 'D':[np.nan,np.nan,np.nan,1,np.nan,np.nan,np.nan]}) My goal is to identify the elements of df1 which do not appear in df2. I was able to achieve my goal using the following lines of code. df = pd.DataFrame({}) for i, row1 in df1.iterrows(): found = False for j, row2, in df2.iterrows(): if row1['A']==row2['C']: found = True print(row1.to_frame().T) if found==False and pd.isnull(row1['A'])==False: df = pd.concat([df, row1.to_frame().T], axis=0) df.reset_index(drop=True) Is there a more elegant and efficient way to achieve my goal? Note: the solution is A B 0 DDD NaN
tagged with: for-loop
has answer: http://stackoverflow.com/a/49793816
tagged with: python
has title: Find different rows between 2 dataframes of different size with Pandas
type: AnsweredQuestion
tagged with: row
downvote count: 0
has comment: http://stackoverflow.com/comment/86601554
tagged with: pandas
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49793816
answer count: 1
tagged with: dataframe

http://stackoverflow.com/comment/86770938
type: Comment
type: QuestionComment
has text: I added views.post_detail code. I followed your guide and changed pk=post.pk -> post.pk however, still not working..
comment on: http://stackoverflow.com/q/49868725
score: 0

http://stackoverflow.com/comment/86634605
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49809354
has text: It might even be possible to do `isin(set(search_strings_list))` for a bit of a boost.
score: 0

http://stackoverflow.com/q/49836480
linked to: http://stackoverflow.com/q/45314416
tagged with: pyqt
has body: I have a python application that simply displays given html, with the following code: import sys from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout from PyQt5.QtWebEngineWidgets import QWebEngineView class IFace(QWidget): def __init__(self): super().__init__() self.setGeometry(300, 300, 1000, 500) self.view = WebView(self) self.setLayout(QGridLayout(self)) self.layout().addWidget(self.view, 0, 0) self.layout().setContentsMargins(0, 0, 0, 0) class WebView(QWebEngineView): def __init__(self, parent): super().__init__(parent) self.setHtml(""" Hi! Hi! Hi! """) if __name__ == '__main__': app = QApplication(sys.argv) w = IFace() w.show() sys.exit(app.exec_()) The html is displayed correctly at first, but resizing the window vertically will cause the displayed webpage to 'stretch' downwards, distorting the text: Before resizing: After resizing: Note how the the text is taller, but not wider. The text also moves downwards as the window is shrunk vertically. When I place another widget to the left of the QWebEngineView, such as a QLabel, the distortion affects the QLabel as well. If I do not include the QWebEngineView, the QLabel is not distorted. Why does this happen, and how can I fix it? Thanks. UPDATE: It appears to have something to do with the instantiation of a QWebEngineView that has the window as a parent, as the effect persists when the QWebEngineView is only created not placed, and the effect does not remain when the QWebEngineView is instantiated by QWebEngineView() without the widget as a parent.
has comment: http://stackoverflow.com/comment/86690523
answer count: 1
tagged with: pyqt5
duplicate of: http://stackoverflow.com/q/45314416
has answer: http://stackoverflow.com/a/52021607
accepted answer: http://stackoverflow.com/a/52021607
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86689696
has title: PyQt5: QWebEngineView Distortion on Resize
tagged with: qwebengineview
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/49838956
answer count: 2
tagged with: pandas
upvote count: 3
possible better answer: http://stackoverflow.com/a/49839443
downvote count: 0
linked to: http://stackoverflow.com/q/49793652
has answer: http://stackoverflow.com/a/49839443
favorite count: 0
type: Question
has body: I have two DataFrames, 'Students' DataFrame and 'Fee' DataFrame. The fee details of some of the students are missing in 'Fee' DataFrame. I would like to return the details of all students whose fee details are missing. The three fields 'Class', 'Section' and 'RollNo' form a unique combination. Students = pd.DataFrame({ 'Class': [7, 7, 8], 'Section': ['A', 'B', 'B'], 'RollNo': [2, 3, 4], 'Student': ['Ram', 'Rahim', 'Robert'] }) Fee = pd.DataFrame({ 'Class': [7, 7, 8], 'Section': ['A', 'B', 'B'], 'RollNo': [2, 2, 3], 'Fee': [10, 20, 30] }) Students Class RollNo Section Student 0 7 2 A Ram 1 7 3 B Rahim 2 8 4 B Robert Fee Class Fee RollNo Section 0 7 10 2 A 1 7 20 2 B 2 8 30 3 B Essentially, I would like to find the unmatched records from the left table when I do a left join between 'Students' and 'Fee' DataFrames based on 3 fields mentioned above. What is the simplest way to achieve this using Pandas in Python? Thank you very much!
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49839187
has answer: http://stackoverflow.com/a/49839187
has title: unmatched left table records in a left join in pandas
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/49862726
tagged with: space
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/86741646
score: 0
has body: The row is meant to be filled with enemies, however only 2 appear. What is meant to happen is that the enemies are supposed to appear at the top of the screen and fill the screen without blitting forever. However it only blits two of these enemies and the for loop doesn't add any more to the group, why? Main File Code: # main game loop def mainGame(): gameRunning = True # boolean variable to show the main game loop is running aliens = Group()# Make a group to store the aliens in # create a fleet of aliens gf.create_fleet(spaceSettings, display, ship, aliens) # main game event loop while gameRunning: # while gameRunning is true the following will continuously occur gf.checkEvents(spaceSettings, display, ship, bullets) # runs the alternate events loop in game functions ship.update() # updates the ships movement gf.updateBullets(bullets) # updates the bullets movement and display gf.updateScreen(spaceSettings, display, ship, aliens, bullets) # updating the screen with the relevant images Game Functions: from alien import Alien # importing the alien class def create_fleet(spaceSettings, display, ship, aliens): """Create a fleet of aliens.""" # Create an alien and find the number of aliens in a row. alien = Alien(spaceSettings, display) number_aliens_x = get_number_aliens_x(spaceSettings, alien.rect.width) # create the fleet of aliens for alien_number in range(number_aliens_x): create_alien(spaceSettings, display, aliens, alien_number)+ def get_number_aliens_x(spaceSettings, alien_width): """How many aliens will fit in a row.""" available_space_x = spaceSettings.displayWidth - 2 * alien_width number_aliens_x = int(available_space_x / (2 * alien_width)) return number_aliens_x def create_alien(spaceSettings, display, aliens, alien_number): """Create an alien and place it in a row.""" alien = Alien(spaceSettings, display) alien_width = alien.rect.width alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x aliens.add(alien) print(aliens)
has comment: http://stackoverflow.com/comment/86742648
tagged with: for-loop
has comment: http://stackoverflow.com/comment/86742933
has comment: http://stackoverflow.com/comment/86743148
type: UnansweredQuestion
answer count: 1
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86740763
has comment: http://stackoverflow.com/comment/86743745
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49885709
has comment: http://stackoverflow.com/comment/86765377
has comment: http://stackoverflow.com/comment/86743340
has title: Space Invaders pygame: Only 2 enemies will display in a row

http://stackoverflow.com/comment/86785357
has text: i feel that all 4 columns should be in the first statement! what are your thoughts?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49884395

http://stackoverflow.com/comment/86885419
has text: If you're able to stream documents from your cursor, you can pipe that stream to S3. I'll try to write a POC later when I have some time. There is the `ijson` library that allows to stream json
comment on: http://stackoverflow.com/q/49886530
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86809164
type: Comment
type: QuestionComment
has text: Is it possible that two paths in `some_list` have the same file name included in `presorted_list`? In that case, should they maintain their relative positions?
comment on: http://stackoverflow.com/q/49896864
score: 1

http://stackoverflow.com/comment/86584955
score: 0
comment on: http://stackoverflow.com/q/49784457
has text: Hi Andrew, the .tsv files i'm using _should_ be the same as the csv files, as the csv files were created by opening the tsv files in excel, selecting a sample of rows, and saving as csv
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/103792631
comment on: http://stackoverflow.com/q/49863742
type: Comment
has text: This link should be useful: [Link](https://medium.com/@darshildesai/user-retention-in-python-8c33fa5766b6)
type: QuestionComment
score: 0

http://stackoverflow.com/q/49761727
upvote count: 1
tagged with: python
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/49762181
type: Question
tagged with: pandas
favorite count: 0
has title: How to return max value and associated index in Pandas dataframe column
has comment: http://stackoverflow.com/comment/86539065
type: AnsweredQuestion
has body: I need to supply a tuple with the highest value from a column (yield) and the associated index value in the form (index, value) I came up with: t= (df['yield'].idxmax(),df['yield'].max()) But I'm wondering is there a nicer way to get these values (in a tuple)?
downvote count: 0
accepted answer: http://stackoverflow.com/a/49762181

http://stackoverflow.com/comment/86637758
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49809314
has text: angle-bracket representation?

http://stackoverflow.com/a/64196727
answers question: http://stackoverflow.com/q/49889524
type: Answer
score: 2
downvote count: 0
has body: Try this: conda install -c conda-forge mlxtend Don't mix pip and Conda environments. Last time I did this I broke my Python and needed to reinstall everything again. If you must deal with different environments using pip and conda because of many projects, use pyenv.
upvote count: 2

http://stackoverflow.com/q/49760249
tagged with: qtwebchannel
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49762445
has title: How to pass back value from JS to Python
accepted answer: http://stackoverflow.com/a/49762445
score: 1
tagged with: python
type: AnsweredQuestion
tagged with: pyqt
upvote count: 1
has body: I wanted to display a 2D Map with Python and then do something with the coordinates of the coursor in the Python code. I cant get the coordinates to the Python Part however. Heres my code: from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWebEngineWidgets import * from PyQt5.QtWidgets import QWidget,QVBoxLayout, QApplication from PyQt5.QtWebChannel import QWebChannel import bs4 maphtml = ''' WebGL Earth API - Side-by-side - Basic Leaflet compatibility ''' class Browser(QApplication): def __init__(self): QApplication.__init__(self, []) self.window = QWidget() self.window.setWindowTitle("Serial GPS Emulator"); self.web = QWebEngineView(self.window) self.web.setHtml(maphtml) self.layout = QVBoxLayout(self.window) self.layout.addWidget(self.web) self.window.show() self.exec() Browser() It would be good if the code would stay in one file but if its totally impossible to do it in one splitting it is acceptable. I guess the first step in solving mny Problem would be to call a function from the HTML/JS part as backend.print("test") also doesnt work. I also noticed that self.exec() Blocks the rest of the code, is there a way to execute any other code while the map is running? Thanks!
downvote count: 0
answer count: 1
tagged with: pyqt5
tagged with: javascript

http://stackoverflow.com/q/49779281
type: Question
linked to: http://stackoverflow.com/q/35020797
has answer: http://stackoverflow.com/a/49815419
accepted answer: http://stackoverflow.com/a/49815419
linked to: http://stackoverflow.com/q/49820873
tagged with: similarity
tagged with: python
linked to: http://stackoverflow.com/q/36427820
score: 8
possible better answer: http://stackoverflow.com/a/68377521
type: AnsweredQuestion
has body: Is there a string similarity measure available in Python+Sqlite, for example with the sqlite3 module? Example of use case: import sqlite3 conn = sqlite3.connect(':memory:') c = conn.cursor() c.execute('CREATE TABLE mytable (id integer, description text)') c.execute('INSERT INTO mytable VALUES (1, "hello world, guys")') c.execute('INSERT INTO mytable VALUES (2, "hello there everybody")') This query should match the row with ID 1, but not the row with ID 2: c.execute('SELECT * FROM mytable WHERE dist(description, "He lo wrold gyus") &lt; 6') How to do this in Sqlite+Python? Notes about what I've found so far: The Levenshtein distance, i.e. the minimum number of single-character edits (insertions, deletions or substitutions) required to change one word into the other, can be useful, but I'm not sure if an official implementation exists in Sqlite (I've seen a few custom implementations, like this one) The Damerau-Levenshtein is the same, except it also allows transposition between 2 adjacent characters; it is also called the Edit distance I know it's possible to define a function myself, but implementing such a distance will be non-trivial (doing natural language processing comparison super efficiently for databases is really non-trivial), that's why I wanted to see if Python / Sqlite already features such a tool Sqlite has FTS (Full Text Seach) features: FTS3, FTS4, FTS5 CREATE VIRTUAL TABLE enrondata1 USING fts3(content TEXT); /* FTS3 table */ CREATE TABLE enrondata2(content TEXT); /* Ordinary table */ SELECT count(*) FROM enrondata1 WHERE content MATCH 'linux'; /* 0.03 seconds */ SELECT count(*) FROM enrondata2 WHERE content LIKE '%linux%'; /* 22.5 seconds */ but I don't find about string comparison with such a "similarity distance", FTS's features MATCH or NEAR don't seem to have similarity measure with letters changes, etc. Moreover this answer shows that: SQLite's FTS engine is based on tokens - keywords that the search engine tries to match. A variety of tokenize…
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/68377521
tagged with: sqlite
has title: String similarity with Python + Sqlite (Levenshtein distance / edit distance)
tagged with: string-comparison
upvote count: 8
favorite count: 0

http://stackoverflow.com/a/60727926
has body: This should resolve your issue: x = context.config.userdata.get('environment')
answers question: http://stackoverflow.com/q/49884302
type: Answer
score: 0

http://stackoverflow.com/comment/86573007
comment on: http://stackoverflow.com/a/49778813
score: 0
type: Comment
has text: While the code is fine, this really seems to be creating a problem that has not been asked in the question.
type: AnswerComment

http://stackoverflow.com/a/49764022
score: 0
answers question: http://stackoverflow.com/q/49762971
has comment: http://stackoverflow.com/comment/86597641
has comment: http://stackoverflow.com/comment/86597492
type: Answer
has comment: http://stackoverflow.com/comment/86597961
has comment: http://stackoverflow.com/comment/86597948
has body: You are using the cv.fit_transform method incorrectly. As per the documentation, this method accepts an iterable of strings. You are providing the method a list of tuples. Here is an excerpt from the documentation: fit_transform(raw_documents, y=None) Parameters: raw_documents: iterable An iterable which yields either str, unicode or file objects. One way you can do this: text_train_cv = cv.fit_transform(list(zip(*train))[0])
has comment: http://stackoverflow.com/comment/86597619
has comment: http://stackoverflow.com/comment/86597480
has comment: http://stackoverflow.com/comment/86597990

http://stackoverflow.com/comment/86830220
has text: I just had a try with this (evaluated in *scratch*) and does not seem to have the desired effect. Would welcome an independent test to see if its just me, lisp is really not my thing... Thanks...
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49901874
type: Comment

http://stackoverflow.com/comment/86712266
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49843335
has text: Ok, sorry. I have now added that. Will that suffice?

http://stackoverflow.com/q/49835662
tagged with: python
tagged with: image-processing
has answer: http://stackoverflow.com/a/49836244
has body: I am looking for a straightforward way of applying automatic white balance to an image. I found some official documentation about a balanceWhite() method: cv::xphoto::WhiteBalancer Class Reference However, I have an obscure error when I try to call the function as shown in the example. image = cv2.xphoto_WhiteBalancer.balanceWhite(image) Raises: Traceback (most recent call last): File "C:\Users\Delgan\main.py", line 80, in load image = cv2.xphoto_WhiteBalancer.balanceWhite(image) TypeError: descriptor 'balanceWhite' requires a 'cv2.xphoto_WhiteBalancer' object but received a 'numpy.ndarray' If then I try to use a cv2.xphoto_WhiteBalancer object as required: balancer = cv2.xphoto_WhiteBalancer() cv2.xphoto_WhiteBalancer.balanceWhite(balancer, image) It raises: Traceback (most recent call last): File "C:\Users\Delgan\main.py", line 81, in load cv2.xphoto_WhiteBalancer.balanceWhite(balancer, image) TypeError: Incorrect type of self (must be 'xphoto_WhiteBalancer' or its derivative) Did anyone succeeded to use this feature with Python 3.6 and OpenCV 3.4? I also tried with derived classes GrayworldWB, LearningBasedWB and SimpleWB but errors are the same.
accepted answer: http://stackoverflow.com/a/49836244
score: 2
tagged with: python-3.x
upvote count: 2
answer count: 1
downvote count: 0
has title: How to use "xphoto_WhiteBalancer.balanceWhite" with Python and OpenCV?
favorite count: 0
type: Question
tagged with: opencv
type: AnsweredQuestion
tagged with: opencv3.0

http://stackoverflow.com/q/49834868
has comment: http://stackoverflow.com/comment/86684863
has body: I have this code: read = open('file.py', 'r+') intent = 0 for line in read: if '{' in line: intent += 1 #print intent, ", up" if '}' in line: #intent -= 1 print intent, ", down" if " " in line: print "tab" I want to add "\t" * intent to the beginning every line. How can I do that?
has title: Python - Add string to beginning of file in loop
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49834948
has answer: http://stackoverflow.com/a/49834943
tagged with: python
score: -1
upvote count: 0
answer count: 2
tagged with: file-io
downvote count: 1
has comment: http://stackoverflow.com/comment/86685075
favorite count: 0
type: Question

http://stackoverflow.com/comment/86710315
has text: sorry I didn't read your question properly before suggesting the dupe. I see you are using `is_integer` already.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49847677

http://stackoverflow.com/q/49875720
has answer: http://stackoverflow.com/a/49878190
downvote count: 0
has comment: http://stackoverflow.com/comment/86767500
has answer: http://stackoverflow.com/a/49875990
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49877693
has comment: http://stackoverflow.com/comment/86767057
answer count: 4
score: 8
upvote count: 8
type: Question
has title: Call __exit__ on all members of a class
tagged with: python
has comment: http://stackoverflow.com/comment/86767315
accepted answer: http://stackoverflow.com/a/49876462
has body: Is there a Pythonic way to automatically __exit__ all members of a class? class C: def __init__(self): self.a = open('foo') self.b = open('bar') def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): # Is it correct to just forward the parameters here? self.a.__exit__(self, exc_type, exc_value, traceback) self.b.__exit__(self, exc_type, exc_value, traceback) Can I do this without manually calling __exit__ on a and b? Am I even calling __exit__ correctly? Suppose that the resources I have aren't files like in the example and there isn't a method like close or destroy. Is it perhaps good practice to implement a method like this on top of the __enter__ and __exit__?
has comment: http://stackoverflow.com/comment/86767116
has answer: http://stackoverflow.com/a/49876462
linked to: http://stackoverflow.com/q/1984325
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49877693
has comment: http://stackoverflow.com/comment/86767598

http://stackoverflow.com/comment/86540457
has text: You need `tk.Tk()` to start the tkinter application. `tk.Toplevel()` is for opening new windows in general not something you would use to start the application up.
type: QuestionComment
comment on: http://stackoverflow.com/q/49762485
type: Comment
score: 0

http://stackoverflow.com/q/49912226
has body: I'm using SQLAlchemy to manage 2 databases. One is a local SQLite DB and the other is a remote MySQL DB on Google's cloud platform and they both share the same schema. I'm trying to use append the rows contained in the SQLite DB to the MySQL DB. I currently have one file that defines my class like so: SensorCollection.py class Readings(Base): __tablename__ = 'readings' time = Column(String(250), primary_key=True) box_name = Column(String(250)) FS = Column(Numeric) IS = Column(Numeric) VS = Column(Numeric) CO = Column(Numeric) TVOC = Column(Numeric) cTemp = Column(Numeric) fTemp = Column(Numeric) humidity = Column(Numeric) pressure = Column(Numeric) Then I have another file that declares my Base, Session, and engine: base.py from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///%s' % 'db/db.db') Session = sessionmaker(bind=engine) Base = declarative_base() And finally my actual code: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.schema import Table from SensorCollection import Readings from sqlalchemy.sql.expression import insert # uploads MySQL database to Google cloud server # uses ORM to ensure the databases can communicate with each other user = *** password = *** host = *** port = *** dbName = *** instanceConnectionName = *** # create the engine for the local db engineLocal = create_engine('sqlite:///%s' % 'db/db.db') BaseLocal = Readings(None, None, None, None, None, None, None, None, None, None, None) # create the engine for the Google db engineGoogle = create_engine('mysql+mysqldb://%s@%s:%s/%s?unix_socket=/cloudsql/%s' % (user, host, port, dbName, instanceConnectionName)) SessionGoogle = sessionmaker(bind=engineGoogle) BaseGoogle = Readings(None, None, None, None, None, None, None, None, None, None, None) # create the local db BaseLocal.metadata.create_all(engineLocal) # create the Google db and start…
type: Question
answer count: 2
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49912643
tagged with: google-cloud-platform
has title: How do I migrate rows from a local SQLite DB to a remote MySQL DB using SQLAlchemy?
score: 0
tagged with: sqlite
tagged with: mysql
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/49993765

http://stackoverflow.com/q/49790456
has comment: http://stackoverflow.com/comment/86596087
type: Question
tagged with: memory-management
has comment: http://stackoverflow.com/comment/86596616
answer count: 0
type: UnansweredQuestion
has body: In my python code, I try to compute the material response of a structure consisting of two different materials. After inspecting the code, I found that the following type of structure is using a lot of memory: class ClassA: # This is a class with some memory expensive properties def __init__(self, prop_a, prop_b): self.prop_a = prop_a self.prop_b = prop_b # A function def calculateC(self, ka, kb): C = ka * kb # some long, expensive calculation going on here return C class Communicator: # This is a class will need the function handles that point to calculateC def __init__(self, function1, function2): self.function1 = function1 self.function2 = function2 def splitComputeCompose(self, ka, kb, ind1, ind2): ans1 = self.function1(ka[ind1], kb[ind1]) # compute the part related to inst1 ans2 = self.function1(ka[ind2], kb[ind2]) # compute the part related to inst2 ans = [ans1, ans2] # compose the final array to return return ans def main(): part1 = ClassA(someValue1, someValue2) part2 = ClassA(someValue3, someValue4) myCommunicator = Communicator(part1.calculateC, part2.calculateC) # somehow doubles the memory usage The problem, as far as I understand it, is that passing part1.calculateC &amp; part2.calculateC to the communicator class seems to copy them. How do I avoid this? How do I merely pass the function handle, is there a way to improve the above structure?
has title: Python reduce memory usage when passing class functions
tagged with: python
tagged with: class
score: 0

http://stackoverflow.com/comment/86821223
score: 0
type: Comment
has text: Thank you very much. With your first solution it works, but it automatically calls the openfile() function immediatly on startup..?
comment on: http://stackoverflow.com/a/49902660
type: AnswerComment

http://stackoverflow.com/a/49853739
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49853649
score: 4
answers question: http://stackoverflow.com/q/49853649
type: Answer
upvote count: 4
has body: If you are using category.parent.parent, you are following the foreign key forwards two times. Therefore you can use select_related. Category.objects.filter(name__contains=something).select_related('parent__parent') prefetch_related would be useful if you were following the foreign key backwards (i.e. fetching the children of categories). You may want to look at django-mptt if you are storing a tree of categories. It may make other queries more efficient.

http://stackoverflow.com/a/49814584
type: Answer
has comment: http://stackoverflow.com/comment/86696652
answers question: http://stackoverflow.com/q/49813952
upvote count: 2
has comment: http://stackoverflow.com/comment/86646563
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86645577
accepted answer of: http://stackoverflow.com/q/49813952
has comment: http://stackoverflow.com/comment/86704256
has comment: http://stackoverflow.com/comment/86644379
has comment: http://stackoverflow.com/comment/86644554
score: 2
has comment: http://stackoverflow.com/comment/86718893
has body: You need to switch the backend from Qt4 to Tk. What you're currently doing is you open a Qt based plot window from a Tkinter based application. This work but isn't interoperable. Insert the following line somewhere at the top (not in the saveentryfunction): plt.switch_backend('TkAgg') # TkAgg (instead Qt4Agg)

http://stackoverflow.com/q/49862318
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/101685710
has answer: http://stackoverflow.com/a/49865393
tagged with: python
upvote count: 29
has comment: http://stackoverflow.com/comment/109507397
has body: How can I run mypy on all .py files in a project? I have seen I can specify a module to run mypy on but not something to specify a file mask or something like this.
type: Question
accepted answer: http://stackoverflow.com/a/49865393
answer count: 2
has title: Run mypy on all Python files of a project
downvote count: 0
possible better answer: http://stackoverflow.com/a/72543893
score: 29
has answer: http://stackoverflow.com/a/72543893
favorite count: 0
tagged with: mypy

http://stackoverflow.com/q/49826341
has title: Create new list from from a single column of existing list?
has comment: http://stackoverflow.com/comment/86668786
has body: Using Python 2.7 Existing list: Columns and same hostname multiple entries: xlist Index([u'id', u'last_checkin', u'name'], dtype='object') {'last_checkin': &lt;DateTime '20180411T14:28:18' at 7f0639d26d88&gt;, 'id': 1000017017, 'name': 'linux1v'} {'last_checkin': &lt;DateTime '20180411T17:18:30' at 7f0639d26dd0&gt;, 'id': 1000019428, 'name': 'linux1v'} {'last_checkin': &lt;DateTime '20180411T17:18:52' at 7f0639d26e18&gt;, 'id': 1000019430, 'name': 'linux1v'} {'last_checkin': &lt;DateTime '20180411T17:24:55' at 7f0639d26e60&gt;, 'id': 1000019437, 'name': 'linux1v'} {'last_checkin': &lt;DateTime '20180411T17:21:18' at 7f0639d26ea8&gt;, 'id': 1000019443, 'name': 'linux1v'} {'last_checkin': &lt;DateTime '20180411T17:30:26' at 7f0639d26ef0&gt;, 'id': 1000019453, 'name': 'linux1v'} New list: zlist for i in xlist: zhostname = i.get('name') #print zhostname if zhostname not in zlist: zlist.append(i) In 1st list there are multiple entries for the same host with a different last_checkin date and/or id. For the new list I am trying add to the list when hostname does not already exist. But the new list seems to be an exact copy of the first list. It is like it is not checking for only the hostname in the new list. I do not care about the last_checkin date or id for either entry. How does it validate the entry if I am only checking the name of the host? i.e.: [if zhostname not in zlist: zlist.append(i)] So when it looks for the hostname in zlist is it also validating the other columns and sees it is different based on the whole row? Hopefully this is not clear as mud. My goal is to have a list with no duplicate hostname entries regardless of id or last_checkin.
upvote count: 0
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/86668572
tagged with: python-2.7
tagged with: list
downvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/49826840
has comment: http://stackoverflow.com/comment/86668582
favorite count: 0
type: Question

http://stackoverflow.com/q/49837521
tagged with: python-3.x
has body: I am a Python newbies. I am struck with this quiz. It should use a while or for loop. Here is a quiz question: Assume s is a string of lower case characters. Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print Number of times bob occurs is: 2 This is my code. count = 0 string = 'bob' strings = s.find(string) for i in s: if strings != -1: count = count + 1 print(count) Thank you for your help!
tagged with: while-loop
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86690337
tagged with: python
linked to: http://stackoverflow.com/q/2970520
has comment: http://stackoverflow.com/comment/86690308
tagged with: for-loop
answer count: 0
duplicate of: http://stackoverflow.com/q/2970520
downvote count: 0
has title: Count number of times the sub string occurs in string in Python
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86690319
favorite count: 0
type: Question

http://stackoverflow.com/comment/86761089
type: Comment
type: QuestionComment
has text: Something that preserves my dataframe structure as well as possible, without resorting to pickling external files.
score: 0
comment on: http://stackoverflow.com/q/49872843

http://stackoverflow.com/comment/86811594
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49896802
has text: And many many others.
type: Comment

http://stackoverflow.com/comment/86819683
has text: ive made that change, and get the following error 'set' object does not support indexing
comment on: http://stackoverflow.com/a/49901914
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86841987
has text: it is matching 10/01/1811 also
type: Comment
comment on: http://stackoverflow.com/a/49912981
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86663274
score: 1
type: Comment
has text: You might find [ccbv](https://ccbv.co.uk/projects/Django/2.0/django.views.generic.list/ListView/) useful for exploring Django’s class based views.
comment on: http://stackoverflow.com/q/49823075
type: QuestionComment

http://stackoverflow.com/q/49802143
tagged with: python
tagged with: flask
type: AnsweredQuestion
has title: Flask - SocketIO hidden behind reverse proxy with Nginx
upvote count: 3
has body: I want to integrate Flask-SocketIO with my Flask project. My app is running behind a Nginx reverse proxy: location /plivo_api{ rewrite ^/plivo_api(.*) /$1 break; proxy_pass http://127.0.0.1:8090; } So I undestand all trafic received in the /plivo_api will be rewrited as "/" port 8090. This part work well. The problem starts when I want to connect to the socket. Direct connection to socket has no problem. # all those examples work # from localhost var socket = io.connect() var socket = io.connect('http://localhost:8090/') # running the app out of the reverse proxy var socket = io.connect('http://my_server:8090/') But throught Nginx I cannot connect # Bad Gateway var socket = io.connect('http://my_server/plivo_api') Question is Do I'm missing something to connect to my socketio app or there's something extra to add to Nginx config ? The flask app code with socketio integration looks like # this code work well, the flask app and socket io # problem must be in Ngin settings. The flask app code with socketio integration looks like from flask import Flask, render_template from flask_socketio import SocketIO, emit HOST = '127.0.0.1' PORT = 8090 app = Flask(__name__) app.config['SECRET_KEY'] = 'secret' app.config['DEBUG'] = True app.config['SERVER_NAME'] = f'{HOST}:{PORT}' socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') if __name__ == '__main__': socketio.run(app, port=PORT, host=HOST)
accepted answer: http://stackoverflow.com/a/49820399
tagged with: flask-socketio
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49820399
favorite count: 0
type: Question
score: 3
tagged with: reverse-proxy
tagged with: nginx

http://stackoverflow.com/a/49872364
has comment: http://stackoverflow.com/comment/86761142
has comment: http://stackoverflow.com/comment/86761546
upvote count: 5
accepted answer of: http://stackoverflow.com/q/49872226
type: Answer
answers question: http://stackoverflow.com/q/49872226
has comment: http://stackoverflow.com/comment/86760688
has comment: http://stackoverflow.com/comment/86760343
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/86760802
type: AcceptedAnswer
has body: Remove the trashed=false and query to get shared files is: sharedWithMe Also there is no concept of bucket in google drive Query to use: {'q': 'sharedWithMe'} EDIT I still believe trashed=false should work Work around: There must be a better way but a trick is to do the following: list_of_trash_files = drive.ListFile({'q': 'trashed=true'}) list_of_all_files = drive.ListFile({'q': ''}) final_required_list = set(list_of_all_files) - set(list_of_trash_files)
has comment: http://stackoverflow.com/comment/86760543

http://stackoverflow.com/q/49759946
score: 3
has comment: http://stackoverflow.com/comment/86537519
has comment: http://stackoverflow.com/comment/86537759
tagged with: deep-learning
upvote count: 3
has comment: http://stackoverflow.com/comment/86537310
has body: Introduction: I have trained Autoencoders (vanilla &amp; variational) in KERAS for MNIST images, and have observed how good the latent representation in the bottleneck layer looks for clustering them together. Objective: I want to do the same for short texts. Tweets specifically! I want to cluster them together based on their semantics using pre-trained GloVe embeddings. What I am planning to do is create a CNN encoder and a CNN decoder as a start, before moving on to LSTMs/GRUs. Problem: ~~~What should be the correct loss? How do I implement it in Keras?~~~ This is how my KERAS model looks like INPUT_TWEET (Word indexes) >> EMBEDDING LAYER >> CNN_ENCODER >> BOTTLENECK >> CNN_DECODER >> OUTPUT_TWEET (Word indexes) Layer (type) Output Shape Param # ----------------------------------------------------------------- Input_Layer (InputLayer) (None, 64) 0 embedding_1 (Embedding) (None, 64, 200) 3299400 enc_DO_0_layer (Dropout) (None, 64, 200) 0 enc_C_1 (Conv1D) (None, 64, 16) 9616 enc_MP_1 (MaxPooling1D) (None, 32, 16) 0 enc_C_2 (Conv1D) (None, 32, 8) 392 enc_MP_2 (MaxPooling1D) (None, 16, 8) 0 enc_C_3 (Conv1D) (None, 16, 8) 200 enc_MP_3 (MaxPooling1D) (None, 8, 8) 0 ***bottleneck (Flatten)*** (None, 64) 0 reshape_2 (Reshape) (None, 8, 8) 0 dec_C_1 (Conv1D) (None, 8, 8) 200 dec_UpS_1 (UpSampling1D) (None, 16, 8) 0 dec_C_2 (Conv1D) (None, 16, 8) 200 dec_UpS_2 (UpSampling1D) (None, 32, 8) 0 dec_C_3 (Conv1D) (None, 32, 16) 400 dec_UpS_3 (UpSampling1D) (None, 64, 16) 0 conv1d_2 (Conv1D) (None, 64, 200) 9800 dense_2 (Dense) (None, 64, 1) 201 flatten_2 (Flatten) (None, 64) 0 ----------------------------------------------------------------- This is clearly wrong because it tries to minimize the MSE loss between the Input and the Output (word indexes), where I think it should do it in the embedding layers (embedding_1 and conv1d_2). Now how do I do it? Does it make sense? Is there a way to do this in Keras? Please check my code below: The code: sequence_input = Input(shape=(MAX_S…
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86537449
tagged with: nlp
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86537091
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86537517
has title: Regarding Text Autoencoders in KERAS for topic modeling
has comment: http://stackoverflow.com/comment/86537414
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86537290
has comment: http://stackoverflow.com/comment/86536984
has comment: http://stackoverflow.com/comment/86536921
has comment: http://stackoverflow.com/comment/86536860
tagged with: python
tagged with: keras
has comment: http://stackoverflow.com/comment/86537190
linked to: http://stackoverflow.com/q/47735205
has answer: http://stackoverflow.com/a/49761586
has comment: http://stackoverflow.com/comment/86537291
has comment: http://stackoverflow.com/comment/86536298
has comment: http://stackoverflow.com/comment/86537314

http://stackoverflow.com/a/49882706
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49882324
has body: You can using stack with groupby df.stack().astype(str).groupby(level=1).apply(','.join) Out[738]: loc.1 1,2,3,4,7,5,6 loc.2 3,4,3,7,7,8,6 loc.3 1,4,3,1,7,8,6 dtype: object
upvote count: 1
score: 1

http://stackoverflow.com/q/49903991
has comment: http://stackoverflow.com/comment/86824032
answer count: 1
tagged with: class
has body: I'd like to do something like this: Robot.GyroController.getLatestMeasurement() Is there a way to do this? More specifically I wanted to do this: robot = Robot.__init__(arguments) latesMeasurement = robot.GyroController.getLatestMeasurement() Is this valid python? And most importantly, is it possible to do so? I need to do a LEGO competition. I can use whatever programming language that I want to and so I figured I'd write a library to get slightly better abstraction over the existent one (also to practice python as I want to get into tensorflow) I have a class called robot. This class is initialized with references to all the motors/sensors the robot has. From there, I want some subclasses (or maybe something else?) that can control motors, sensors, and do some other fancy stuff. Instead of passing robot (that contains references to motors/sensors) every time I use motors/sensors, I figured that I could do something like this. PS. I am coming from OOP, and still learning python, so please, it is my intention to improve the question as best as I can. Please give me a chance.
has comment: http://stackoverflow.com/comment/86823867
has comment: http://stackoverflow.com/comment/86823952
accepted answer: http://stackoverflow.com/a/49904426
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49904426
tagged with: python-3.x
has title: Having mulitple classes inside a class python3?
type: Question
has comment: http://stackoverflow.com/comment/86824025
tagged with: python

http://stackoverflow.com/q/49826797
has answer: http://stackoverflow.com/a/49826857
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/86669345
has comment: http://stackoverflow.com/comment/86669279
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49826859
has comment: http://stackoverflow.com/comment/86669315
tagged with: django
has answer: http://stackoverflow.com/a/49826844
has comment: http://stackoverflow.com/comment/86669326
favorite count: 0
has comment: http://stackoverflow.com/comment/86669208
has title: Remove every character before the website name in a URL
answer count: 3
linked to: http://stackoverflow.com/q/286150
has body: For example if I have https://stackoverflow.com/questions/ask I'd like to cut it to stackoverflow.com/questions/ask or if I have http://www.samsung.com/au/ I'd like to cut it to samsung.com/au/. I want to make a template tag for this but not sure what to return: def clean_url(url): return ? template Any idea?
downvote count: 3
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86669228

http://stackoverflow.com/comment/89415795
type: Comment
comment on: http://stackoverflow.com/a/50419127
score: 0
type: AnswerComment
has text: @Oleksandr Even though you are using TuriCreate instead of Pandas the code in app's should still work.

http://stackoverflow.com/comment/86542099
has text: @Joylove Glad to help!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49761129
type: Comment

collada
type: Tag
tag name: collada
tags question: http://stackoverflow.com/q/49872672

http://stackoverflow.com/comment/86690648
type: QuestionComment
has text: Knowing your goal is important to know. `tkinter` has special classes called "Variables" (see [The Variable Classes (`BooleanVar`, `DoubleVar`, `IntVar` `StringVar`)](http://effbot.org/tkinterbook/variable.htm)) that make what you want to do easy and avoids global variables. Also see [Control variables: the values behind the widgets](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/control-variables.html) for more details.
comment on: http://stackoverflow.com/q/49837453
score: 1
type: Comment

http://stackoverflow.com/q/49842115
has body: I want to sum the divisors of a large list of numbers, and to do so, I used a prime numbers generator : def sieve_of_eratosthenes(limit): # Initialize the primality list a = [False] * 2 + [True] * (limit-2) for (i, isprime) in enumerate(a): if isprime: yield i # Mark factors non-prime for n in range(i*i, limit, i): a[n] = False Since what I want to do is something like: for n in numbers_list: s = 0 for p in sieve_of_eratosthenes(limit): if not x % p: s += p I wonder would it be better just to create a generator once, and then turn it into a list, resulting in a large object I create only once, or keep creating the generator in each iteration (since I'll need to start from the beginning each time). Are generators supposed to be used like this, or are lists the right solution, or maybe this is just a simple trade-off of memory / run-time?
tagged with: generator
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49843200
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/49843200
has answer: http://stackoverflow.com/a/49842255
type: Question
has title: Is it better to use generator or list when I need to go back to the start often?
possible better answer: http://stackoverflow.com/a/49842255
tagged with: python

http://stackoverflow.com/comment/86541499
type: AnswerComment
has text: @Wen I reckon your second solution is actually going to be far slower. The second `apply` is fine given that you're unlikely to have many modes.
comment on: http://stackoverflow.com/a/49762821
type: Comment
score: 0

http://stackoverflow.com/q/49820878
has body: i have the following excel (xlsx) file with informations like: files val_1 val_2 val_3 val_4 1 file_1 545.0 475.20822 116 43.0 2 file_2 179.0 19.791214 17 39.0 3 file_3 600.0 450.54407 302 92.0 4 file_4 1936.0 397.71826 182 271.0 i want to parse this file and then e.g. draw a boxplot by column "val_1" and then save the boxplot into the same excel file but on e.g. worksheet : sheet 2 is there a way to do this just with pandas without matplotlib ? or is matplotlib mandatory?
has title: pandas parsing excel file creating boxplot and store it in excel file again
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49830538
accepted answer: http://stackoverflow.com/a/49830538
upvote count: 1
tagged with: python
tagged with: excel
favorite count: 0
possible better answer: http://stackoverflow.com/a/49821097
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49821097
downvote count: 0
tagged with: pandas
score: 1
tagged with: boxplot

http://stackoverflow.com/comment/86745844
type: Comment
has text: Sorry just one more question Maxim - how does Keras know to return the existing tensor list to `moments` and not a new list of zero tensors, if a name is not specified? Any resource you could point me to would be appreciated.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49862339

http://stackoverflow.com/comment/99363224
comment on: http://stackoverflow.com/a/56357526
type: AnswerComment
has text: Ah ok, then it is a general issue with metrics in TensorFlow. Thank you for referencing this nice article, which answers my question. Maybe, you can include this reference to your answer? Then I can accept it.
score: 0
type: Comment

http://stackoverflow.com/comment/86704079
comment on: http://stackoverflow.com/q/49843069
score: 0
type: QuestionComment
has text: i have updated the question with screenshot of shell.when i run the code the web cam will turn on but it won't display any tkinter window. @ArtemisFowl
type: Comment

http://stackoverflow.com/q/49885517
has comment: http://stackoverflow.com/comment/86787578
type: Question
has answer: http://stackoverflow.com/a/49885604
has comment: http://stackoverflow.com/comment/86787849
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49885627
has comment: http://stackoverflow.com/comment/86787185
tagged with: python
has body: Nothing scares me more than the Python Class concept; and recently I have been trying to use/create classes to understand their purpose, structure and features, etc. However, I am not clear about the concept of class and how to create them. Please take a look at the following example: class Prob(object): def __init__ (self,filename): self.file_contents = read_file(filename) def prob_build(self): self.problem, self.aux_vars = build_problem(file_contents) first_object = Prob(some_file) alpha,beta, gamma = first_object.prob_build() In this case, read_file, build_problem are custom functions that read data from a CSV file and build a PuLP-based linear problem, respectively. Now, my understanding is that when I initialize an object based on my Prob class, the file_contents are available for the class to use internally. In that case, how do I get the variables alpha, beta and gamma? For the current code, I get a TypeError: 'NoneType' object is not iterable. I have tested the functions and I know that they work without any error, which leaves me thinking that there is something wrong with the way I have defined the class. Any suggestions?
has comment: http://stackoverflow.com/comment/86787228
answer count: 4
has comment: http://stackoverflow.com/comment/86787655
score: 0
has title: Developing with Python Class
has answer: http://stackoverflow.com/a/49886335
has answer: http://stackoverflow.com/a/49885661

http://stackoverflow.com/comment/86630458
has text: The fitted line is not shown in the plot because it has a linewidth of 0. The lines you see are from your first plot. The answer tells you how to get rid of those. To iterate over the columns of an array you may indeed iterate of the length of one row of it.
type: Comment
comment on: http://stackoverflow.com/a/49807191
score: 0
type: AnswerComment

http://stackoverflow.com/q/49793232
score: 0
has answer: http://stackoverflow.com/a/49810120
answer count: 1
has body: I am developing a GUI using pyqt4 where it has a lineEdit and browse button. So the user can either browse or enter the path. When the user starts typing, how do I give suggestions for the same folder starting with this letter something like in windows file explorer? Is there any module in pyqt4 to do that?
has title: How to give suggestions when typing the first letter of a folder in lineEdit leads to the folders starting with this letter in pyQt4?
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pyqt4
tagged with: python
has comment: http://stackoverflow.com/comment/86634757
has comment: http://stackoverflow.com/comment/86617673

http://stackoverflow.com/comment/86707826
score: 0
type: AnswerComment
has text: np.allclose() = true. Thanks, this was both strange/unexpected, but after doing some reading on floating point, it makes sense why this happens!
type: Comment
comment on: http://stackoverflow.com/a/49840222

pycharm
tags question: http://stackoverflow.com/q/49837339
tags question: http://stackoverflow.com/q/49832176
tags question: http://stackoverflow.com/q/49777023
tags question: http://stackoverflow.com/q/49859151
tags question: http://stackoverflow.com/q/49838532
tags question: http://stackoverflow.com/q/49787551
tags question: http://stackoverflow.com/q/49792127
tags question: http://stackoverflow.com/q/49847076
tags question: http://stackoverflow.com/q/49812802
tags question: http://stackoverflow.com/q/49883378
tags question: http://stackoverflow.com/q/49888883
tag name: pycharm
tags question: http://stackoverflow.com/q/49844189
tags question: http://stackoverflow.com/q/49820583
tags question: http://stackoverflow.com/q/49829319
tags question: http://stackoverflow.com/q/49882078
type: Tag
tags question: http://stackoverflow.com/q/49902483
tags question: http://stackoverflow.com/q/49814187
tags question: http://stackoverflow.com/q/49777474
tags question: http://stackoverflow.com/q/49852552
tags question: http://stackoverflow.com/q/49806573
tags question: http://stackoverflow.com/q/49818994
tags question: http://stackoverflow.com/q/49764199
tags question: http://stackoverflow.com/q/49800112
tags question: http://stackoverflow.com/q/49849475
tags question: http://stackoverflow.com/q/49828755
tags question: http://stackoverflow.com/q/49789383

http://stackoverflow.com/q/49781127
favorite count: 0
type: Question
has title: how to make vertical lines touch the boundaries of the chart?
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/49781361
accepted answer: http://stackoverflow.com/a/49781361
score: 3
tagged with: pandas
tagged with: matplotlib
tagged with: python
has body: I would like the vertical lines I create with ax.vlines to touch the upper and lower bounds of my chart, in the same manner as axvline does. Consider this simple example: import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'time' : [pd.to_datetime('2016-01-02'), pd.to_datetime('2016-01-03'), pd.to_datetime('2016-01-04')], 'value1' : [1, 2, 3], 'value2' : [10, 20, 30]}) df.set_index('time', inplace = True) df Out[95]: value1 value2 time 2016-01-02 1 10 2016-01-03 2 20 2016-01-04 3 30 Now the chart is: fig, ax = plt.subplots(figsize=(30, 15)) ax.plot(df.index, df["value1"], color = 'black') ax2 = ax.twinx() ax2.plot(df.index, df["value2"], color = 'red') #axvline stretches nicely ax.axvline( pd.to_datetime('2016-01-04'), color = 'red', alpha = 1, linestyle = '--') #vlines stops before touching the upper and lower boundaries ymin, ymax = ax2.get_ylim() ax.vlines([pd.to_datetime('2016-01-02'), pd.to_datetime('2016-01-03')], ymin = ymin, ymax = ymax, color = 'blue', linestyle = '-') gives : You can see those blue lines remain in the air, while the nice red vertical line stretches completely. How can I achieve that? Thanks!
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49786000
possible better answer: http://stackoverflow.com/a/49786000

http://stackoverflow.com/a/49764275
type: Answer
accepted answer of: http://stackoverflow.com/q/49764248
score: 0
type: AcceptedAnswer
has body: The reason the code has no affect is because you modify the value of x, a local variable to the function scope, and not the player position. Call player.setx(x) to actually update the player position after updating the local variable x. If you want to bound your positions you could also use the built in min/max methods: def move_left(): x = player.xcor() x -= playerspeed player.setx(max(x, -280)) def move_right(): x = player.xcor() x += playerspeed player.setx(min(x, 280))
answers question: http://stackoverflow.com/q/49764248

http://stackoverflow.com/q/49843097
tagged with: numpy
type: Question
has comment: http://stackoverflow.com/comment/86700852
has comment: http://stackoverflow.com/comment/86701471
has comment: http://stackoverflow.com/comment/86703141
has body: I have an numpy ndarray, shape is (R,1). I wonder if I firstly store it into a .txt file, and then load out. But in this process, total line number decrease for 1. Codes I use: #!/usr/bin/python #!/usr/bin/env python import numpy as np from numpy import loadtxt dictkey=dict.keys() Xarr=np.array(dictkey).reshape(-1,1) print Xarr.shape np.savetxt('filepath/file.txt', Xarr, fmt='%s') f = open("step_2/Part_DBS/S3_DBs/GO_For_SVM.txt") f.readline() # skip the header X = np.loadtxt(f) print X.shape In print Xarr.shape, row number is 15431, and in print X.shape, row number becomes to 15430. How it comes? And I wonder if the row order will change, I hope it totally unchanged. Ps: if I just use np.savetxt('filepath/file.txt', Xarr) There will be error TypeError: Mismatch between array dtype ('|S28218') and format specifier ('%.18e') My python version is Python 2.7.13
type: UnansweredQuestion
tagged with: python
has title: Row number change while save numpy ndarray in to text or read from .txt file
score: 0
answer count: 0

http://stackoverflow.com/comment/86752327
score: 0
type: AnswerComment
has text: Sorry a naive question, though. What would be the Python 3.3 equivalent of dst_filename = f'./csv/file_{str(index)}.csv'?
comment on: http://stackoverflow.com/a/49868041
type: Comment

http://stackoverflow.com/a/49834494
has comment: http://stackoverflow.com/comment/86704596
has comment: http://stackoverflow.com/comment/86704303
score: 3
has comment: http://stackoverflow.com/comment/86705311
upvote count: 3
has comment: http://stackoverflow.com/comment/86705098
has comment: http://stackoverflow.com/comment/86702250
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49834241
downvote count: 0
has comment: http://stackoverflow.com/comment/86704962
answers question: http://stackoverflow.com/q/49834241
has comment: http://stackoverflow.com/comment/86704797
has comment: http://stackoverflow.com/comment/86705015
has comment: http://stackoverflow.com/comment/86704452
type: Answer
has body: After entering 538707 on this URL, the page redirects to this URL. The tables and other data on this page are loaded from AJAX requests. You can directly get data from these requests for scraping. To see the AJAX requests, go the XHR tab under the Network tab in Developer tools and refresh the page. You can get data from the XHR requests you see here. For example, the table Securitywise Delivery Position is loaded from this URL. So, you can directly get the table like this: import requests r = requests.get('https://www.bseindia.com/stock-share-price/SiteCache/SecurityPosition.aspx?Type=EQ&amp;text=538707') soup = BeautifulSoup(r.text, 'lxml') table = soup.find('table') Scrape this table using BeautifulSoup. For example: print(table.find('td', class_='newseoscripfig').text) # 13 Apr 2018 Similarly, you can find nearly all the data that is loaded dynamically in other XHR requests. As Selenium is not used here, the script is pretty fast.
has comment: http://stackoverflow.com/comment/86704935

http://stackoverflow.com/q/49777982
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49778066
tagged with: python
has body: I'm trying to reorganize my DataFrame in a certain way that creates new rows based on repeated index values. import pandas as pd values = [800.0, 400.0, 200.0, 100.0, 50.0, 25.0, 12.5, 0.0, 800.0, 400.0, 200.0, 100.0, 50.0, 25.0, 12.5, 0.0] things = [3.0621, 1.5309, 0.75, 0.4001, 0.1978, 0.1031, 0.0509, 0.0031, 2.9066, 1.5859999999999999, 0.7945,0.3938, 0.2156, 0.1063, 0.0519, 0.0019] tester = pd.DataFrame(data=things, index=values) tester.columns = ['things'] tester.index.name = 'values' In [3]: tester Out[3]: things values 800.0 3.0621 400.0 1.5309 200.0 0.7500 100.0 0.4001 50.0 0.1978 25.0 0.1031 12.5 0.0509 0.0 0.0031 800.0 2.9066 400.0 1.5860 200.0 0.7945 100.0 0.3938 50.0 0.2156 25.0 0.1063 12.5 0.0519 0.0 0.0019 I'd like re-design this as such: thing1 thing2 values 800.0 3.0621 2.9066 400.0 1.5309 1.5860 200.0 0.7500 0.7945 100.0 0.4001 0.3938 50.0 0.1978 0.2156 25.0 0.1031 0.1063 12.5 0.0509 0.0519 0.0 0.0031 0.0019 There's got to be some simple way to do this. Should I not be setting values as an index perhaps? Apologies if this is a duplicate, I'd been searching for a while but couldn't find anything that specifically covers this.
accepted answer: http://stackoverflow.com/a/49778066
type: AnsweredQuestion
has title: Re-organizing Pandas DataFrame into more columns based on unique/repeated index values
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/53825697
answers question: http://stackoverflow.com/q/49915328
upvote count: 2
score: 2
downvote count: 0
has body: Because there is no error, the directory exists and there are still no files created in your specified directory, it is possible that the code runs and creates the files but in a different directory. What is your file_path keyword set to when you create a connection? File backend The file backend writes emails to a file. A new file is created for each new session that is opened on this backend. The directory to which the files are written is either taken from the EMAIL_FILE_PATH setting or from the file_path keyword when creating a connection with get_connection(). To specify this backend, put the following in your settings: EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_PATH = '/tmp/app-messages' # change this to a proper location Django Docs File Backend
type: Answer

http://stackoverflow.com/comment/86732331
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49857570
type: Comment
has text: Channels first or last is an option that doesn't change results. It's about your preference and about how your data is organized. If you change this option, make sure to permute or swap the axes of your data as well. I asked because I was confused about your 4D data.

http://stackoverflow.com/q/49767083
has title: How to get multiple records in one DNS query
tagged with: sockets
tagged with: python
has answer: http://stackoverflow.com/a/49767336
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49767487
score: 0
accepted answer: http://stackoverflow.com/a/49767487
answer count: 2
has body: This simple code snippet using dnspython the code resolves the name to IP. In this example, the domain is google.com and the answer for A record. How can I get multiple records (e.g. TXT, CNAME, ..) in one query? from dns.resolver import dns myResolver = dns.resolver.Resolver() #create a new instance named 'myResolver' myAnswers = myResolver.query("google.com", "A") #Lookup the 'A' record(s) for google.com for rdata in myAnswers: #for each response print (rdata) #print the data
possible better answer: http://stackoverflow.com/a/49767336
tagged with: dns
type: Question
tagged with: dnspython

http://stackoverflow.com/a/55503949
downvote count: 0
has body: I had the same problem. Use df['Tata'].map(int)
score: 6
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/49836620

http://stackoverflow.com/a/49802083
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/86619257
has body: You are so close: @staticmethod def add_member(): # belongs to the class print() print("Welcome to the team!") print() first_name = input("What's your first name?\n") second_name = input("What's your surname?\n") address = input("Where do you live?\n") # get the maximum id and add one if Team.members: unique_id = max(Team.members, key=lambda m: m.user_id) + 1 else: unique_id = 0 Team(unique_id , first_name, second_name, address) And in the main function change on call: elif choice == 2: Team.add_member()
has comment: http://stackoverflow.com/comment/86619081
answers question: http://stackoverflow.com/q/49801901
has comment: http://stackoverflow.com/comment/86619328

http://stackoverflow.com/comment/86580823
type: QuestionComment
has text: Each of the 100 result consists of a set of different elements e.g. div, img, anchor, text, etc. What exactly do you want to copy and where do you want to copy?
comment on: http://stackoverflow.com/q/49782514
type: Comment
score: 0

http://stackoverflow.com/q/49896643
upvote count: 1
has comment: http://stackoverflow.com/comment/86859034
has title: boost python errors raised on following step by step guidance from boost python
favorite count: 0
has comment: http://stackoverflow.com/comment/86808803
type: Question
has body: I am struggling to figure this out and getting a large volume of boost errors when trying to convert my c++ class "Car" into a python module Code from Car.h #ifndef Carproj_CAR_H #define Carproj_CAR_H #include &lt;string&gt; class Car { public: Car(std::string &amp; name, int &amp; speed); void drive(); void increaseSpeed(); private: std::string m_name; int m_speed; }; Code from Car.cpp #include "Car.h" #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;boost/python.hpp&gt; using namespace boost::python; Car::Car(std::string &amp; name, int &amp; speed) { m_name = name; m_speed = speed; } void Car::drive() { std::cout &lt;&lt; "Driving" &lt;&lt; std::endl; } void Car::increaseSpeed() { m_speed+=30; } BOOST_PYTHON_MODULE(Car) { class_&lt;Car&gt;("Car",init&lt;std::string, int&gt;()) .def("drive",&amp;Car::drive).def("increaseSpeed",&amp;Car::increaseSpeed); } Errors receiving - whole message :) In file included from /usr/include/boost/preprocessor/iteration/detail/iter/forward1.hpp:57:0, from /usr/include/boost/python/object/value_holder.hpp:50, from /usr/include/boost/python/object/class_metadata.hpp:11, from /usr/include/boost/python/class.hpp:23, from /usr/include/boost/python.hpp:18, from /home/damian/CLionProjects/Carproj/Car.cpp:8: /usr/include/boost/python/object/value_holder.hpp: In instantiation of ‘boost::python::objects::value_holder&lt;Value&gt;::value_holder(PyObject*, A0, A1) [with A0 = boost::python::objects::reference_to_value&lt;std::__cxx11::basic_string&lt;char&gt; &gt;; A1 = int; Value = Car; PyObject = _object]’: /usr/include/boost/python/object/make_holder.hpp:94:17: required from ‘static void boost::python::objects::make_holder&lt;2&gt;::apply&lt;Holder, ArgList&gt;::execute(PyObject*, boost::python::objects::make_holder&lt;2&gt;::apply&lt;Holder, ArgList&gt;::t0, boost::python::objects::make_holder&lt;2&gt;::apply&lt;Holder, ArgList&gt;::t1) [with Holder = boost::python::objects::value_holder&lt;Car&gt;; ArgList = boost::mpl::vecto…
has comment: http://stackoverflow.com/comment/86854733
has answer: http://stackoverflow.com/a/49902274
type: UnansweredQuestion
tagged with: python
tagged with: c++
has comment: http://stackoverflow.com/comment/86815497
score: 1
tagged with: boost
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/86686910
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49835647
has text: I tried it before posting the issue. I've spent about ~3h to investigate how it's _actually_ works

http://stackoverflow.com/comment/86608005
has text: The second part of your answer worked for me. I will look forward with your recommendation. Thanks.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49796708
type: Comment

http://stackoverflow.com/q/49811533
upvote count: 1
has comment: http://stackoverflow.com/comment/86638636
favorite count: 0
type: Question
tagged with: gbm
tagged with: prediction
has title: Checking Accuracy of GradientBoostingClassifier when predicting class probabilities
has comment: http://stackoverflow.com/comment/86643198
tagged with: python
has body: While working with GradientBoostingClassifiers, I'm trying to obtain the probability of the classes the model has predicted for which i use the "predict_proba(X)" method. But I would like to know how to check the accuracy of this prediction. P = np.array(D1.drop(['Class'], axis = 1)) q = np.array(D1['Class']) P_train, P_test, q_train, q_test = train_test_split(P, q) qst = GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.08, loss='deviance', max_depth=None, max_features=None, max_leaf_nodes=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=400, presort='auto', random_state=None, subsample=0.8, verbose=0, warm_start=False).fit(P_train, q_train) The total dataset is of (17520x24) - 24 features including the "Class" Feature The above code has 3 classes pred_prob_P_test = qst.predict_proba(P_test) This gives the percentage probability of the target belonging to each Class I would like to check the accuracy of this predicted probability.
accepted answer: http://stackoverflow.com/a/49819199
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49819199
score: 1
tagged with: classification
answer count: 1
downvote count: 0
tagged with: machine-learning

http://stackoverflow.com/q/49829210
tagged with: django
has comment: http://stackoverflow.com/comment/86674162
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86674086
has answer: http://stackoverflow.com/a/49829421
tagged with: python
has body: I am trying to get an input to appear on my page, and have been following Max Goodridge's walkthrough ep.45, but seem to have gotten myself stuck on this particular section. If anyone could assist this would be a massive help. My urls.py: url(r'^bandlist/$', polls_views.bandlist, name='bandlist'), url(r'^bandlist/(\d+)/$', polls_views.BandView.as_view(), name='bandview'), My views.py def bandlist(request): query = Band.objects.order_by('bandname') args = {'query': query} return render(request, 'bandlist.html', args) class BandView(TemplateView): template_name = 'bandview.html' def get(self, request): form = BandForm() return render(request, self.template_name, {'form': form}) My forms.py class BandForm(forms.Form): post = forms.CharField() And the template (band.html) {% extends 'bbase.html' %} {% block content %} {{ band.bandname }} Total Ratings: {{ band.totalrating }} How many times have {{band.bandname}} been rated: {{ band.totalrated }} Average rating (Out of 5): {{ form.as_p }} {% endblock %} After this, I will then be attempting to implement a rating and review system for each band. If anyone could give advice on that as well that would be very much appreciated. EDIT: Here is the full traceback: Internal Server Error: /bandlist/1/ Traceback (most recent call last): File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\views\generic\b…
has title: TypeError: get() takes 2 positional arguments but 3 were given
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/86673956
downvote count: 0

http://stackoverflow.com/q/49861102
type: Question
accepted answer: http://stackoverflow.com/a/49862301
has comment: http://stackoverflow.com/comment/86737430
possible better answer: http://stackoverflow.com/a/49861206
has answer: http://stackoverflow.com/a/49862301
tagged with: python-3.x
has title: PIP and python -m pip doesnt work when I specify the version
type: AnsweredQuestion
answer count: 2
downvote count: 0
tagged with: pip
upvote count: 1
tagged with: python
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86739202
has answer: http://stackoverflow.com/a/49861206
has body: I have got a problem when I want to install a specific version of a python library since I updated pip to 10.0.0. I would like to install it back but I cant find it, so I am forced to use the whole command , but it doesnt let me to install specific version of python package, any idea how to do it ? C:\Windows\system32&gt;python -m pip install APScheduler==3.0.0 Collecting APScheduler==3.0.0 C:\Windows\system32&gt;python -m pip install pip APScheduler==3.0.0 Requirement already satisfied: pip in c:\program files (x86)\python36-32\lib\site-packages (10.0.0) Collecting APScheduler==3.0.0 C:\Windows\system32&gt;python -m pip install APScheduler==3.0.0 Collecting APScheduler==3.0.0 C:\Windows\system32&gt;python -m pip install pymongo Collecting pymongo Downloading https://files.pythonhosted.org/packages/c2/96/00951e252c6cad023b3fd60457b2ab1c1329073516086c7ac1b6833a439e/pymongo-3.6.1-cp36-cp36m-win32.whl (286kB) 100% |████████████████████████████████| 286kB 1.3MB/s Installing collected packages: pymongo Successfully installed pymongo-3.6.1 also this is the part of a pip error I am dealing with , so any help would be awesome ^.^ ( Tried few things from stack overflow but neighter of them worked ) C:\Windows\system32&gt;pip install APScheduler==3.0.0 Fatal error in launcher: Unable to create process using '""c:\program files (x86)\python36-32\python.exe" "C:\Program Files (x86)\Python36-32\Scripts\pip.exe" install APScheduler==3.0.0'

http://stackoverflow.com/a/58797722
type: Answer
has body: The error message is giving the clue here: dot.exe is missing in the path (C:/Anaconda/Library/bin). Complementing @Ioannis answer, you have to install GraphViz executables (via conda) for getting the dot.exe in your path. For my case, after installing GraphViz (conda install GraphViz) I tried with the latest pydot (pip install pydot) and the error was resolved.
answers question: http://stackoverflow.com/q/49771377
score: 0

http://stackoverflow.com/q/49900685
has title: Undo "Install Certificates.command"
has body: In Python 3.6+ on Mac, various SSL-related operations will fail (typically with a cryptic SSL: CERTIFICATE_VERIFY_FAILED error) until you run /Applications/Python\ 3.6/Install\ Certificates.command to install root certificates. After encountering such an error, I Googled, eventually discovered this solution (which is noted at, e.g. https://bugs.python.org/issue29065#msg283984), did it, and it worked. But now I'd like to tweak my code to catch the error I was seeing before and show a helpful error message explaining to the user that they need to run /Applications/Python\ 3.6/Install\ Certificates.command. I can't easily test this error-handling code, though, since, having run the command, I no longer get the SSL error that I want to catch. How can I uninstall the certificates that were installed by Install Certificates.command in order to perform such testing?
answer count: 1
favorite count: 0
type: Question
score: 9
upvote count: 13
tagged with: python
has answer: http://stackoverflow.com/a/50428300
accepted answer: http://stackoverflow.com/a/50428300
tagged with: macos
downvote count: 4
tagged with: openssl
type: AnsweredQuestion

http://stackoverflow.com/comment/86666965
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49825444
has text: @TemporalWolf `def f(): return 1, 2 print(type(f()))` prints `<class 'tuple'>`

http://stackoverflow.com/q/49798116
has comment: http://stackoverflow.com/comment/86611401
answer count: 1
favorite count: 0
type: Question
has body: I am developing website for simple question and answer forum. I want to get upvotes for an answer. models.py class Answer(models.Model): ans = models.TextField() img = models.CharField(max_length=100) created_by = models.ForeignKey(User, related_name='answer') created_on = models.DateTimeField(auto_now_add=True) ques = models.ForeignKey(Question, related_name='answer') def __str__(self): return self.ans class Upvote(models.Model): upvote = models.BooleanField(default=False) upvote_by = models.ForeignKey(User, related_name='upvote') upvoted_on = models.DateTimeField(auto_now_add=True) #ques = models.ForeignKey(Question, related_name='upvote') ans = models.ForeignKey(Answer, related_name='upvote') def __str__(self): return self.upvote_by views.py I can get upvotes for an answer like below answer = get_object_or_404(Answer, pk=1) upvotes = Upvote.objects.filter(ans=answer) How to take upvotes from answer object ? Is it possible please correct me if i am wrong. Something like below, answer.upvote_set Thanks in advance !!
has answer: http://stackoverflow.com/a/49799863
tagged with: django
accepted answer: http://stackoverflow.com/a/49799863
tagged with: python
has comment: http://stackoverflow.com/comment/86610836
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has title: How to take upvotes for the answer in Django?

http://stackoverflow.com/a/49802056
upvote count: 1
has comment: http://stackoverflow.com/comment/86618861
downvote count: 0
score: 1
type: Answer
has body: &gt;&gt;&gt; a = 10**32 &gt;&gt;&gt; a/1000/1000 9.999999999999999e+25 As you know, Python 3 division is no longer an integer division (a//1000//1000 would have worked fine), so you're performing 2 floating point divisions here, introducing an (unnecessary) floating point accumulation error. &gt;&gt;&gt; a/1000000 1e+26 this only performs one division, so lower floating point error effect, even if result is now floating point.
answers question: http://stackoverflow.com/q/49801931

http://stackoverflow.com/q/49794432
type: Question
has answer: http://stackoverflow.com/a/49800061
tagged with: pipenv
has body: My Ubuntu 16.04.03 is installed with Python 3.5.2. How do I setup pipenv to use Python 3.6 when my system does not have python 3.6? $ pipenv --python 3.6 Warning: Python 3.6 was not found on your system… You can specify specific versions of Python with: $ pipenv --python path/to/python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49799971
score: 73
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/49799742
has answer: http://stackoverflow.com/a/70121350
has title: How to setup a pipenv Python 3.6 project if OS Python version is 3.5?
upvote count: 73
downvote count: 0
has answer: http://stackoverflow.com/a/53734041
possible better answer: http://stackoverflow.com/a/55151969
accepted answer: http://stackoverflow.com/a/49800061
has answer: http://stackoverflow.com/a/55151969
favorite count: 0

http://stackoverflow.com/a/49760528
has body: for line in fisier: iterates over lines in file without removing line endings (usually the line return) so: print(line) will print the line and an empty line so it's better to write: with open('catastrofa.txt') as fisier: for line in fisier: if text in line: print(line, end='') to avoid extra line returns.
answers question: http://stackoverflow.com/q/49760172
type: Answer
score: 0

http://stackoverflow.com/q/49834062
has answer: http://stackoverflow.com/a/49847373
possible better answer: http://stackoverflow.com/a/49847373
has comment: http://stackoverflow.com/comment/86709969
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 0
tagged with: coreml
answer count: 3
has comment: http://stackoverflow.com/comment/86687002
downvote count: 1
tagged with: turi-create
has comment: http://stackoverflow.com/comment/86695021
has answer: http://stackoverflow.com/a/49852268
accepted answer: http://stackoverflow.com/a/49852268
favorite count: 0
type: Question
has body: During the guide I followed from I have an error: CoreMD using Python Need to create a simple dataset following the guide. The only difference between guide is made by me: data["personalityType"] = data["path"].apply( lambda path: "Enfj" if "enfj" in path else lambda path: "Enfp" if "enfp" in path else lambda path: "Entj" if "entj" in path else lambda path: "Entp" if "entp" in path else lambda path: "Esfj" if "esfj" in path else lambda path: "Esfp" if "esfp" in path else lambda path: "Estj" if "estj" in path else lambda path: "Estp" if "estp" in path else lambda path: "Infj" if "Infj" in path else lambda path: "Infp" if "infp" in path else lambda path: "Intj" if "intj" in path else lambda path: "Intp" if "intp" in path else lambda path: "Isfj" if "isfj" in path else lambda path: "Isfp" if "isfp" in path else lambda path: "Istj" if "istj" in path else "Istp") instead of: data["foodType"] = data["path"].apply(lambda path: "Rice" if "rice" The error log in Terminal: python classifier.py Traceback (most recent call last): File "classifier.py", line 20, in data.save("ptype.sframe") File "/usr/local/lib/python2.7/site-packages/turicreate/data_structures/sframe.py", line 2808, in save raise ValueError("Unsupported format: {}".format(format)) File "/usr/local/lib/python2.7/site-packages/turicreate/cython/context.py", line 49, in exit raise exc_type(exc_value) RuntimeError: Exception in python callback function evaluation: TypeError("Cannot convert type 'function' into flexible type.",): Traceback (most recent call last): File "turicreate/cython/cy_pylambda_workers.pyx", line 427, in turicreate.cython.cy_pylambda_workers._eval_lambda File "turicreate/cython/cy_pylambda_workers.pyx", line 172, in turicreate.cython.cy_pylambda_workers.lambda_evaluator.eval_simple File "turicreate/cython/cy_flexible_type.pyx", line 1306, in turicreate.cython.cy_flexible_type.process_common_typed_list File "turicreate/cython/cy_flexible_type.pyx", line 1251, in turicreate.cython.cy_flexible_type…
has answer: http://stackoverflow.com/a/50419127
linked to: http://stackoverflow.com/q/50452760
has comment: http://stackoverflow.com/comment/86694650
has title: Python 2.7 several conditions for lambda? Elif?
linked to: http://stackoverflow.com/q/51182760
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86715861

http://stackoverflow.com/a/49837242
type: AcceptedAnswer
score: 2
accepted answer of: http://stackoverflow.com/q/49837206
downvote count: 0
has comment: http://stackoverflow.com/comment/86689928
type: Answer
answers question: http://stackoverflow.com/q/49837206
upvote count: 2
has body: You could use a list comprehension here: def pig_latin(sentence): return ' '.join([s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay' for s in sentence.split()]) print(pig_latin("convert all the words")) Output: onvertcay allay hetay ordsway You could also keep your current approach where the function converts a single word, and use map(): &gt;&gt;&gt; def pig_latin_word(s): ... return s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay' ... &gt;&gt;&gt; ' '.join(map(pig_latin_word, "convert all the words".split())) 'onvertcay allay hetay ordsway' &gt;&gt;&gt;

http://stackoverflow.com/q/49818868
accepted answer: http://stackoverflow.com/a/49819037
tagged with: python
has answer: http://stackoverflow.com/a/49819037
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/86652527
has comment: http://stackoverflow.com/comment/86652690
tagged with: list
has comment: http://stackoverflow.com/comment/86652783
upvote count: 2
type: AnsweredQuestion
score: 0
downvote count: 2
has body: My list comprehension returns the error "List index out of range" if the value does not exist in the list. Objective: Check a three-letter code for a country given by a variable (country) and transform the code into a two-letter code by looking up a list of tuples (COUNTRIES) Constant: # Two letter code, three letter code, full name COUNTRIES = [ ('US', 'USA', 'United States'), ('DE', 'DEU', 'Germany'), .... ] Code: country = 'EUR' # Check if code in country has 3 characters (I have multiple checks for two letter codes too) and is not None if len(country) == 3 and country is not None: country = [code2 for code2, code3, name in COUNTRIES if code3 == country][0] If I only include a list with three letter codes USA and DEU, the code works fine. If I add the fictitious code "EUR", which is not a valid country code in the variable "country", than I get the List index out of range error. How can I return None instead of breaking the program? The variable country will be used later on again.
answer count: 1
favorite count: 0
tagged with: tuples
has title: Python list comprehension: list index out of range
type: Question

http://stackoverflow.com/comment/86627881
comment on: http://stackoverflow.com/q/49806456
has text: Could you explain a bit more why you can't simply do `swap = func2` `func2 = lambda x: func1(x) + swap(x)`?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86685490
score: 0
type: AnswerComment
has text: acc1, etc... should never have existed. `accounts = [ bank('0', '0', '0', '0'), bank('0', '0', '0', '0') ]` but notice you already have a bug: you aren't using unique account numbers.
comment on: http://stackoverflow.com/a/49834525
type: Comment

http://stackoverflow.com/q/49854145
favorite count: 0
has title: Even numbers generator in python
has comment: http://stackoverflow.com/comment/86722802
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49866297
type: Question
has answer: http://stackoverflow.com/a/49854202
downvote count: 3
has comment: http://stackoverflow.com/comment/86722925
answer count: 5
score: -2
has answer: http://stackoverflow.com/a/49854429
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49854477
possible better answer: http://stackoverflow.com/a/49854243
has answer: http://stackoverflow.com/a/49854243
has body: written a small code to generate even numbers. &gt;&gt;&gt;even = [] &gt;&gt;&gt;[even for x in range(15) if x % 2 == 0] output is - [(), (), (), (), (), (), ()] Can the above code generate even numbers if so what is the fix ? How can i have a block of code instead of if statement in above line, my goal is to generate prime numbers. [prime for x in range(2,15) for y in range(1,int(x/2)) if (x%y) != 0 ..................]
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86724008
accepted answer: http://stackoverflow.com/a/49854429

http://stackoverflow.com/a/49859894
has body: Check this for example: v1 = 1, v2 = (1,) type(v1) # outputs &lt;type 'tuple'&gt; type(v2) # outputs &lt;type 'tuple'&gt; Comma makes a tuple from the expression while the parentheses are just optional.
answers question: http://stackoverflow.com/q/49859755
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86830842
type: Comment
type: QuestionComment
has text: @abarnert what do you mean by unique? It's not possible to create a duplicate key in a python dictionary, to my knowledge.
score: 0
comment on: http://stackoverflow.com/q/49907090

http://stackoverflow.com/a/49891061
score: 1
upvote count: 1
has body: atlantic = atlantic.to_xarray() Seems that it's unnecessary to call xr.open_dataset().
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49890750

http://stackoverflow.com/q/49849589
tagged with: tuples
tagged with: python
has answer: http://stackoverflow.com/a/49849629
duplicate of: http://stackoverflow.com/q/8966538
has body: Can someone explain that the importance of lambda in this format of sorting tuples? Further, what exactly does each element of this sorting method mean? sorted(authorlist, key = lambda tup: tup[0], reverse = True) I know that reverse = True allows for the list of tuples to be sorted in decending order, the tup[0] indicates what index you want to sort by, and that the first parameter is the tuple/list, but what does key = lambda mean and why is tuple referred to as tup? Thanks!
has comment: http://stackoverflow.com/comment/86713777
has title: Python Tuple Sorting Syntactical Meaning (Purpose of lambda)
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/8966538
answer count: 1
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86713759
tagged with: lambda
favorite count: 0
type: Question

http://stackoverflow.com/q/49871030
has title: How to fetch the latest records using find_one in pymongo?
accepted answer: http://stackoverflow.com/a/49871423
tagged with: python
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/75551971
has body: I have an existing program where I'm trying to fetch last inserted document which matches the key aws_account_id using find_one in pymongo. I'm using this query to perform the fetching: report = securitydb.scout.find_one({'aws_account_id': aws_account.account_number}) But this query returns a wrong document. The image below demonstrates the expected result and the wrong one that I'm getting. In the image, both documents have the same aws_account_id but the red one is inserted last. So the expected result is the red marked document but it pulls the yellow marked document. I'm not sure if I need to use sorting or things like that. I got some solution but those are based on pure mongo query. I need help doing this with pymongo. Thanks In Advance, Robin
has answer: http://stackoverflow.com/a/49871423
tagged with: pymongo
downvote count: 0
score: 16
upvote count: 16
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/75551971
tagged with: mongodb

http://stackoverflow.com/a/50985982
type: Answer
answers question: http://stackoverflow.com/q/49835342
accepted answer of: http://stackoverflow.com/q/49835342
downvote count: 4
has body: This works without any problems.
type: AcceptedAnswer
upvote count: 1
score: -3

http://stackoverflow.com/a/49812775
has body: In regards to your second question, I don't believe it is possible to do what you want without using new unless you are ok with making it a function like fferri describes. What you can do is this if you want to maintain the class structure. Class Field(object): def __init___(self): pass def __new__(cls, filename): if '.grb' in fileName: return FieldGrib(fileName) if '.nc' in fileName: return FieldnetCDF(fileName) else: raise valueError('File format not supported') class FieldGrib(Object_To_Inherit_From) def __init__(self, fileName): super().__init__(fileName) self.fileName = fileName ...etc. EDIT: If you want to maintain functions from the base class you can change the inherited class on the FieldGrib class and the FieldnetCDF class as those are what is returned from the factory class. EDIT 2: You cannot inherit from the factory class because when you call super it will run new again, entering a recursive loop. The factory class is simply that, a factory. It should not inherit from anything. It simply dictates which class to return. FieldGrib and FieldGrib should inherit from the class that contains the functionality you want, not from Field. If field is only ever used to create other things you can create a private Field class called class _Field(object): that contains the functionality you want and can be inherited from. It shouldn't be called directly though. This would turn FieldGrab into class FieldGrib(_Field):
upvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49812559
downvote count: 1
answers question: http://stackoverflow.com/q/49812559
type: Answer
score: -1

http://stackoverflow.com/q/49861600
has answer: http://stackoverflow.com/a/49861711
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
tagged with: function
tagged with: python
score: -1
has body: I'm sorry for my bad English. I get an error when I try to get() the Entry named entry from outside the class. Error: AttributeError: 'function' object has no attribute 'entry' "" Example Code: class asd: def gui(self, guiwindow, labelplacex, labelplacey, textx, texty, entryx, entryy): self.root = tk self.image = tk.PhotoImage(file=aimage_path) self.label = tk.Label(image=self.image) self.label.pack() self.label.place(x=labelplacex , y=labelplacey) self.text = Label(guiawindow, text="Code:") self.text.pack() self.text.place(x = textx,y = texty) self.entry = Entry(guiwindow) self.entry.pack() self.entry.place(x = entryx,y = entryy) self.button = Button(Tk(), text="Back Menu", command=self.asdfg) self.button.pack() self.root.mainloop() asd.gui.entry.get() How to do this??
answer count: 2
has title: Why am I getting this class tkinter.Entry.get() AttributeError error?
upvote count: 0
tagged with: user-interface
has answer: http://stackoverflow.com/a/49861742
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49843818
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49843631
answers question: http://stackoverflow.com/q/49843631
downvote count: 0
type: AcceptedAnswer
has body: I Fixed it...I used re_path instead of path and it worked like a charm.. re_path('(?P&lt;pk&gt;\d+)/',views.School_Dview.as_view(),name='detail')

http://stackoverflow.com/comment/86558978
type: Comment
has text: can you post your models and your views? And your traceback as well please
type: QuestionComment
comment on: http://stackoverflow.com/q/49771998
score: 0

http://stackoverflow.com/comment/86834598
comment on: http://stackoverflow.com/q/49905149
score: 0
type: Comment
type: QuestionComment
has text: PNGs are *always* compressed; it's part of their specifications. (Assuming you don't mean "compression method: store" – this, technically, is still a form of 'zlib compatible compression', not "uncompressed".) I assume you mean something like "downsampling"?

http://stackoverflow.com/a/49801008
has body: There are several examples of data web applications created using Bokeh at demo.bokeh.org. Here is one modeled after the "Shiny Movie Explorer", but written in pure Python/Bokeh (instead of R/Shiny). You can find much more details about creating and deploying Bokeh applications in the Running a Bokeh Server chapter of the docs. Here is a complete (but simpler) example that demonstrates the basic gist and structure: import numpy as np from bokeh.io import curdoc from bokeh.layouts import column from bokeh.models import ColumnDataSource, Slider from bokeh.plotting import figure # Set up data x = np.linspace(0, 4*np.pi, 200) y = np.sin(x) source = ColumnDataSource(data=dict(x=x, y=y)) # Set up plot plot = figure(title="my sine wave") plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) # Set up widgets freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1, step=0.1) # Set up callbacks def update_data(attrname, old, new): # Get the current slider values and set new data k = freq.value x = np.linspace(0, 4*np.pi, 200) y = np.sin(k*x) source.data = dict(x=x, y=y) freq.on_change('value', update_data) # Set up layouts and add to document curdoc().add_root(column(freq, plot)) curdoc().title = "Sliders" To run this locally you'd execute: bokeh serve --show myscript.py For more sophisticated deployments (i.e. with proxies) or to embed directly in e.g. Flask, see the docs.
downvote count: 1
upvote count: 5
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49800444

http://stackoverflow.com/comment/86555175
score: 0
type: AnswerComment
has text: Thanks for the clarification.
type: Comment
comment on: http://stackoverflow.com/a/49768876

http://stackoverflow.com/q/49821100
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86658205
accepted answer: http://stackoverflow.com/a/49821524
tagged with: if-statement
has answer: http://stackoverflow.com/a/49821524
has title: Reading YAML files and accessing lists
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86658030
type: Question
tagged with: python-3.x
has body: I am currently reading data from a .yml file. Inside the file is the following part for every main entry: - ! name: Martial Focus prerequisites: tier1: any: Attribute: - Attribute1:§ 1 - Attribute2:§ 1 Feat: - Feat1 Other: - Other Prerequisites cost: - 3 description: | [...] effect: | [...] I've been able to read all the data, including 'prerequisites', but here I have a special problem: Where with the other data, I was able to access sublists it seems to be different for this: The "any:" part is optional, so it could also say something like prerequisites: tier1: Attribute: - Attribute1:§ 1 - Attribute2:§ 1 Feat: - Feat1 Other: - Other Prerequisites Reading the .yml file converts the part above to 'prerequisites': { 'tier1': { 'any': { 'Attribute': ['Attribute1:§ 1', 'Attribute2:§ 1'], 'Feat': ['Feat1'], 'Other': ['Other Prerequisites'] } } } So in my code, for every "tierX", I check if it contains a key "any:" via if 'any' in tier: # do the stuff to be done if 'any' exists else: # do the stuff to be done if it doesn't But it never seems to be true. Since "Attribute:", "Feat:" and "Other:" are also optional, I do the same for those inside the if-else-statement and it's the same problem with them though for those there's no else-statement. Below you can find the code I'm using. It won't be the prettiest since I litterally started with python today but I hope that you'll help me anyway: prerequisites = "" tierNum = 0 for tier in data['prerequisites']: tierNum += 1 thisTier = "" if 'any' in tier: print("'any' found!") content = tier['any'] if 'Other' in content: other = "" for s2 in content['Other'][:-1]: other += s2 + ", " thisTier += "**" + other if len(content['Other'][:-1]) == 0: thisTier += str(content['Other'][-1:]) else: thisTier += "or " + str(content['Other'][-1:]) if 'Attribute' in content: attributes = "" for s2 in content['Attribute'][:-1]: attributes += s2 + ", " if thisTier.length() == 0: thisTier += "**" + attributes else: thisTier += ", or " + attribute…
tagged with: yaml
answer count: 1
downvote count: 0
upvote count: 1
tagged with: key

http://stackoverflow.com/comment/86670201
has text: What's wrong with this code? And, if you want us to debug it, the code seems nice and short and complete, but it's still not a [mcve] without sample input and desired output.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49827331

http://stackoverflow.com/q/49873518
score: 0
has body: I am new to django.I want upload the csv file,process the data and render the results it on UI.For that I have created the following code. The problem is csv file is not uploading. If I'm uploaded other file format it not showing any error message. Also I want to print csv data the results on UI. views.py from django.shortcuts import render from django.conf import settings from django.http import HttpResponseRedirect from django.contrib import messages import csv from django.core.urlresolvers import reverse import logging def upload_csv(request): data = {} if "GET" == request.method: return render(request, "myapp/upload_csv.html", data) # if not GET, then proceed try: csv_file = request.FILES["csv_file"] if not csv_file.name.endswith('.csv'): c=messages.error(request,'File is not CSV type') return HttpResponseRedirect(reverse("myapp:upload_csv",{"c":c})) #if file is too large, return if csv_file.multiple_chunks(): messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),)) return HttpResponseRedirect(reverse("myapp:upload_csv")) file_data = csv_file.read().decode("utf-8") lines = file_data.split("\n") #loop over the lines and save them in db. If error , store as string and then display for line in lines: fields = line.split(",") data_dict = {} data_dict["GSTIN/UIN"] = fields[0] data_dict["start_date_time"] = fields[1] data_dict["end_date_time"] = fields[2] data_dict["notes"] = fields[3] try: form = EventsForm(data_dict) if form.is_valid(): form.save() else: logging.getLogger("error_logger").error(form.errors.as_json()) except Exception as e: logging.getLogger("error_logger").error(repr(e)) pass except Exception as e: logging.getLogger("error_logger").error("Unable to upload file. "+repr(e)) messages.error(request,"Unable to upload file. "+repr(e)) #return HttpResponseRedirect(reverse("myapp:index",data_dict)) return HttpResponseRedirect("myapp/upload_csv.html") html {% csrf_token %} File: Upload {% if c %} {{c}} {% endif %} Also help…
type: UnansweredQuestion
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/49873781
type: Question
has title: csv file is not printing in django webpage
has comment: http://stackoverflow.com/comment/86762746
tagged with: python

http://stackoverflow.com/comment/86833483
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49908726
has text: @Andersson 's answer is better
type: Comment

http://stackoverflow.com/comment/86837075
comment on: http://stackoverflow.com/q/49889421
score: 0
has text: Nothing quick comes to mind. Maybe you can try printing the outputs of each layer starting from the input image all the way to final output and see where the it becomes the same. Alternatively, it would help if you could reduce the code size/complexity that still reproduces it. Maybe somebody can spot the issue.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49871107
has comment: http://stackoverflow.com/comment/86757718
tagged with: python
tagged with: global
has body: I'm currently working on a tkinter project. The code is shown below: import tkinter as tk from tkinter import font as tkfont background_colour = "#F0F0F0" class Application(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title("CCNA Command Learner") self.geometry("500x500") self.iconbitmap("favicon.ico") container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (IntroPage, MainPage): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame("IntroPage") def show_frame(self, page_name): frame = self.frames[page_name] frame.tkraise() class IntroPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.image = tk.PhotoImage(file="IntroImage.gif") self.head_img = tk.Label(self, image=self.image, background=background_colour) self.head_img.pack() self.label = tk.Label(self, bg=background_colour, text="\nLearn essential commands for the CCNA exam\n\nPlease enter your name") self.label.pack() self.head_entry = tk.Entry(self) self.head_entry.pack() self.submit = tk.Button(self, text="Submit", command=self.submit_button) self.submit.pack() def submit_button(self): global var_username self.controller.show_frame("MainPage") var_username = self.head_entry.get() class MainPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.introduction = tk.Label(self, text="Hello" + var_username) self.introduction.pack() if __name__ == "__main__": app = Application() app.mainloop() My problem is that in the submit_button method of my IntroPage class, I am trying to set a global variable so that my MainPage class can then access it. However, despite declaring it and setting it, I am still gettin…
has title: Python - Global not working as expected
has comment: http://stackoverflow.com/comment/86757590
tagged with: python-3.x
answer count: 2
tagged with: tkinter
has answer: http://stackoverflow.com/a/49871253
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86757467
has answer: http://stackoverflow.com/a/49871355
has comment: http://stackoverflow.com/comment/86757631
type: Question
tagged with: class
score: 0

http://stackoverflow.com/a/49906334
accepted answer of: http://stackoverflow.com/q/49906237
has comment: http://stackoverflow.com/comment/129067395
score: 84
answers question: http://stackoverflow.com/q/49906237
has body: See: find_element_by_* commands are deprecated in selenium In newer versions of selenium try: from selenium.webdriver.common.by import By browser.find_element(By.XPATH, '//button[text()="Outliers"]') older versions of selenium: browser.find_element_by_xpath('//button[text()="Outliers"]') To update ALL of the older versions I found a nifty regex here, and then just fixup the import: https://stackoverflow.com/a/70586710/2026508
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 84

asynchronous
tags question: http://stackoverflow.com/q/49770609
tags question: http://stackoverflow.com/q/49827169
tags question: http://stackoverflow.com/q/49855087
tags question: http://stackoverflow.com/q/49758189
tags question: http://stackoverflow.com/q/49869769
type: Tag
tags question: http://stackoverflow.com/q/49852825
tag name: asynchronous
tags question: http://stackoverflow.com/q/49908972
tags question: http://stackoverflow.com/q/49910152

http://stackoverflow.com/q/49899373
tagged with: django-unittest
tagged with: mocking
answer count: 0
has title: Mock Django ModelChoiceField's database call
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: django-models
has body: I'd like to test a form without the tests hitting the database. The form references a Model using a ModelChoiceField which in turn runs a query during form.is_valid() that tries to fetch the referenced object from the database. This happens in related_object_field.to_python() which tries to get the object from the default manager's QuerySet. I tried patching my model's queryset.get() but to no avail: @patch('myapp.models.MyModel._default_manager.get_queryset') def test_form(mocked_get_queryset): assert mocked_get_queryset.called # &lt;-- this assertion fails [...] form = MyForm(data=my_data) assert form.is_valid() This is a snippet of the traceback which shows why the database is hit and what I'd like to have mocked: form.is_valid() django/forms/forms.py:179: in is_valid return self.is_bound and not self.errors django/forms/forms.py:174: in errors self.full_clean() django/forms/forms.py:376: in full_clean self._clean_fields() django/forms/forms.py:394: in _clean_fields value = field.clean(value) django/forms/fields.py:148: in clean value = self.to_python(value) django/forms/models.py:1245: in to_python value = self.queryset.get(**{key: value}) [...] E Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I guess that I'm not patching the right place. Can you give me any hints on how to mock the database call?
tagged with: python
score: 2

http://stackoverflow.com/q/49851375
has comment: http://stackoverflow.com/comment/86717871
has comment: http://stackoverflow.com/comment/86717391
favorite count: 0
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/11867359
has comment: http://stackoverflow.com/comment/86717928
has comment: http://stackoverflow.com/comment/86738696
type: UnansweredQuestion
tagged with: python
score: -1
has body: Just a simple code below: import numpy as np x=np.array([1,2]) y=[1,2] L=1 def set_L(x,y,L): x[0]+=1 y[0]+=1 L+=1 print(id(x)) print(id(y)) print(id(L)) I found that array x and list y is the same in the function set_L(), does this mean by default list and array are global variables? however variable L is not global in the function set_L(). I am confusing that why Python is designed like this?
has title: list and array is global by default in python3.6?
linked to: http://stackoverflow.com/q/20771487
tagged with: list
has answer: http://stackoverflow.com/a/49851444
upvote count: 0
answer count: 1
tagged with: arrays
duplicate of: http://stackoverflow.com/q/20771487
tagged with: global-variables
downvote count: 1

http://stackoverflow.com/q/49888485
tagged with: multiprocessing
type: Question
has answer: http://stackoverflow.com/a/49901842
type: UnansweredQuestion
tagged with: python
has body: A code of mine does from pathos.multiprocessing import ProcessingPool def myFunc(something): thispool = ProcessingPool(nodes=Result.cores) listOfResults = thispool.map(something) return listOfResults for i in range(1000): myFunc(i) Now, in my actual more involved code, memory usage just kept growing. The code should take nothing, but if I run it with 12 cores, these 12 cores will initially take almost 1mb memory, but over the runtime of several hours, each of which will take several GB. So, I thought that pool would leak memory, and that I better close it after each iteration: def myFunc(something): thispool = ProcessingPool(nodes=Result.cores) listOfResults = thispool.map(something) thispool.close() thispool.join() return listOfResults However, now, after several iterations, I get ValueError: Pool not running at the this pool.map() line. If I create a new test = ProcessingPool(nodes=4) and try to run test.map(), I get the same error. Which is weird, I have initialized a new variable... does pathos.processing.ProcessingPool have the feature of a unique process pool, and if I close one, I close all? What's the correct way of implementing a pathos.multiprocessing.ProcessingPool inside a loop, without memory leakage? When I instead use multiprocessing.Pool, the problem does not arise.
has title: Pathos.multiprocessing's Pool appears to be nonlocal?
score: 3
upvote count: 3
downvote count: 0
tagged with: pathos
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/86673956
type: QuestionComment
comment on: http://stackoverflow.com/q/49829210
has text: It is obvious that `as_view()` got argument supplied more than expected. If you call `detail` but accidentally route to `list`. Exception like this will be raised.
score: 0
type: Comment

http://stackoverflow.com/q/49761330
score: 3
answer count: 0
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Using Flask-User with app factory and blueprints
tagged with: python
tagged with: flask
has body: I am working on my first bigger Flask App and having a few hang-ups with my project structure. My App has the usual models.py, routes.py and forms.py. In the base folder I have my_app.py which imports create_app from app. I organized routes.py and forms.py inside a blueprint and register that blueprint in create_app() inside __init__.py. As I have multiple roles, I am using Flask-User and need a UserManager object. To instanciate it, I need the app, db and user. Because routes.py is a blueprint which is registered with the app I tried to instanciate Usermanager with the blueprint. Gets me a Type Error. Where do I instanciate the UserManager, where I also have the User model or how do I get my instance of app inside a module? EDIT: I have found that there is current_user for my problem stated above. Another hickup I have is in forms.py. I am generating one form with data from the db. When I do the Questions.query.all() I get a RuntimeError: No application found. Either work inside a view function or push an application context. What am I doing wrong there? I even get that error inside the create_all() function when I try from app import models db.create_all() . ├── app │ ├── __init__.py │ ├── main │ │ ├── __init__.py │ │ ├── forms.py │ │ └── routes.py │ ├── models.py │ └── templates │ ├── admin │ │ └── index.html │ ├── base.html │ ├── index.html ├── config.py ├── my_app.py init.py from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_user import UserManager from flask_babelex import Babel db = SQLAlchemy() login = LoginManager() def create_app(): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) login.init_app(app) from app.main import bp as main_bp app.register_blueprint(main_bp) from app import models # Setup Flask-User and specify the User data-model user_manager = UserManager(app, db, models.User) routes.py from flask import render_template from app.main.forms …

http://stackoverflow.com/q/49837155
tagged with: python
tagged with: cython
has comment: http://stackoverflow.com/comment/86891225
tagged with: module
has comment: http://stackoverflow.com/comment/86699614
has comment: http://stackoverflow.com/comment/86698997
has answer: http://stackoverflow.com/a/49944572
has comment: http://stackoverflow.com/comment/86891271
has comment: http://stackoverflow.com/comment/86895985
accepted answer: http://stackoverflow.com/a/49944572
tagged with: import
type: Question
has comment: http://stackoverflow.com/comment/86697090
has title: Spyder does not recognise cython modules when importing in a script
has body: I have got a cython script example1.pyx with various functions. I am trying to use one of these functions in my python script. To do this I am simply trying to import the function from the cython module as follows: from example1 import myfunction1 I am using Spyder to run my python script. When I run it I get the following error ModuleNotFoundError: No module named 'example1' for some reason, .pyx extension scripts are not recognised as modules that can be imported. I can successfully import other python scripts, but no luck with cython .pyx scripts. Turns out I wasnot compiling the python script. So I did so using the following script: from setuptools import setup, Extension import numpy from Cython.Distutils import build_ext as _build_ext list_pyx = ['cydtw', 'cygak', 'cycc', 'soft_dtw_fast'] ext = [Extension( '%s' % s, ['%s.pyx' % s], include_dirs=[numpy.get_include()] ) for s in list_pyx] setup( include_dirs=[numpy.get_include()], ext_modules=ext, cmdclass={'build_ext': _build_ext}, ) when I ran this, I got the error saying I need Visual C++ 14.0 compiler. Looking at documentation in https://wiki.python.org/moin/WindowsCompilers, Visual Studio 15 which I have installed already should have Visual C++ 14.0 so that was confusing. So I updated my setuptools. Got rid of that error, but turns out I it cant find a file path C;\program files\Microsoft SDKs\Windows\v8.1\lib. which I can see it doesn't. So that's where I am stuck now. Any clues?
has comment: http://stackoverflow.com/comment/86719944
has comment: http://stackoverflow.com/comment/86699299
has comment: http://stackoverflow.com/comment/86698452
has comment: http://stackoverflow.com/comment/86891491
has comment: http://stackoverflow.com/comment/86699447
type: AnsweredQuestion
score: 0
tagged with: spyder
has comment: http://stackoverflow.com/comment/86891991
answer count: 1

http://stackoverflow.com/q/49770819
type: Question
has answer: http://stackoverflow.com/a/49770932
tagged with: python
has answer: http://stackoverflow.com/a/49770912
has body: I have a seemingly simple problem, but I the code that I believe should solve it is not behaving as expected -- but a less elegant code that I find functionally equivalent behaves as expected. Can you help me understand? The task: create a list, drop a specific value. The specific usecase is that I am dropping a specific list of columns of pd.df, but that is not the part I want to focus on. It's that I seem to be unable to do it in a nice, pythonic single-line operation. What I think should work: result = list(df.columns).remove(x) This results in object of type 'NoneType' However, the following works fine: result = list(df.columns) result.remove(X) These look functionally equivalent to me -- but the top approach is clearer and preferred, but it does not work. Why?
type: AnsweredQuestion
tagged with: list
answer count: 3
upvote count: 2
possible better answer: http://stackoverflow.com/a/49770870
score: 2
accepted answer: http://stackoverflow.com/a/49770912
downvote count: 0
has title: Pythonic way not working with list
has answer: http://stackoverflow.com/a/49770870
favorite count: 0

http://stackoverflow.com/q/49790598
tagged with: email
answer count: 1
has comment: http://stackoverflow.com/comment/86597550
type: Question
has title: Reference for code in given string
has comment: http://stackoverflow.com/comment/86597783
has answer: http://stackoverflow.com/a/49791536
accepted answer: http://stackoverflow.com/a/49791536
has comment: http://stackoverflow.com/comment/86597120
has comment: http://stackoverflow.com/comment/86597829
tagged with: python
has comment: http://stackoverflow.com/comment/86597940
has comment: http://stackoverflow.com/comment/86596963
type: AnsweredQuestion
has body: I'm running an automated messaging service that sends HTML and plain-text e-mails. The script that I'm using will receive 3 parameters. To, subject and a string that contains 4 different types of data. The problem is, I can't figure out how to reference these four values seperately. I've done a couple of attempts with sys.argv[3], which should display these given arguments. The question I have is, how do I get Python to recognize these as 4 different values, instead of one string? Because I to reference them in the e-mails I've written, which are written into the code itself. #!/usr/bin/env python list1=[0,1,2,3,4]; import mimetypes, os, smtplib, sys, untangle from email import encoders from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formatdate from email.utils import make_msgid me = "xx@yy.nl" you = "yyy@xx.nl" DESTINATION=sys.argv[1] SUBJECT=sys.argv[2] MESSAGE=sys.argv[3] PASS='yyyxxxyyy' SRVSMTP='mysmtpsever:587' msg = MIMEMultipart('alternative') msg['Subject'] = SUBJECT msg['From'] = me msg['To'] = you msg['Date'] = formatdate() msg['Message-ID'] = make_msgid() text = """ email with references here """ html = """ html email with references here """ part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) smtpserver = smtplib.SMTP(SRVSMTP) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo() smtpserver.login(me, PASS) smtpserver.sendmail(me, you, msg.as_string()) smtpserver.quit() The string the monitoring system pastes is in BASH. What I had in mind is something the lines of XML's working, like this. {HOST.NAME} {TRIGGER.NAME} {TRIGGER.STATUS} {TRIGGER.SEVERITY} I feel like I'm thinking into the right direction, but I can't wrap my head around this. Any advice is appreciated.
has comment: http://stackoverflow.com/comment/86597486
score: 0
tagged with: bash

http://stackoverflow.com/comment/86635311
has text: @wwii Im not sure about indexing in isin. I tried the code you have given but got the following error.SystemError: <built-in method view of numpy.ndarray object at 0x000001A7F47CFF30> returned a result with an error set
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49809354
score: 0

http://stackoverflow.com/comment/86580389
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49781866
type: Comment
has text: It's to construct a new Tensor as described above. I'm looking for an appropriate way to for-loop the Tensor `indices` and `values`,

http://stackoverflow.com/comment/86830388
score: 1
type: Comment
has text: Your code was very useful and I used it. In addition, I updated the `~ /.pypirc` file. [link](https://github.com/pypa/pypi-legacy/issues/590#issuecomment-316972088)
comment on: http://stackoverflow.com/a/49890646
type: AnswerComment

http://stackoverflow.com/a/49795846
upvote count: 2
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/49794347
type: Answer
has body: So what is happening here is that the continuous requests to your check_valid_session view are refreshing the cookie's age to 10 seconds from the last request as it should. The cookie will only expire when it has been in your case 10 seconds since the last request. Because you have to make a request to get the cookies expiry this will return some value close to 10 every time. As for the problem of saving the users data with a cookie if their session has expired. How will you know what user is making the request if there is no session data? The only thing you could do that i can think of is to somehow save their post data with their associated ip address. Although this is definitely over complicating the problem and would not be good from a security point of view as it would be possible for other users to see this post data if they made a request with the same ip. The simplest solution to this is to just increase the timeout for the session. 10 seconds is incredibly short, the default value for SESSION_COOKIE_AGE is 1209600 (2 weeks, in seconds)

http://stackoverflow.com/a/51016922
answers question: http://stackoverflow.com/q/49916196
upvote count: 8
type: Answer
score: 8
downvote count: 0
has body: i find a way to solve the problem myself: pip_model = cv_model.bestModel pip_model.write().overwrite().save("/Users/fushuai/PyCharmProject/CTREstimation/model")

http://stackoverflow.com/comment/86770456
type: Comment
comment on: http://stackoverflow.com/q/49877354
type: QuestionComment
score: 0
has text: `LoginRequiredMiddleware`? if you're using classes you can just use the `LoginRequiredMixin` or `PermissionRequiredMixin`. I don't know why you're in need of your own class?

http://stackoverflow.com/a/77062161
upvote count: 1
has body: The same thing happen to me with one environment, and just adding ./ to the begining of the path solved it. So in your case it would be ./venv-test/Scripts/activate instead of venv-test/Scripts/activate
has comment: http://stackoverflow.com/comment/137289746
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49799331
downvote count: 0

http://stackoverflow.com/comment/86782724
type: Comment
type: QuestionComment
has text: @Shubashree you seem to ignore that most classifiers, including decision trees, actually produce a probability output, which is subsequently converted to a "hard" class membership (0/1) according to a threshold...
comment on: http://stackoverflow.com/q/49878985
score: 2

http://stackoverflow.com/q/49860491
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49860682
score: 0
has comment: http://stackoverflow.com/comment/86736095
answer count: 1
has comment: http://stackoverflow.com/comment/86736268
tagged with: http
type: Question
has answer: http://stackoverflow.com/a/49860682
has title: Python HTTPConnectionPool error
has body: I'm trying to run a python script (that is not mine) which is supposed to connect to an IP address (192.168.1.3) on the LAN. File "control/insert_to_container.py", line 36, in &lt;module&gt; res=read_info.open_file() File "/control/read_info.py", line 21, in open_file r = requests.get('http://'+line.rstrip('\t')+':491155') File "/usr/local/lib/python2.7/site-packages/requests/api.py", line 72, in get return request('get', url, params=params, **kwargs) File "/usr/local/lib/python2.7/site-packages/requests/api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "/usr/local/lib/python2.7/site-packages/requests/sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python2.7/site-packages/requests/sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python2.7/site-packages/requests/adapters.py", line 508, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='192.168.1.3', port=491155): Max retries exceeded with url: / (Caused by NewConnectionError('&lt;urllib3.connection.HTTPConnection object at 0x7f8fd9e9b250&gt;: Failed to establish a new connection: [Errno 111] Connection refused',)) I specified the IP address in a config file. Would anybody know what the %09 is in the error HTTPConnectionPool(host=192.168.1.3%09. I wondering if this is the source of the error.
has comment: http://stackoverflow.com/comment/86736179
tagged with: python

http://stackoverflow.com/comment/86818443
type: AnswerComment
score: 0
type: Comment
has text: your problem could be that there is some `postal_code` in `df1` not in `df2` then you have an empty `df2_select_add`. One option could be to check if `df2_select_add` is empty. After the line 'df2_select_add = ...' you can add `if df2_select_add.empty: return 'N'`
comment on: http://stackoverflow.com/a/49880773

http://stackoverflow.com/q/49834738
accepted answer: http://stackoverflow.com/a/49834769
type: Question
tagged with: python-3.x
answer count: 2
has comment: http://stackoverflow.com/comment/86684719
has comment: http://stackoverflow.com/comment/86684664
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86684697
tagged with: python
has answer: http://stackoverflow.com/a/49834831
favorite count: 0
possible better answer: http://stackoverflow.com/a/49834831
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/86684640
has body: I have a string pizzas and when comparing it to pizza - it is not the same. How can you make a program that counts common letters (in order) between two words, and if it's a 60% match then a variable match is True? For e.g. pizz and pizzas have 4 out of 6 letters in common, which is a 66% match, which means match must be True, but zzip and pizzasdo not have any letters in order in common, thus match is False
has title: How to count common letters in order between two words in Python?
has answer: http://stackoverflow.com/a/49834769

http://stackoverflow.com/a/49875566
has comment: http://stackoverflow.com/comment/86799840
score: 1
accepted answer of: http://stackoverflow.com/q/49875520
type: AcceptedAnswer
has body: You can convert columns names to default by range: df1.columns = range(len(df1.columns)) df2.columns = range(len(df2.columns)) df_combined = pd.concat([df1,df2]) Or: map1 = dict(zip(df1.columns, range(len(df1.columns)))) map2 = dict(zip(df2.columns, range(len(df2.columns)))) df_combined = pd.concat([df1.rename(columns=map1), df2.columns.to_frame().T.rename(columns=map2), df2.rename(columns=map2)], ignore_index=True) print (df_combined) 0 1 2 3 0 1 4 7 NaN 1 2 5 8 NaN 2 3 6 9 NaN 3 W X Y Z 4 W1 X1 Y1 Z1 5 W2 X2 Y2 Z2 6 W3 X3 Y3 Z3
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49875520
type: Answer

http://stackoverflow.com/a/49826423
type: Answer
has comment: http://stackoverflow.com/comment/86669213
has comment: http://stackoverflow.com/comment/86669140
has comment: http://stackoverflow.com/comment/86669268
has comment: http://stackoverflow.com/comment/86669410
has comment: http://stackoverflow.com/comment/86669063
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: I expect this approach will be faster: df.set_index('TIME', inplace=True) df.update(labelDf.reset_index().melt(id_vars=['index', 'LABEL']). \ groupby(['index', 'LABEL'])['value']. \ apply(lambda x: pd.Series(list(range(*list(x))+[max(x)]))). \ reset_index().set_index('value')) df # some_features LABEL # TIME # 1 f -1.0 # 2 f 0.0 # 3 f 0.0 # 4 f 0.0 # 5 f -1.0 # 6 f 1.0 # 7 f 1.0 Explanation: This performs a series of reshaping operations on your labelDf (none of them in-place) before passing the reshaped dataframe to .update. First, melt labelDf: labelDf.melt(id_vars='LABEL') # LABEL variable value # 0 0 TIME_START 2 # 1 1 TIME_START 6 # 2 0 TIME_STOP 4 # 3 1 TIME_STOP 8 Then, group by LABEL, select value, and apply a lambda that places the TIME_START and TIME_STOP values in a list, creates a range with that list and appends the list max to make it inclusive (e.g. so range(*list([2,4]))+[max([2,4])] returns [2, 3, 4]), and passes the resulting list to pd.Series to split the list into columns. Hence the result of this operation: labelDf.melt(id_vars='LABEL').groupby('LABEL')['value'].apply( \ lambda x: pd.Series(range(*list(x))+[max(x)])) ...looks like this: # LABEL # 0 0 2 # 1 3 # 2 4 # 1 0 6 # 1 7 # 2 8 The final steps are reseting the index, and then setting it to value, in this case, so that the dataframe that's passed to .update looks like this: # LABEL level_1 # value # 2 0 0 # 3 0 1 # 4 0 2 # 6 1 0 # 7 1 1 # 8 1 2 Note that you can drop the level_1 column, but it's not necessary -- since there is no column with this name in your df, it will have no bearing on the result of update.
accepted answer of: http://stackoverflow.com/q/49826145
answers question: http://stackoverflow.com/q/49826145
has comment: http://stackoverflow.com/comment/86669458
has comment: http://stackoverflow.com/comment/86669295

http://stackoverflow.com/comment/86840268
type: Comment
has text: @NBC you are welcome. Regular expressions. Very complicated and powerful. I am still learning. Questions on SO help me practice. I am not totally convinced this express is robust enough. However, I think it solves the problem for this test dataset.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49912145

http://stackoverflow.com/a/49815910
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49815589
type: Answer
accepted answer of: http://stackoverflow.com/q/49815589
has body: you dont need the url to actually post it in the same page just use this {% extends 'admin/baseadmin.html' %} {% load staticfiles %} {% block content %} {% csrf_token %} {% csrf_token %} {{form.as_p}} {% endblock %}
score: 0
has comment: http://stackoverflow.com/comment/86646174

http://stackoverflow.com/comment/86678726
score: 0
type: Comment
has text: @KeyurPotdar That's the thing. I have no idea what this is and each time I log in the name and the value are different
type: QuestionComment
comment on: http://stackoverflow.com/q/49831540

http://stackoverflow.com/comment/86989499
type: QuestionComment
has text: @Pygasm because this is useful for things other than games
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49886706

http://stackoverflow.com/a/49786860
answers question: http://stackoverflow.com/q/49786837
type: Answer
has body: Use re.sub and replace the pattern /.*$ with empty string: import re input = "PHP/USD" line = re.sub(r"/.*$", "", input) print line # prints PHP If you wanted the reverse, then use the pattern ^.*/.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49786837
score: 0

http://stackoverflow.com/comment/86622468
has text: Have you tried b'https'?
type: Comment
comment on: http://stackoverflow.com/q/49803909
score: 0
type: QuestionComment

http://stackoverflow.com/a/56270166
score: 2
answers question: http://stackoverflow.com/q/49784063
downvote count: 0
type: Answer
has body: You can try: dict(df.dtypes)['column name'] == 'int' df.dtypes returns list of tuples and the easiest way to get the type as string for each column is to convert it to dict.
upvote count: 2

http://stackoverflow.com/comment/86768213
comment on: http://stackoverflow.com/q/49875145
type: QuestionComment
has text: @ChandaKorat it throws first screenshot error
score: 0
type: Comment

http://stackoverflow.com/a/49854202
has body: even = [ x for x in range(15) if x%2 == 0] Just a list comprehension
answers question: http://stackoverflow.com/q/49854145
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86820339
has text: Very nice solution! The first time I really see the benefits of decorators and will finally use them :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49902424
type: AnswerComment

http://stackoverflow.com/comment/86662196
score: 0
comment on: http://stackoverflow.com/q/49811284
type: QuestionComment
has text: @KeerthiBachu yes what you got is right ..this is exactly what I want..... Actually this problem statement was asked me in interview. and interviewer was so clear about problem statement.
type: Comment

http://stackoverflow.com/q/49847534
answer count: 2
has answer: http://stackoverflow.com/a/49847640
tagged with: pivot
has body: How do I return column name and value based on column value for each record ? I have this: I would like to update first_color with color name having highest value first_value with highest value and so on, as shown in the below snippet. Note: This is just an example, I have over 100 columns for which I need column name &amp; value for top 5 columns/values. So, looking for a dynamic sql if possible. I got till this point, using cross apply.
tagged with: sql
score: 1
downvote count: 0
possible better answer: http://stackoverflow.com/a/49848232
upvote count: 1
tagged with: excel
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49848232
accepted answer: http://stackoverflow.com/a/49847640
tagged with: sql-server
type: AnsweredQuestion
has title: Return SQL Server column name and corresponding value based on column value

http://stackoverflow.com/comment/86796965
comment on: http://stackoverflow.com/a/49890383
has text: @BOi Yeah, sorry I've been stuck on this problem for the last three hours, I really didn't want to make a post because I figured it'd be something stupid which it was but I could not figure out what was wrong. Thanks to everybody! You're great.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/86536739
comment on: http://stackoverflow.com/q/49760656
type: Comment
type: QuestionComment
has text: I need to figure out how to get inspect.getfile() to return an absolute path.
score: 0

http://stackoverflow.com/comment/86637143
has text: Great comparison! Thanks!
type: Comment
comment on: http://stackoverflow.com/a/49770323
score: 0
type: AnswerComment

http://stackoverflow.com/q/49787327
has body: I'm just trying to do something very basic on my Mac using selenium and I can't even open a webpage. I'm getting an error of : Traceback (most recent call last): File "/Users/godsinred/Desktop/InstagramLiker/GmailAccountGenerator.py", line 10, in &lt;module&gt; driver = webdriver.Chrome() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 68, in __init__ self.service.start() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 88, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home Here is my code below: from selenium import webdriver import time link = "https://accounts.google.com" driver = webdriver.Chrome() driver.get(link) time.sleep(5) driver.quit()
downvote count: 0
score: 18
tagged with: selenium
answer count: 6
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/63547135
has answer: http://stackoverflow.com/a/68718009
linked to: http://stackoverflow.com/q/47148872
has answer: http://stackoverflow.com/a/67765707
has answer: http://stackoverflow.com/a/52465764
tagged with: python
upvote count: 18
tagged with: webdriver
accepted answer: http://stackoverflow.com/a/49788993
possible better answer: http://stackoverflow.com/a/53577896
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49788993
has title: Selenium on MAC, Message: 'chromedriver' executable may have wrong permissions
has answer: http://stackoverflow.com/a/53577896

http://stackoverflow.com/comment/86740343
type: AnswerComment
score: 0
has text: @AndyG to assign values to a key in a dictionary `d`, you do `d[key] = value`, not `key = value`
type: Comment
comment on: http://stackoverflow.com/a/49861739

http://stackoverflow.com/a/49823873
upvote count: 1
has comment: http://stackoverflow.com/comment/86671794
has comment: http://stackoverflow.com/comment/86671765
type: Answer
accepted answer of: http://stackoverflow.com/q/49823263
has comment: http://stackoverflow.com/comment/86667172
answers question: http://stackoverflow.com/q/49823263
has body: I would like to draw some line or bar graphs that group by market and between some date values, say 2000 and 2002 in this example I will be using in both cases this as my data: import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'market': ['A', 'A', 'B', 'B', 'C', 'C'], 'date': [2000, 2001, 2000, 2001, 2000, 2001], 'm1': [1, 2, 3, 4, 5, 6 ], 'm2': [4, 3, 5, 2, 1, 0]}) Use @Ami Tavory's answer to format the date correctly For one subplot per metric: f, ax = plt.subplots(ncols=2) df.pivot(columns='market', index='date', values='m1').plot(ax=ax[0]) df.pivot(columns='market', index='date', values='m2').plot(ax=ax[1]) plt.plot() For one subplot per market: f, ax = plt.subplots(ncols=3) df[df.market=='A'].plot(x='date', y=['m1', 'm2'], ax=ax[0]) df[df.market=='B'].plot(x='date', y=['m1', 'm2'], ax=ax[1]) df[df.market=='C'].plot(x='date', y=['m1', 'm2'], ax=ax[2]) plt.plot()
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49832530
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86680308
tagged with: list
has comment: http://stackoverflow.com/comment/86680807
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has title: Python mutation of lists in tuples
has answer: http://stackoverflow.com/a/49832990
favorite count: 0
type: Question
tagged with: python-3.x
has body: After learning about lists and box-and-pointer diagrams, I decided to create random stuff for myself and test out my knowledge. I am going to use the words shallow copy and suspected shallow copies as I'm not really sure whether they are correct by definition. My queries are in the reasons provide for the behaviour of such code, please tell me whether I'm thinking soundly. Code A from copy import * x=[1,[2,[3,[4]]]] #normal copy/hardcopy a=x v=list(x) #suspected shallow copy y=x.copy() #shallow copy z=deepcopy(x) #theoretical deep copy w=x[:] #suspected shallow copy def test(): print("Original:",x) print("hardcopy:",a) print("suspected shallow copy",v) print("shallow copy",y) print("deep copy:",z) print("suspected shallow copy",w) x[1]=x[1]+[4] test() Output A: Original: [1, [2, [3, [4]], 4]] hardcopy: [1, [2, [3, [4]], 4]] suspected shallow copy [1, [2, [3, [4]]]] shallow copy [1, [2, [3, [4]]]] deep copy: [1, [2, [3, [4]]]] suspected shallow copy [1, [2, [3, [4]]]] Code B a=(1,2,[1,2,3]) def shallow_copy(x): tup=() for i in x: tup+=(i,) return tup def hardcopy(x): return x b=hardcopy(a) c=shallow_copy(a) a[2]+=[3] Output B: I see TypeError in IDLE here, but the mutation of the list element is still done, and across ALL a,b,c Continuation from output B: a[2][0]=a[2][0]+99 a,b,c Output C: ((1, 2, [100, 2, 3, 3]), (1, 2, [100, 2, 3, 3]), (1, 2, [100, 2, 3, 3])) Code D: a=[1,2,(1,2,3)] def shallow_copy(x): tup=[] for i in x: tup+=[i] return tup def hardcopy(x): return x b=hardcopy(a) c=shallow_copy(a) d=a.copy() a[2]=a[2]+(4,) a,b,c,d Output D: [1, 2, (1, 2, 3, 4)], [1, 2, (1, 2, 3, 4)], [1, 2, (1, 2, 3)], [1, 2, (1, 2, 3)] From Output A, we observe the following: 1)For lists which have shallow copies, doing x[1]=x[1]+[4] does not affect the shallow copies. My reasons for the above could be a) = followed by + does __add__ instead of __iadd__(which is +=), and doing __add__ should not modify the object, only changing the value for one pointer(x and its hardcopy in this…

http://stackoverflow.com/comment/86540875
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/49762598
has text: `0.0.0.0` is not a real address, it's a special value that means "listen on every IPv4 network you can listen on". To connect, you have to specify one of those addresses. Usually you'll want to use `127.0.0.1` if you're running on the same machine of the server.
type: Comment

http://stackoverflow.com/q/49846327
tagged with: firefox
tagged with: opera
downvote count: 0
upvote count: 1
tagged with: python
tagged with: google-chrome
answer count: 0
score: 1
tagged with: http
favorite count: 0
has title: Why browsers are doubling requests to backend
type: Question
has body: I noticed in the logs that my backend service is overloaded with a lot of timeouting requests. Therefore I wrote a simple example in Python (very easy to write and test with): import socket import threading class RequestHandler(threading.Thread): def __init__(self, client, address): self.client = client self.client.settimeout(5.0) self.address = address threading.Thread.__init__(self, name="Handler") self.setDaemon(True) self.start() def run(self): print "Request: %s" % str(self.address) print "%s" % self.client.recv(1024) file = open("/Users/kk/Desktop/apachi-icon.png") data = file.read() file.close() self.client.send("HTTP/1.1 200 OK\r\n") self.client.send("Server: KkHttp/1.0.0\r\n") self.client.send("Cache-Control: max-age=%s\r\n" % (60 * 60 * 24)) self.client.send("Content-Length: %d\r\n" % len(data)) self.client.send("Connection: close\r\n") self.client.send("Content-Type: image/png\r\n") self.client.send("\r\n") self.client.send(data) self.client.close() print "Response: %s" % str(self.address) acceptSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) acceptSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) acceptSocket.bind(("", 8080)) acceptSocket.listen(100) while True: s, a = acceptSocket.accept() RequestHandler(s, a) Then I use my Chrome (I tested Opera and Firefox are doing the same) to request a single file: And in the console of my Python server, I can see two requests, one of them actually timeouting: Request: ('127.0.0.1', 61047) GET /www/sportovniservis/frontend/img/apachi-icon.png HTTP/1.1 Host: localhost:8080 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: cs-CZ,cs;q=0.9,en;q=0.8 Cookie: __KK_BLAZEK_LOGIN__=%22789c0dd24b76a3381…
type: UnansweredQuestion

http://stackoverflow.com/q/49795346
accepted answer: http://stackoverflow.com/a/49796026
tagged with: regex
has answer: http://stackoverflow.com/a/49796026
type: Question
has title: Filtering list items with case insensitive
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49795842
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/49795842
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86605887
score: 0
has comment: http://stackoverflow.com/comment/86605647
has body: Need help to minimize the code.I have used RegEx to filter data from a JSON file to accept (I)teration as well (i)teration. But while replacing the list items which has Iteration or iteration, I can only replace one. by appending the results I am getting the desired output, but it stretches the code for this simple task.and I am not sure though tomorrow I may get Iteration as iTERaTion .. My goal is to extract the only numbers from the list items to convert it to date time format, which I will be taking care. Code: print("Unfiltered Folders : \n", Path_List) regex = re.compile('(?i)^20\d{6}-Iteration$') regex1 = re.compile('(?i)-iteration$') Filtered_Path_List = list(filter(regex.search,Path_List)) print("List of Iteration folder will be considered for further Process: \n", Filtered_Path_List) final_iteration = [e.replace("-Iteration", "") for e in Filtered_Path_List] print("Latest Iteration list : ", final_iteration) LOG: Unfiltered Folders : ['20171226-Iteration', '20180105-iteration', '20180112-iteration', '20180117-Iteration', '20180118-Iteration', '20180123-Iteration', '20180124-Iteration', '20180202-Iteration', '20180207-Iteration', '20180220-Iteration', '20180321-Iteration', '20180322-Iteration', '20180327-Iteration', '_Kyle-AutomationTesting', '_Template'] List of Iteration folder will be considered for further Process: ['20171226-Iteration', '20180105-iteration', '20180112-iteration', '20180117-Iteration', '20180118-Iteration', '20180123-Iteration', '20180124-Iteration', '20180202-Iteration', '20180207-Iteration', '20180220-Iteration', '20180321-Iteration', '20180322-Iteration', '20180327-Iteration'] Latest Iteration list : ['20171226', '20180105-iteration', '20180112-iteration', '20180117', '20180118', '20180123', '20180124', '20180202', '20180207', '20180220', '20180321', '20180322', '20180327'] all_iteration.txt file created on : 2018-04-12 16:44 Process finished with exit code 0 As you can see the final_iteration[] has '20180105-iteration', '20180112-it…

x3d
type: Tag
tags question: http://stackoverflow.com/q/49887398
tag name: x3d

http://stackoverflow.com/q/49856172
possible better answer: http://stackoverflow.com/a/49856243
tagged with: regex
has answer: http://stackoverflow.com/a/49856356
has answer: http://stackoverflow.com/a/49856243
has title: Python regex, capture groups that are not specific
type: AnsweredQuestion
answer count: 3
score: 1
downvote count: 0
upvote count: 1
has body: Consider the following example strings: abc1235abc53abcXX 123abc098YXabc I want to capture the groups that occur between the abc, e.g. I should get the following groups: 1235, 53, XX 123, 098YX I'm trying this regex, but somehow it does not capture the in-between text: (abc(.*?))+ What am I doing wrong? EDIT: I need to do it using regex, no string splitting, since I need to apply further rules on the captured groups.
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49856355
has answer: http://stackoverflow.com/a/49856355
tagged with: python

http://stackoverflow.com/a/49881460
has comment: http://stackoverflow.com/comment/86824679
has comment: http://stackoverflow.com/comment/86780647
score: 1
type: Answer
has body: There will be some added space complexity, but one way to get to this would be to expand b to enable a broadcasted comparison and enable you to get rid of the (Python) loop entirely: # for n = 10; m = 2; np.random.seed(444) &gt;&gt;&gt; np.sum(b &gt; b[:, None], axis=-2) / n array([[0.7, 0.1], [0.3, 0.6], [0. , 0.2], [0.4, 0.8], # ... Full code: import numpy as np np.random.seed(444) def loop(b): # Could also use for (i, j), val in np.ndenumerate(b) p = np.zeros_like(b) for i in range(0, n): for j in range(0, m): r = b[i, j] p[i, j] = ((b[:, j] &gt; r).sum()) return p / n def noloop(b): n = b.shape[0] return np.sum(b &gt; b[:, None], axis=-2) / n n = 10 m = 2 b = np.random.rand(n, m) assert np.allclose(loop(b), noloop(b)) # True n = 1000 m = 200 b = np.random.rand(n, m) %timeit loop(b) # 1.59 s ± 50.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit -r 7 -n 1 noloop(b) # 443 ms ± 18.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) assert np.allclose(loop(b), noloop(b)) # True
answers question: http://stackoverflow.com/q/49880927
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86822340

http://stackoverflow.com/a/49889128
has comment: http://stackoverflow.com/comment/86794402
type: Answer
downvote count: 1
score: -1
upvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49889088
has body: This line is not valid python3 syntax: (EDIT: it's a valid syntax ! But not what you want :) ) print ("The password is %s") % (line); Use this instead: print ("The password is %s" % line) Also, accordig to the error message, line might be None.
accepted answer of: http://stackoverflow.com/q/49889088

http://stackoverflow.com/comment/129098154
score: 0
comment on: http://stackoverflow.com/a/49911616
type: Comment
type: AnswerComment
has text: The pre-3.10 solution seems way more complicated than it needs to be? Seems to me that once you've created `MyDataClass`, you can just do `original_init = MyDataClass.__init__`, then define `def new_init(self, ..., *, kw_only_arg, ...): original_init(self, ..., kw_only_arg=kw_only_arg, ...)`, and then finally `MyDataClass.__init__ = new_init`... I don't have time to test right now but I think that should be good enough?

http://stackoverflow.com/a/49859519
score: 4
answers question: http://stackoverflow.com/q/49859287
upvote count: 4
has body: The GIL guarantees that one single process is executed at any time. However, when using threads you may have files or other objects shared between threads. Even if only one thread is active at any moment (because of the GIL), multiple threads may have access to the same object, here is when locks enter into play. Using threading.Lock() avoids that a given object is accessed by a second thread while a first thread is already using it. Let's say you have a file and two threads want to write the same file. The GIL gurantee that only one WRITE operation it is executed at a given moment, the Lock will guarantee that only a single thread can write that file.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86778410
type: Comment
has text: @Lundin OCaml ;)
comment on: http://stackoverflow.com/a/49881061
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86705492
type: AnswerComment
comment on: http://stackoverflow.com/a/49845128
score: 0
has text: this is a very strange assignment if the strings actually have \032 in them since that already means something to python
type: Comment

http://stackoverflow.com/comment/86848412
score: 1
comment on: http://stackoverflow.com/q/49916472
type: QuestionComment
has text: Whatever you and maybe others working in the code prefer.
type: Comment

http://stackoverflow.com/comment/86546459
has text: hour_click = context.browser.find_element_by_id("listitem1innerListBoxjqxWidgetac7737dcf714") hour_click.click() time.sleep(3)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49765233
type: QuestionComment

http://stackoverflow.com/q/49778697
score: 0
has answer: http://stackoverflow.com/a/49779601
answer count: 3
possible better answer: http://stackoverflow.com/a/49778753
has comment: http://stackoverflow.com/comment/86572819
upvote count: 1
has answer: http://stackoverflow.com/a/49778753
downvote count: 1
favorite count: 0
type: Question
has body: Essentially I want to strip out the text in-between a closing square bracket "]" and the start of a word (CALL or RETURN) Strings to work with: [2018-01-18 18:22:28,516] .- CALL do.something(key=True) [2018-01-18 18:22:28,517] .- RETURN do.something Expected output: .- .- My code looks something like this: def find_middle_bit(string): string_of_interest = re.search(r"\](.*)[^A-Za-z]", string) print str(string.strip()) if string_of_interest: print string_of_interest.group(1) line = "[2018-01-18 18:22:28,516] .- CALL do.something(key=True)" find_middle_bit(line) Actual output: .- CALL do.something(key=True What am I missing here?
accepted answer: http://stackoverflow.com/a/49778828
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/49778828
has comment: http://stackoverflow.com/comment/86572809
has title: Why does my regex work in a tester but not in re.search?
type: AnsweredQuestion

http://stackoverflow.com/q/49833921
tagged with: push-notification
tagged with: android
has answer: http://stackoverflow.com/a/49833949
tagged with: python
type: Question
has body: I'm working on a project on pythonanywhere.com and my code in Python (with Flask framework) manages requests of an Android app that wants to access the MySQL database. The point is that I would like a notification to arrive on the Android smartphone when a row is added to a database table. If I understand correctly, from Python to Android I can use Firebase Cloud Messaging, but I'm not sure what to use from MySQL to Python: a trigger that calls a script that will send the notification? Or Python listening to the database? Or what else? Remember that I'm not using personal servers and databases but those offered by the above mentioned domain so I'm not sure I can use everything I want (for example, if I'm not mistaken, it is not possible to implore a UDF). Thanks in advance!
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49850786
tagged with: mysql
has answer: http://stackoverflow.com/a/49850786
tagged with: firebase
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49833949
has title: Python - send notification to Android app after the MySQL database has changed

http://stackoverflow.com/q/49880974
has answer: http://stackoverflow.com/a/49881068
has answer: http://stackoverflow.com/a/49881088
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
has title: Regex in Python to match words with special characters
accepted answer: http://stackoverflow.com/a/49881068
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/117769123
downvote count: 1
has body: I have this code import re str1 = "These should be counted as a single-word, b**m !?" match_pattern = re.findall(r'\w{1,15}', str1) print(match_pattern) I want the output to be: ['These', 'should', 'be', 'counted', 'as', 'a', 'single-word', 'b**m'] The output should exclude non-words such as the "!?" what are the other validation should I use to match and achieve the desired output?
type: AnsweredQuestion
score: 3
answer count: 3
has answer: http://stackoverflow.com/a/49881123
possible better answer: http://stackoverflow.com/a/49881088

http://stackoverflow.com/q/49863084
linked to: http://stackoverflow.com/q/38438646
tagged with: python
has title: Shape matching using shape contours detection
score: 0
has answer: http://stackoverflow.com/a/49884254
has body: import numpy as np import cv2 temp = cv2.imread('./image/star.jpg') ret, temp_thre = cv2.threshold(temp, 100, 255,0) cv2.imshow("store gray iamge",temp_thre) cv2.waitKey(0) _, contours, hierarchy = cv2.findContours(temp_thre, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) temp_cont = sorted(contours, key=cv2.contourArea, reverse= True) new_temp_cont = temp_cont[1] tar = cv2.imread('./image/store.jpg') tar_gray = cv2.cvtColor(tar, cv2.COLOR_BGR2GRAY) tar_thr = cv2.threshold(tar_gray, 127, 255, 0) _, contours, hierarchy = cv2.findContours(tar_thr, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) for c in contours: match = cv2.matchShapes(new_temp_cont, c, 1, 0.0) print(match) if match &lt; 0.15: closest_match = c else: closest_match = [] cv2.drawContours(tar, [closest_match], -1, (0,255,0),2) cv2.imshow("output", tar) cv2.waitKey(0) cv2.destroyAllWindows() This is my code but I still haven't been able to rectify it. Please help me in this regard. Error arrived here is: C:\python36\python.exe C:/Users/shahid/PycharmProjects/untitled/segmentation_object_detection.py OpenCV Error: Unsupported format or combination of formats ([Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only) in cvStartFindContours_Impl, file C:\projects\opencv-python\opencv\modules\imgproc\src\contours.cpp, line 199 Traceback (most recent call last): File "C:/Users/shahid/PycharmProjects/untitled/segmentation_object_detection.py", line 10, in &lt;module&gt; _, contours, hierarchy = cv2.findContours(temp_thre, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)`enter code here` cv2.error: C:\projects\opencv-python\opencv\modules\imgproc\src\contours.cpp:199: error: (-210) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function cvStartFindContours_Impl
answer count: 1
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/86756836
type: UnansweredQuestion

http://stackoverflow.com/comment/86857601
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49914268
has text: my version is 2.0.2
type: Comment

http://stackoverflow.com/comment/86534236
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49759611
has text: Importing a package doesn't automatically load all its submodules.

http://stackoverflow.com/comment/86641777
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49813365
has text: Just did, replace the original screenshot.
score: 0

http://stackoverflow.com/q/49906809
has answer: http://stackoverflow.com/a/49907158
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49913774
tagged with: python
has title: json does not have column names after resample pandas
has answer: http://stackoverflow.com/a/49913774
has comment: http://stackoverflow.com/comment/86830050
score: 2
has comment: http://stackoverflow.com/comment/86842772
answer count: 2
has comment: http://stackoverflow.com/comment/86829612
upvote count: 2
downvote count: 0
has body: How to get column names when you are using to_json on resample data? amount = df['amount'].resample('M').last() amount = amount.to_json() output that I'm getting: {"1501459200000":1.79,"1504137600000":88.80} output I want: [{"time":"1501459200000","amount":1.79},{"time":"1504137600000","amount":88.80}]
has comment: http://stackoverflow.com/comment/86842680
favorite count: 0
possible better answer: http://stackoverflow.com/a/49907158
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/49811766
has body: By Euclidian distance: &gt;&gt;&gt; some_pt1 = [(10.76,2.9),(3.24,4.28),(7.98,1.98),(3.21,9.87)] &gt;&gt;&gt; some_pt2 = [(11.87,6.87), (67.87,8.88), (44.44, 6.78), (9.81, 1.09), (6.91, 0.56), (8.76, 8.97), (8.21, 71.66)] &gt;&gt;&gt; &gt;&gt;&gt; def dist_sq(p1_p2): ... p1, p2 = p1_p2 ... return sum(x*y for x,y in zip(p1, p2)) ... &gt;&gt;&gt; &gt;&gt;&gt; min(((p1, p2) for p1 in some_pt1 for p2 in some_pt2), key=dist_sq) ((3.24, 4.28), (6.91, 0.56)) Which has runtime O(n*m) (where n, m are the lengths of your lists). Since you need to look at all the pairs, it won't get better than this. Note that comparing the squared distances is enough, no need to compute the root.
has comment: http://stackoverflow.com/comment/86638541
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/86638421
answers question: http://stackoverflow.com/q/49811583
has comment: http://stackoverflow.com/comment/86638480

http://stackoverflow.com/q/49900892
has answer: http://stackoverflow.com/a/49901210
tagged with: python-2.7
has body: Hi I am having a really frustrating time trying to import a json file to my python script. When I run the file individually it works fine. However I am trying to import the file into another area of my system import sys sys.path.append(r'/home/seamus/code/544-dss/controllers/google') import google_worksheets test = google_worksheets.g_sheets() print(test.service) When I do this it works until hitting this line of code in my class ServiceAccountCredentials.from_json_keyfile_name('newcred.json', self.scope) Then I get the error message: No such file or directory: 'newcred.json' The file newcred.json is in the same directory as google_worksheets and when I run google_worksheets on it's own it works fine (right click file and click run). Any suggestion on how to fix this would be greatly appreciated as this is very annoying? My folder structure is like this: /home/seamus/code/544-dss/controllers/google with init.py, google_worksheets.py and newcred.json all living inside the google folder. Thanks very much
has comment: http://stackoverflow.com/comment/86817357
type: Question
has title: No such file or directory: 'newcred.json'
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/86580493
has text: Either way, check out http://blog.dolphm.com/pep257-good-python-docstrings-by-example/ it shows examples of both
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49782603
score: 0

http://stackoverflow.com/q/49837339
tagged with: pandas
answer count: 0
score: 1
downvote count: 0
upvote count: 1
has title: Pycharm: importing pandas prevents console output
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/48209506
has comment: http://stackoverflow.com/comment/86739761
has body: I use Pycharm 2018.1, anaconda python 3.6 When I run a script using the configuration in the screenshot, I get its output in the console as expected. Also, I get a command line afterwards. However, if I import Pandas in the same script, no output is generated. This very simple script: print('test') results in 'test' being printed as output in the console window. Simply adding a Pandas import statement as follows import pandas print('test') makes that I do not get any output. Why would importing pandas mess up Pycharms behavior? ps. I found related question: PyCharm shows no output from pandas. However, here it is suggested to explicitly print whatever I want to see in the console. I already do so and still Pandas messes up the expected output.
tagged with: pycharm

http://stackoverflow.com/q/49797401
upvote count: 5
tagged with: rpy2
tagged with: python
tagged with: http://stackoverflow.com/tag/r
has title: unsigned integer error while trying to convert pandas dataframe to R's dataframe using rpy2
answer count: 2
score: 5
tagged with: pandas
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59659698
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49868203
has body: I have the below data : grp_m1 grp_m2 grp_m3 grp_m4 $50-$75 $50-$75 $50-$75 $50-$75 $50-$75 $50-$75 $50-$75 $50-$75 $150-$175 $150-$175 $150-$175 $150-$175 $100-$125 $100-$125 $100-$125 $100-$125 $150-$175 $125-$150 $125-$150 $125-$150 These are then converted to dummies. The dtype of these dummies is unsigned int in the pandas dataframe, and when I try to convert into this into an R dataframe by using the below code: from rpy2.robjects import pandas2ri pandas2ri.activate() pandas2ri.py2ri(data) I get the error below: Error while trying to convert the column "grp_m4_$175-$200". Fall back to string conversion. The error is: Cannot convert numpy array of unsigned values -- R does not have unsigned integers. (name, str(e))) C:\Users\hduser\AppData\Local\Continuum\anaconda3.1\lib\site-packages\rpy2-2.9.1-py3.6-win-amd64.egg\rpy2\robjects\pandas2ri.py:61: UserWarning: Error while trying to convert the column "grp_m4_$200-$225". Fall back to string conversion. The error is: Cannot convert numpy array of unsigned values -- R does not have unsigned integers. (name, str(e))) Can this be fixed or do I need to remove those columns all together, e.g. just skip the column if this error is coming? Can someone please help me with this?
has comment: http://stackoverflow.com/comment/86609516

http://stackoverflow.com/a/49848093
score: 18
type: Answer
has body: Introduction Let's start by describing the sample image in detail. It is a 4 channel image (RGB + alpha transparency), but it only uses shades of gray. The image fits the drawing quite well, there's only a minimal margin around the shape. There is a filled, anti-aliased, rotated outer ellipse, surrounded by a transparent background. The outer ellipse is filled with a rotated elliptical gradient (concentric, and with same rotation as the ellipse), which is black on the edge, progressing linearly to white in the center. The outer ellipse is overlaid with a concentric, filled, anti-aliased, rotated inner ellipse (again same rotation, both axis are scaled in the same proportion). The fill colour is white. Furthermore, let: a and b be the semi-major and semi-minor axis of the ellipse theta be the rotation angle of the ellipse around its center in radians (at 0 a points along the x axis) inner_scale is the ratio between corresponding axes of the inner to the outer ellipse (i.e. 0.5 means inner is scaled down by 50%) h and k are the (x,y) coordinates of the ellipse center In the demonstrated code we will use the following imports: import cv2 import numpy as np import math And set the parameters defining our drawing (we will calculate h and k) as: a, b = (360.0, 200.0) # Semi-major and semi-minor axis theta = math.radians(40.0) # Ellipse rotation (radians) inner_scale = 0.6 # Scale of the inner full-white ellipse Step #1 The first step we need to take in order to generate such image is to calculate what size of a "canvas" (the image we will be drawing into) we need. To do this, we can calculate the bounding box of the rotated outer ellipse and add some small margin around it. I'm not aware of an existing OpenCV function to efficiently do this, but StackOverflow saves the day -- there already is a related question with an answer linking to a useful article discussing the problem. We can use those resources to come up with the following Python implementation: def ellipse_bbox…
upvote count: 18
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49829783
has comment: http://stackoverflow.com/comment/86727543
accepted answer of: http://stackoverflow.com/q/49829783

http://stackoverflow.com/comment/86595454
score: 0
has text: I uploaded my code as pic.
comment on: http://stackoverflow.com/q/49789600
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49799906
possible better answer: http://stackoverflow.com/a/49800202
has answer: http://stackoverflow.com/a/49801030
has answer: http://stackoverflow.com/a/49800202
favorite count: 0
type: Question
tagged with: statistics
has comment: http://stackoverflow.com/comment/86614547
score: 2
type: AnsweredQuestion
tagged with: gamma-distribution
has comment: http://stackoverflow.com/comment/86614808
tagged with: python
has comment: http://stackoverflow.com/comment/86614668
tagged with: scipy
has body: I have a gamma distribution with shape and scale parameter 2.126, 0.370. You can plot it with following code: shape, scale = 2.126, 0.370 # mean=4, std=2*sqrt(2) s = np.random.gamma(shape, scale, 1000) weights = np.ones_like(s)/float(len(s)) plt.hist(s, 30,weights=weights) The parameters are originally used to describe the walking distance between home and a public transport node with unit km. Now I want to transfer the unit to m. How could I keep the same shape, only with difference on the unit of x Axis. What should the new shape and scale parameters be? To be more clear, I want the x axis scales to become 500, 1000, 1500 ... instead of 0.5, 1, 1.5 ...
tagged with: distribution
answer count: 2
has title: Python covert x axis unit of gamma distribution
upvote count: 2
accepted answer: http://stackoverflow.com/a/49801030
downvote count: 0

http://stackoverflow.com/comment/86766866
type: QuestionComment
has text: The arrays are histograms of Images so I did represented the histogram in 2d format instead of 1d array and it didn't work, what I did is that I applied np function of converting a 1d array to 2d array just as simple as that and also represented the pixels instead of histogram but as 2d matrix of the image and it doesn't work because the rest of the data in the same row are all numeric, I researched a bit if random forest classifier can take in mixed values as input or only numeric and it seems as @hellpanderr stated that classifier expect to get only numeric values, but kindly guide me.
comment on: http://stackoverflow.com/q/49843361
score: 0
type: Comment

http://stackoverflow.com/comment/86836554
has text: I don't know what you expect here. Normally Numba optimizes your desired function to your working function. If it can't do that, it is often beneficial to do quite the opposite you are trying to do manually. How do you expect np.arange works in non-comiled code? It is looping to get the values and ones more looping if the values should be copyied to the destination array. Think of how you would do that in C and you usually get the most performant code.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49907604

http://stackoverflow.com/a/50061161
type: Answer
answers question: http://stackoverflow.com/q/49826003
has comment: http://stackoverflow.com/comment/87230877
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49826003
downvote count: 0
score: 2
has body: No, pandas can't read such a structure. An alternative solution is to use pandas to read your data, but transform this into an easily accessible dictionary, rather than keeping your data in a dataframe with MultiIndex. There are 2 sensible requirements to make your data more usable: Make your investment fund names unique. This is trivial. Convert your Excel grouping to an additional column which indicates the parent of the row. In the below example, these 2 requirements are assumed. Setup from collections import defaultdict from functools import reduce import operator import pandas as pd df = pd.DataFrame({'name': ['Simpson Family', 'Marge Simpson', 'Maggies College Fund', 'MCF Investment 2', 'MS Investment 1', 'MS Investment 2', 'MS Investment 3', 'Homer Simpson', 'HS Investment 1', 'HS Investment 3', 'HS Investment 2', 'Griffin Family', 'Lois Griffin', 'LG Investment 2', 'LG Investment 3', 'Brian Giffin', 'BG Investment 3'], 'Value': [600, 450, 100, 100, 100, 200, 50, 150, 100, 50, 0, 200, 150, 100, 50, 50, 50], 'parent': ['Families', 'Simpson Family', 'Marge Simpson', 'Maggies College Fund', 'Marge Simpson', 'Marge Simpson', 'Marge Simpson', 'Simpson Family', 'Homer Simpson', 'Homer Simpson', 'Homer Simpson', 'Families', 'Griffin Family', 'Lois Griffin', 'Lois Griffin', 'Griffin Family', 'Brian Giffin']}) Value name parent 0 600 Simpson Family Families 1 450 Marge Simpson Simpson Family 2 100 Maggies College Fund Marge Simpson 3 100 MCF Investment 2 Maggies College Fund 4 100 MS Investment 1 Marge Simpson 5 200 MS Investment 2 Marge Simpson 6 50 MS Investment 3 Marge Simpson 7 150 Homer Simpson Simpson Family 8 100 HS Investment 1 Homer Simpson 9 50 HS Investment 3 Homer Simpson 10 0 HS Investment 2 Homer Simpson 11 200 Griffin Family Families 12 150 Lois Griffin Griffin Family 13 100 LG Investment 2 Lois Griffin 14 50 LG Investment 3 Lois Griffin 15 50 Brian Giffin Griffin Family 16 50 BG Investment 3 Brian Giffin Step 1 Define a child -> parent dictionary and s…

http://stackoverflow.com/comment/86681731
has text: Okay, I never assign the filter result in a variable. Thank you!
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49833241
type: AnswerComment

http://stackoverflow.com/q/49871071
duplicate of: http://stackoverflow.com/q/18296755
has answer: http://stackoverflow.com/a/49871180
has body: I am having trouble understanding how the following code finds the key with maximum value in a dictionary. I know first parameter i.e my_dict.keys() returns a list of keys. But I am not getting about 2nd parameter.. Help me out key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
possible better answer: http://stackoverflow.com/a/49871180
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86757363
upvote count: 1
downvote count: 1
has title: How to find maximum valued key in dictionary in Python
accepted answer: http://stackoverflow.com/a/49871144
has comment: http://stackoverflow.com/comment/86757602
favorite count: 0
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/18296755
has comment: http://stackoverflow.com/comment/86757432
has answer: http://stackoverflow.com/a/49871144
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/49807452
has answer: http://stackoverflow.com/a/49807570
tagged with: python
tagged with: visual-studio-2017
score: 0
has title: Python Support for Windows 7 in Visual Studio 2017
tagged with: installation
answer count: 1
has body: I have 2 options here: I can go to Python's website and select the link that says python for windows and download the language from there, and then use any supported compiler-interpreter linker and debugger for it. The other alternative is I can choose Python Deployment from Visual Studio's 2017 Installer. The current version in the Visual Studio installer for Python is 3.6.3 which I'm fairly sure that if I install it into Visual Studio and there are any updates Visual Studio will let me know. If I choose to download Python from their website there newest version is 3.6.5. I'm not too concerned about the differences in the versions. I just need to have a working version of the language with a supported compiler - interpreter... Is there any major difference from choosing the one over the other? I read through the MS docs about their tools for Visual Studio on Python and they do claim that if you already have it installed there is no need to check the boxes to install the core language through their installer as it will automatically detect if you have Python installed. For Windows 7 and Visual Studio 2017 which is more preferable: downloading Python from their website directly and then integrating it into Visual Studio; or just letting Visual Studio install its version for me? I am new to python; but I need a working version of it in order to build binaries for MPIR - MPFR - MPFRCPP. The reason I asked is if I chose to install all the available options under Visual Studio it is about 18GB in size which would include Python's tools and different versions of Anaconda. However the Visual Studio documents also stated if you decide to use Python for Data Science to also select the Data Science &amp; Analytical Applications from the workloads section. This would add about another 2GB. This would take some time to download and install postponing any and all of my project developments. I just want to know what I'm in store for and what is the better of my two options.
type: Question
tagged with: windows-7
type: UnansweredQuestion

http://stackoverflow.com/a/49823298
downvote count: 0
has body: response.content is the raw contents of the request. They are not decoded it or anything, it's just the raw bytes. What you want to use instead is the response.text attribute, which contains the decoded content as a string. (You also probably want to use an html parsing library like BeautifulSoup instead of your current page.find approach)
score: 3
answers question: http://stackoverflow.com/q/49823053
type: Answer
upvote count: 3

http://stackoverflow.com/comment/86694242
comment on: http://stackoverflow.com/q/49832053
score: 0
type: QuestionComment
has text: Has anyone tried tout use a regex as separator ? `sep=r"\s+"`
type: Comment

http://stackoverflow.com/q/49868267
type: Question
has comment: http://stackoverflow.com/comment/87172584
has comment: http://stackoverflow.com/comment/86832103
has comment: http://stackoverflow.com/comment/86783336
tagged with: qlistwidget
has comment: http://stackoverflow.com/comment/87168972
has comment: http://stackoverflow.com/comment/86815319
has body: Why do my listwidget items disappear sometimes when i resize the dialog? Before: After: import os, sys, json sys.path.append('Z:\\pipeline\\site-packages') from PySide import QtGui, QtCore, QtSvg ################################################################################ # Custom Widgets ################################################################################ class LayerWidget(QtGui.QWidget): def __init__(self): super(LayerWidget, self).__init__() # controls self.ui_thumbnail = QtGui.QToolButton() self.ui_thumbnail.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) self.ui_thumbnail.setFixedSize(128,128) self.ui_thumbnail.setIconSize(QtCore.QSize(80,80)) self.ui_thumbnail.setText('TITLE HERE') self.ui_profiles = QtGui.QComboBox() self.ui_profiles.addItems(['Item 1','Item 2','Item 3']) # layout main_layout = QtGui.QVBoxLayout() main_layout.setContentsMargins(0,0,0,0) main_layout.setSpacing(0) main_layout.addWidget(self.ui_thumbnail) main_layout.addWidget(self.ui_profiles) main_layout.addStretch() self.setLayout(main_layout) class LayerManager(QtGui.QWidget): def __init__(self): super(LayerManager, self).__init__() self.resize(400, 500) self.ui_layers = QtGui.QListWidget() self.ui_layers.setViewMode(QtGui.QListWidget.IconMode) self.ui_layers.setResizeMode(QtGui.QListWidget.Adjust) self.ui_layers.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.ui_layers.setMovement(QtGui.QListView.Static) self.ui_layers.setIconSize(QtCore.QSize(96,96)) self.ui_layers.setSpacing(10) main_layout = QtGui.QVBoxLayout(self) main_layout.addWidget(self.ui_layers) def add_new_layers(self): for x in range(4): widget = LayerWidget() item = QtGui.QListWidgetItem() self.ui_layers.insertItem(self.ui_layers.count(), item) self.ui_layers.setItemWidget(item, widget) item.setSizeHint(widget.sizeHint()) ################################################################################ # Main Window ###############################################################################…
tagged with: layout
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/41621354
has comment: http://stackoverflow.com/comment/86786377
has comment: http://stackoverflow.com/comment/86786089
tagged with: resize
tagged with: python
has comment: http://stackoverflow.com/comment/86792622
has comment: http://stackoverflow.com/comment/86753417
has comment: http://stackoverflow.com/comment/86794392
has comment: http://stackoverflow.com/comment/86792567
has comment: http://stackoverflow.com/comment/86828430
score: 0
has comment: http://stackoverflow.com/comment/86753559
has comment: http://stackoverflow.com/comment/86827264
answer count: 0
tagged with: pyside
has comment: http://stackoverflow.com/comment/86762130
has comment: http://stackoverflow.com/comment/86786923
upvote count: 1
has comment: http://stackoverflow.com/comment/86752733
has title: QListWidget items disappear in icon view mode when resizing window
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/86679889
score: 0
comment on: http://stackoverflow.com/q/49831917
has text: Your model has very few layers, so there is not a lot of work for the GPU to do for each batch of data. This can be one reason why you are not seeing higher GPU utilization.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49793298
has answer: http://stackoverflow.com/a/49793506
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49793843
downvote count: 0
tagged with: primes
favorite count: 0
has comment: http://stackoverflow.com/comment/86600897
has title: prime generator in python up to 20
has comment: http://stackoverflow.com/comment/86601215
tagged with: python
score: 4
type: Question
upvote count: 4
has body: I don't understand why this (python) code does not produces the primes between 1 and 20. P = [2, 3] p = 4 N = list(range(2, p)) M = list(range(1, p)) while True: for n in N: if p / n in M: p += 1 if p == 20: print(P) break else: P.append(p) p += 1 if p == 20: print(P) break The idea was to start with 4 and check if division between the number and another (smaller) is a hole number, if it is, put it in a list and in the end print the list. instead of printing the primes it printed. [2, 3, 5, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] I know this is a very unproductive way of finding primes but I still don't understand why this is not working. Thanks and sorry for my English.
answer count: 2
has comment: http://stackoverflow.com/comment/86601197
has comment: http://stackoverflow.com/comment/86601376

http://stackoverflow.com/comment/86773907
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49879111
type: Comment
has text: What code have you tried?

http://stackoverflow.com/q/49794899
answer count: 2
has title: flask-sqlalchemy delete query failing with "Could not evaluate current criteria in Python"
downvote count: 0
has answer: http://stackoverflow.com/a/52325828
has answer: http://stackoverflow.com/a/54271540
has comment: http://stackoverflow.com/comment/86604210
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
favorite count: 0
type: Question
has body: I have a query using flask-sqlalchemy in which I want to delete all the stocks from the database where there ticker matches one in a list. This is the current query I have: Stock.query.filter(Stock.ticker.in_(new_tickers)).delete() Where new_tickers is a list of str of valid tickers. The error I am getting is the following: sqlalchemy.exc.InvalidRequestError: Could not evaluate current criteria in Python: "Cannot evaluate clauselist with operator &lt;function comma_op at 0x1104e4730&gt;". Specify 'fetch' or False for the synchronize_session parameter.
has comment: http://stackoverflow.com/comment/86604956
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86605101
tagged with: python
score: 42
linked to: http://stackoverflow.com/q/14929061
upvote count: 42

http://stackoverflow.com/q/49779995
has title: Python: How can I disable add-ins in Outlook and Excel?
has comment: http://stackoverflow.com/comment/86576142
tagged with: outlook-addin
tagged with: python
has comment: http://stackoverflow.com/comment/86575736
score: 0
answer count: 3
has body: I have some add-ins that load on start up. I can't disable this from happening as I don't have administrator rights. I am writing a program that opens outlook and sends emails, but it is slowed down by these add ins. Is there a way to programmatically disable add-ins after opening outlook using python (e.g. using the win32com package)? I need to do the same thing for Excel too. Any advice would be appreciated.
has answer: http://stackoverflow.com/a/49780058
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49780598
tagged with: excel-addins
tagged with: excel
type: Question
has answer: http://stackoverflow.com/a/49780235
tagged with: outlook

http://stackoverflow.com/comment/87027556
score: 0
has text: I've updated the code to fix the problem you were having.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49845100

http://stackoverflow.com/comment/86653506
score: 0
comment on: http://stackoverflow.com/q/49819194
type: Comment
has text: There are 4 in this example -it's all stripped down, but there will probably be a lot of others. I don't have them all added yet, so I could produce them in whatever format works best really. Eventually, I'll probably need to use some form of configuration file for the starting conditions - but that's a bit of a way off yet.
type: QuestionComment

http://stackoverflow.com/a/49826415
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86676910
has comment: http://stackoverflow.com/comment/86668834
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49826305
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49826305
has body: # Create Class class Player: def greating(self): print 'Hello!' # List to store instanses l = [] for i in range(4): l.append(Player()) # Call Instance #1 methods l[0].greating() Here we have a player class and 4 instances from this class stored in l list.

http://stackoverflow.com/a/49787948
upvote count: 1
has comment: http://stackoverflow.com/comment/86591037
has comment: http://stackoverflow.com/comment/86592674
has body: I can run your code on Ubuntu 16.04 without any problems.I think this is Windows signal handlers problem.Windows does not have signals and resolves if your code should exit in a different manner for console and GUi programs .Read more console control handdlers
has comment: http://stackoverflow.com/comment/86590962
has comment: http://stackoverflow.com/comment/86608689
score: 1
has comment: http://stackoverflow.com/comment/86604657
answers question: http://stackoverflow.com/q/49787794
downvote count: 0
type: Answer

http://stackoverflow.com/a/49873150
answers question: http://stackoverflow.com/q/49866366
has comment: http://stackoverflow.com/comment/86761554
score: 0
has body: As eyllanesc was suggesting, some packages were missing for the project local interpreter (maybe the term is wrong). Installing the packages via pyCharm File | Setting | Project Interpreter, solved the issue. Has to install kivi dependencies (sdl2,glew) as well as Pillow.
type: Answer

http://stackoverflow.com/a/49762921
type: Answer
score: 0
has body: I've solved it with the following filter:
answers question: http://stackoverflow.com/q/49760763

http://stackoverflow.com/comment/86738964
comment on: http://stackoverflow.com/q/49861900
score: 0
has text: The issue seems to be with the connection. This is a stupid question, but are you sure that the machine has internet? Could it be that the firewall is blocking this connection? I'd suggest downloading it and then running the setup.py
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49823312
type: AnsweredQuestion
has title: How to design a multithreaded elevator system and handle concurrency?
has comment: http://stackoverflow.com/comment/86663251
upvote count: 2
has comment: http://stackoverflow.com/comment/86663510
score: 1
tagged with: multithreading
has comment: http://stackoverflow.com/comment/86663125
answer count: 1
accepted answer: http://stackoverflow.com/a/49839289
downvote count: 1
has comment: http://stackoverflow.com/comment/86671182
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86663821
has body: I want to write a multithreaded program for an elevator system. The elevator system can only move if the state is running or wait state. In the system, the instruction (which floor to go to) can be added in a multithreaded way. For managing the queue of instruction and getting the next stop for the lift, I have written a QueueManager class. I am not able to figure out how to implement the QueueManager. The problem is I can't get my head around writing the QueueManager. Especially in figuring out how to get the next stop for the Lift from the queue. Here's my implementation for the system in python3: """Implementation of a lift System""" from enum import Enum from typing import TypeVar from threading import Thread import queue LiftType = TypeVar('LiftType', bound='Lift') QueueManagerType = TypeVar('QueueManagerType', bound='QueueManager') SensorNameType = TypeVar('SensorNameType', bound='SensorName') DirectionType = TypeVar('DirectionType', bound='DirectionType') class SensorName(Enum): weight = 'weight' smoke = 'smoke' class Direction(Enum): up = 1 down = -1 class State(Enum): running = 'running' wait = 'waiting' stop = 'stop' class Lift: def __init__(self, num_floors: int, queue_manager: QueueManagerType): """ Contains all the properties of lift """ self.num_floors = num_floors self.curr_direction = Direction.up self.state = State.running self.curr_floor = 0 self.queue_manager = queue_manager def move(self): """ Moves the lift according to the instruction """ if self.state in [State.running, State.wait]: if self.queue_manager.has_instruction(): self.state = State.running stop = self.queue_manager.next_stop(self.curr_direction, self.curr_floor) if stop: print(stop) else: if self.curr_direction == Direction.up: self.curr_direction = Direction.down stop = self.queue_manager.next_stop(self.curr_direction, self.curr_floor) print(stop) else: self.curr_direction = Direction.up else: self.state = State.wait def add_instruction(self, floor, direction=None): """Adds the inst…
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86662859
has comment: http://stackoverflow.com/comment/86663399
has comment: http://stackoverflow.com/comment/86664194
has comment: http://stackoverflow.com/comment/86670940
tagged with: python
has comment: http://stackoverflow.com/comment/86663219
has answer: http://stackoverflow.com/a/49839289

http://stackoverflow.com/q/49855404
accepted answer: http://stackoverflow.com/a/49858193
score: 2
upvote count: 2
has body: While working to implement a paper (Dialogue Act Sequence Labeling using Hierarchical encoder with CRF) using Keras, I need to implement a specific Bidirectional LSTM architecture. I have to train the network on the concept of a Conversation. Conversations are composed of Utterances, and Utterances are composed of Words. Words are N-dimensional vectors. The model represented in the paper first reduces each Utterance to a single M-dimensional vector. To achieve this, it uses a Bidirectional LSTM layer. Let's call this layer A. (For simplicity, let's assume that each Utterance has a length of |U| and each Conversation has a length of |C|) Each Utterance is input to a Bi-LSTM layer with U timesteps, and the output of the last timestep is taken. The input size is (|U|, N), and the output size is (1, M). This Bi-LSTM layer should be applied separately/simultaneously to each Utterance in the Conversation. Note that, since the network takes as input the entire Conversation, the dimensions for a single input to the network would be (|C|, |U|, N). As the paper describes, I intend to feed each utterance (i.e. each (|U|, N)) of that input and feed it to a Bi-LSTM layer with |U| units. As there are |C| Utterances in a Conversation, this implies that there should be a total of |C| x |U| Bi-LSTM units, grouped into |C| different partitions for each Utterance. There should be no connection between the |C| groups of units. Once processed, the output of each of those C groups of Bidirectional LSTM units will then be fed into another Bi-LSTM layer, say B. How is it possible to feed specific portions of the input only to specific portions of the layer A, and make sure that they are not interconnected? (i.e. the portion of Bi-LSTM units used for an Utterance should not be connected to the Bi-LSTM units used for another Utterance) Is it possible to achieve this through keras.models.Sequential, or is there a specific way to achieve this using Functional API? Here is what I have tried so …
answer count: 1
has answer: http://stackoverflow.com/a/49858193
downvote count: 0
has comment: http://stackoverflow.com/comment/86726540
tagged with: keras
has comment: http://stackoverflow.com/comment/86730448
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86729934
has comment: http://stackoverflow.com/comment/86731950
has comment: http://stackoverflow.com/comment/86726457
tagged with: python
has title: Keras Bidirectional LSTM - Layer grouping
tagged with: lstm
type: AnsweredQuestion
tagged with: deep-learning

http://stackoverflow.com/comment/86550973
score: 0
has text: On which element you are trying to click ?
comment on: http://stackoverflow.com/q/49767561
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49823876
tagged with: ansible
answer count: 1
type: Question
has title: Ansible Playbook Retry Logic Using Python API
has body: Using the Ansible 2 Python API I'm able to run playbooks and handle results with a custom callback handler (thanks to this question). Everything works well, but now I'd like to implement a simple retry loop for the PlaybookExecutor. All my callback handler is doing is stuffing any failed tasks in an array, and if I see that the array isn't empty count it as a failure and try again. I have another python module that uses this script to kick off the playbook. The call to run_playbook is nested in a try/except block and I'd like an exception to bubble up so I can properly handle the failure. I'd like to give my playbook 3 attempts at running and if all fail then raise an exception. Here is my code: #! /usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function import logging import os from collections import namedtuple from ansible.parsing.dataloader import DataLoader from ansible.vars.manager import VariableManager from ansible.inventory.manager import InventoryManager from ansible.executor.playbook_executor import PlaybookExecutor from ansible.plugins.callback import CallbackBase class ResultsCallback(CallbackBase): """ A callback plugin used for performing an action as results come in """ def __init__(self): super(ResultsCallback, self).__init__() # Store all failed results self.failed = [] def v2_runner_on_failed(self, result, ignore_errors=False): if ignore_errors: self._display.display("...ignoring", color=C.COLOR_SKIP) host = result._host self.failed.append(result.task_name) def create_inventory_file(hostnames): inv_file = 'ansible_hosts.{0}'.format(os.getppid()) logging.print('\nCreating Ansible host file: {0}/{1}'.format(os.path.join(os.path.expanduser('~')), inv_file)) with open(os.path.join(os.path.expanduser('~'), inv_file), 'w') as host_file: # If ec2, stuff into an '[ec2]' group. # Otherwise don't use a group header if 'ec2' in hostnames[0]: host_file.write('[ec2]\n') for host in hostnames: host_file.write('{0}\n'.format(host)) return os…
tagged with: python
accepted answer: http://stackoverflow.com/a/49879588
tagged with: ansible-2.x
has answer: http://stackoverflow.com/a/49879588
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/35019916

http://stackoverflow.com/comment/86703613
comment on: http://stackoverflow.com/q/49843280
type: Comment
type: QuestionComment
has text: 2018-04-10 04:10:45 looks ok so please print row[3] in your python code to confirm it is the value assign to date column.
score: 0

http://stackoverflow.com/comment/86610264
has text: I'm afraid I don't have any other suggestions. Hope you manage to get it to work
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49793919

http://stackoverflow.com/q/49888332
linked to: http://stackoverflow.com/q/2958684
tagged with: python
has comment: http://stackoverflow.com/comment/87362839
score: 0
has comment: http://stackoverflow.com/comment/86792837
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86792859
downvote count: 1
tagged with: operator-precedence
has comment: http://stackoverflow.com/comment/86792933
has body: print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 Don't you have to do % second after /, +, and -? Ex. 3 + 2 + 1 - 5 + (0) - (.25) + 6 = 6.75 Does Python round up to the nearest whole number?
favorite count: 0
has title: What is the order of operations in Python?
type: Question
has comment: http://stackoverflow.com/comment/86792813
type: UnansweredQuestion

http://stackoverflow.com/comment/86592936
comment on: http://stackoverflow.com/q/49788801
has text: abccd, if there are any experienced geany users here I'm hoping they can help me solve this problem. It seems like a simple thing to set up but it's not working.
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/49830050
type: Question
accepted answer: http://stackoverflow.com/a/49830220
has comment: http://stackoverflow.com/comment/86675298
has title: getting svchost path by PID using python 2.7
has body: i am trying to get svchost.exe path by PID using python. i tried it using psutil but i got access denied error. here is my code- import psutil p = psutil.Process(1832) print p.exe()
tagged with: windows
tagged with: python
tagged with: psutil
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49830220
has comment: http://stackoverflow.com/comment/86675319
answer count: 1

http://stackoverflow.com/a/49844955
has body: You missed to add the value for cell sheet.cell (row=1,column=x+1).value = Try like this from openpyxl import * book = Workbook () sheet = book.active sheet.title = "test" for x in range (7): sheet.cell (row=1,column=x+1).value = "Hello" book.save ('test.xlsx')
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49844925

http://stackoverflow.com/comment/86601376
comment on: http://stackoverflow.com/q/49793298
score: 0
has text: I forgot to say, instead of printing the primes it printed: [2, 3, 5, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49870254
accepted answer: http://stackoverflow.com/a/49870388
has comment: http://stackoverflow.com/comment/86755866
answer count: 1
has comment: http://stackoverflow.com/comment/86756583
favorite count: 0
type: Question
tagged with: python-3.x
has title: wxPython method "takes 1 positional argument but 2 were given" on self.Bind
has answer: http://stackoverflow.com/a/49870388
downvote count: 0
tagged with: wxpython
tagged with: python
has comment: http://stackoverflow.com/comment/86756103
has body: I'm trying to write a gui in WxPython, but I can't seem to figure out how to bind methods to events. Here is my current code: class nlp_gui_class(wx.Frame): def __init__(self, *args, **kw): # ensure the parent's __init__ is called super(nlp_gui_class, self).__init__(*args, **kw) self.file_menu = wx.Menu() self.setting_menu = wx.Menu() self.menubar = None self.filenames = [] self.createMenuBar() self.createFileMenu() self.CreateStatusBar() self.SetStatusText("Corpus linguistics in Python") def createFileMenu(self): OPEN_FILE_ID = 101 open_file_item = self.file_menu.Append(OPEN_FILE_ID, "Open File(s)", "Open file(s)") about_item = self.file_menu.Append(wx.ID_ABOUT, "About", "About") self.file_menu.Append(wx.ID_EXIT, "Exit", "Close") self.Bind(wx.EVT_MENU, self.open_files, open_file_item) def createMenuBar(self): menuBar = wx.MenuBar() menuBar.Append(self.file_menu, "File") # Adding the "file_menu" to the MenuBar self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. def open_files(self): openFileDialog = wx.FileDialog(frame, "Choose corpus files", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE) openFileDialog.ShowModal() self.filenames.extend(openFileDialog.GetPaths()) openFileDialog.Destroy() app = wx.App() # Setting up the menu. frame = nlp_gui_class(None, -1, 'nlp_gui') frame.SetSize(0, 0, 200, 50) # Creating the menubar. frame.Show() app.MainLoop() When I run the program, The frame and menu look like what I expect. However, as soon as I click the menu item "Open File(s)", I get this error: TypeError: open_files() takes 1 positional argument but 2 were given It seems that some extra parameter is being passed when the menu item is being clicked, but I don't know what that item is and how I modify my code so that it runs correctly (i.e., the function is called successfully). What do I need to change here? Edit: thanks to Patrick Artner for his solution. That solved the problem I posted about, and then I realized I had also called wx.FileDialog incor…
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: wxwidgets
tagged with: typeerror

http://stackoverflow.com/q/49906207
tagged with: flask
has title: Can't resolve outer reference to global variable because of inner reference
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49909014
accepted answer: http://stackoverflow.com/a/49909014
has body: I Have the following code: l_sortedQueue = sorted(l_queue, key=lambda i: i['priority']) for i, d in enumerate(l_sortedQueue): if d['key'] == some_value: l_queue= l_sortedQueue.insert(n_queue_position, l_sortedQueue.pop(i)) So I'm basically trying to move one of the dictionary entries in l_queue into a new index while shifting all the other values over one but because of how the data is organized in the list, I had to do it this way (sorting the list based on a 'priority' value before moving the item to a new index). For some reason however, when I reference l_queue within the for loop as in this line: l_queue = l_sortedQueue.insert(n_queue_position, l_sortedQueue.pop(i)) The OUTER reference to l_queue becomes unresolved, and the inner reference refers to a new local variable instead of the global list variable. Without this inner reference, it properly references the global variable however. Why is this? How do I get the inner and outer reference to l_queue to reference the global list variable? Not sure if it is relevant, but this code comes from a flask function.
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/q/49911427
possible better answer: http://stackoverflow.com/a/49911644
tagged with: relation
tagged with: python
has answer: http://stackoverflow.com/a/49911644
accepted answer: http://stackoverflow.com/a/49911553
type: Question
has comment: http://stackoverflow.com/comment/86838867
has body: I am trying to write a function so that when given a list of relations I return true or false whether it is antisymmetric or not. if (a,b) is in the relation and (b,a) is in the relation then a has to be equal b i.e. given [["A","A"], ["A","C"], ["A","B"], ["C","C"]] would return true [["A","A"], ["A","D"], ["D","A"]] would return false because both [A,D] and [D,A] are in the relation but are not equal My idea was: def is_antisymmetric(relation): for a, b in relation: if (a,b) in relation and (b,a) in relation and a == b: return True else: return False But this doesn't seem to be working. Any help would be appreciated
has answer: http://stackoverflow.com/a/49911553
score: 0
tagged with: list
answer count: 2
has title: Determine whether a list is antisymmetric
has comment: http://stackoverflow.com/comment/86838854
upvote count: 1
has comment: http://stackoverflow.com/comment/86838861
has comment: http://stackoverflow.com/comment/86838857
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86838815

http://stackoverflow.com/comment/86615275
has text: It seems there is no data lower than ~300 or above 1000. So that is missing. Of course you could let the histogram be generated over the whole range of data you're interested in. Or you could colorize the background the same as the lowest colormap color.
score: 0
comment on: http://stackoverflow.com/q/49795655
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49851668
has comment: http://stackoverflow.com/comment/86749385
has answer: http://stackoverflow.com/a/49877166
tagged with: pip
upvote count: 1
tagged with: python
has title: PIP fatal error
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86745033
has comment: http://stackoverflow.com/comment/86718081
has comment: http://stackoverflow.com/comment/86721134
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86721043
favorite count: 0
has body: I get a fatal error when using pip install. pip install praw Fatal error in launcher: Unable to create process using '""c:\program files\python36\python.exe" "C:\Program Files\Python36\Scripts\pip.exe" install praw' But when i do the samething but with Python in beginning, it works they way as it used to when using just pip install. python -m pip install praw I have no idea whats causing this issue and I'm not sure how to fix this. Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe"" gives a workaround and not a fix.
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/24627525
has comment: http://stackoverflow.com/comment/86720703
accepted answer: http://stackoverflow.com/a/49877166

http://stackoverflow.com/a/49863378
type: Answer
has comment: http://stackoverflow.com/comment/86742862
answers question: http://stackoverflow.com/q/49863276
downvote count: 0
score: 1
upvote count: 1
has body: Try this : def split(arr, size): return [x[i:i+size] for i in range(0,len(x)-size+1)]

http://stackoverflow.com/a/49900723
score: 5
has comment: http://stackoverflow.com/comment/86818141
has body: If you want to use to_sorted_list you need to remap the list you obtain in a single element. Changing your main function to: def main(): thread_1_scheduler = ThreadPoolScheduler(1) thread = ExternalDummyService() external_obs = thread.subject.publish() external_obs \ .flat_map(lambda msg: Observable.just(msg).subscribe_on(thread_1_scheduler)) \ .to_sorted_list(key_selector=lambda msg: msg.timestamp) \ .flat_map(lambda msglist: Observable.from_iterable(msglist)) \ .scan(seed=State(0, None), accumulator=slow_scan_msg) \ .subscribe(log, print, lambda: print("SLOW FINISHED")) external_obs.connect() thread.start() gives: &gt;emitting Msg(count=0, timestamp=18.924474716186523) &gt;emitting Msg(count=1, timestamp=4.669189453125) &gt;emitting Msg(count=2, timestamp=18.633127212524414) &gt;emitting Msg(count=3, timestamp=15.151262283325195) &gt;emitting Msg(count=4, timestamp=14.705896377563477) &gt;SLOW st.count=0 last_msg.counter=1 ts=4.67 &gt;SLOW st.count=1 last_msg.counter=4 ts=14.71 &gt;SLOW st.count=2 last_msg.counter=3 ts=15.15 &gt;SLOW st.count=3 last_msg.counter=2 ts=18.63 &gt;SLOW st.count=4 last_msg.counter=0 ts=18.92 &gt;SLOW FINISHED Note that the to_sorted_list method will wait for the end of the subject stream to start scanning, so you cannot use it to implement your marble diagram as it shown in the question. To properly implement it, I think you would need something like onBackpressureBuffer which is implemented in RxJava but not in RxPy. This wouldn't solve entirely the issue as the buffer is FIFO (first in first out) and you want a custom way of chosing which message goes out first. This may require a tweak on how the request to the buffer are handled. You may find a better way to progress towards a solution with a extension of RxPy called rxbackpressure, particularly with its class dequeuablebuffer.py that you may be able to adapt to suit your needs.
answers question: http://stackoverflow.com/q/49803754
type: Answer
has comment: http://stackoverflow.com/comment/86820985
has comment: http://stackoverflow.com/comment/86819897
has comment: http://stackoverflow.com/comment/86819273
has comment: http://stackoverflow.com/comment/86819094
has comment: http://stackoverflow.com/comment/86820240
accepted answer of: http://stackoverflow.com/q/49803754
has comment: http://stackoverflow.com/comment/86819579
has comment: http://stackoverflow.com/comment/86817936
has comment: http://stackoverflow.com/comment/86817371
downvote count: 0
has comment: http://stackoverflow.com/comment/86817070
has comment: http://stackoverflow.com/comment/86816875
type: AcceptedAnswer
upvote count: 5

http://stackoverflow.com/q/49843017
tagged with: command-line-interface
favorite count: 0
type: Question
has title: How to call python click from from python?
tagged with: python-click
type: UnansweredQuestion
has body: Correct me if I'm wrong, but it seem that click decorators obscure the function default and construction. Call the wrapped from from the REPL does not immediately work in the same way as the REPL. For example see this from dask distributed: @click.option('--bokeh-prefix', type=str, default=None, help="Prefix for the bokeh app") @click.option('--preload', type=str, multiple=True, is_eager=True, help='Module that should be loaded by each worker process ' 'like "foo.bar" or "/path/to/foo.py"') @click.argument('preload_argv', nargs=-1, type=click.UNPROCESSED, callback=validate_preload_argv) def main(scheduler, host, worker_port, listen_address, contact_address, nanny_port, nthreads, nprocs, nanny, name, memory_limit, pid_file, reconnect, resources, bokeh, bokeh_port, local_directory, scheduler_file, interface, death_timeout, preload, preload_argv, bokeh_prefix, tls_ca_file, tls_cert, tls_key): Is there some simple pattern to get at the function and all its defaults?
tagged with: python
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/49958813
tagged with: read-eval-print-loop
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/86822802
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49892500
type: QuestionComment
has text: I have added the example @shahaf

http://stackoverflow.com/q/49902525
type: Question
has comment: http://stackoverflow.com/comment/86862224
answer count: 2
has comment: http://stackoverflow.com/comment/86821386
has comment: http://stackoverflow.com/comment/86821352
has comment: http://stackoverflow.com/comment/86821327
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49916261
tagged with: python
has title: loading a file in Python. Make string raw
score: 0
has answer: http://stackoverflow.com/a/49904145
has comment: http://stackoverflow.com/comment/86820720
has comment: http://stackoverflow.com/comment/86820670
has body: I would like to load a file in Python using a certain package. The load function of the package needs to know the filename (+ extension) and location. Like this: package.load(os.path.join(my_directory_name, r'my_filename.xml')) My situation is that I get the filename out of a pandas dataframe. I then add the correct extension, which is xml and I then try to load the file. import os import pandas as pd package.load(os.path.join(directory_name, df['filename'] + '.xml')) I get an error: No such file in directory. The problem is that the r is not there. It should be in front of the string. How to I make the string df['filename] + '.xml' raw? Python is interpreting backslashes as special characters, but I want them to mean actual backslashes.
tagged with: load
has comment: http://stackoverflow.com/comment/86820916

http://stackoverflow.com/comment/86774840
comment on: http://stackoverflow.com/q/49801891
type: Comment
type: QuestionComment
has text: I have the same problem. I am importing keras as follows from tensorflow import keras from keras.models import Sequential model = Sequential() etc. then it fails on this line: estimator_model = keras.estimator.model_to_estimator(keras_model=kerasModel()) error: AttributeError: 'Sequential' object has no attribute '_is_graph_network' I am using tensorflow 1.7
score: 1

http://stackoverflow.com/q/49822699
has comment: http://stackoverflow.com/comment/86661213
type: Question
type: UnansweredQuestion
has body: I'm coding in python. In my work, I have a certain parameter for which there are multiple possible values, as well some data X with associated binary target values y. For each of the parameter's values, I run some classification algorithm (eg.: Naive Bayes) using scickit-learn on X and y. In this step, we use cross validation, doing an 80:20 train-test split on our dataset across some number of folds, and average the results. This yields a score (the area under the precision recall curve) for each parameter value, and we pick the one with highest score to be our preferred parameter value for this classifier. We would then like to train the algorithm using all of the data X, rather than just 80% of it, obtaining some decision function f which we'll use for making predictions. These decision functions return probability or numerical values that indicate 'how sure' the algorithm is a certain sample belongs to a certain class; they don't properly predict a class for a sample. This is done with threshold values t: samples for which the numerical value is less than t are assigned the class 0, and the rest of the sampels are assigned the class 1. When we have the true labels, these predictions can be tested against the true labels to make evaluations (like precision and recall) about the prediction. Varying the value of t is precisely what generates the multiple points in Precision-Recall space, allowing us to plot a curve (and hence calculate the area under it) for a given model. We did this for each fold in our cross validation. Now, we have some data Z to which we can apply f, but we don't have the labels. How can we choose an appropriate value of t for our model? More specifically, consider the models generated during the cross-validation (for the same preferred parameter value). Each such model has a corresponding decision function, and hence a corresponding precision-recall curve with associated threshold values. Given a point p_0 in one of these curves, and hence an…
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/86661124
answer count: 0
has comment: http://stackoverflow.com/comment/86663009
tagged with: precision-recall
has title: Binary classification, precision-recall curve and thresholds
tagged with: machine-learning
tagged with: scikit-learn

http://stackoverflow.com/comment/86747724
type: AnswerComment
comment on: http://stackoverflow.com/a/49866022
score: 1
type: Comment
has text: it really depends on the naming of your nodes, but since even in this simple example you already have (id - name) and (id - value) combinations, there is not easy way of looping over this stuff. You need to look for the right combinations by hand, or risk not finding the right stuff.

http://stackoverflow.com/comment/86846877
type: Comment
comment on: http://stackoverflow.com/a/49897146
type: AnswerComment
score: 0
has text: I don't think that problem is `"""` - it seem like an inconsistent usage of single quotes...

http://stackoverflow.com/comment/86937324
has text: Hi, the manual step is just press shift and F2 at the same time in the browser and the dev tools will pop out
comment on: http://stackoverflow.com/q/49912262
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49768750
upvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/86553023
has comment: http://stackoverflow.com/comment/86552829
downvote count: 1
has comment: http://stackoverflow.com/comment/86552704
favorite count: 0
has comment: http://stackoverflow.com/comment/86552720
tagged with: python
score: -1
has body: I was a little curious because when I add a single line in my code, that counts the number of rows in the csv file, the for loop is stop working and just skipping everything inside. My code shown below, is working now, but if I uncomment the row_count it's not working, so my question is why? with open(r"C:\Users\heltbork\Desktop\test\ICM.csv", newline='') as csvfile: sensor = csv.reader(csvfile, delimiter=',', quotechar='|') #row_count = sum(1 for row in sensor) #print(row_count) for row in sensor: #alot of stuff here
type: Question
has title: Skipping for loop in python csv.reader, for row in
has answer: http://stackoverflow.com/a/49768836

http://stackoverflow.com/comment/86709200
score: 0
has text: Code is important, please give us something that illustrates your problem so we can better understand your particular situation.
type: Comment
comment on: http://stackoverflow.com/q/49847153
type: QuestionComment

http://stackoverflow.com/comment/86713202
score: 0
has text: It is not under my control.
type: Comment
comment on: http://stackoverflow.com/a/49849297
type: AnswerComment

http://stackoverflow.com/comment/86747347
score: 0
type: Comment
has text: File link is https://drive.google.com/file/d/1O1LaS02fbtFOWlOD8JaIGqrYn47Dobpd/view?usp=sharing
comment on: http://stackoverflow.com/q/49865741
type: QuestionComment

http://stackoverflow.com/comment/88666837
score: 0
has text: I checked it... i had printed the email message on the screen from the variable... copied the same message and pasted in another variable in another code having the same regex... the only issue is that its not working on the email message , but working perfectly if i copied it any other variable.
type: Comment
comment on: http://stackoverflow.com/a/49817969
type: AnswerComment

http://stackoverflow.com/q/49791146
has body: Let's say I have arr = np.arange(6) arr array([0, 1, 2, 3, 4, 5]) and I decide that I want to treat an array "like a circle": When I run out of material at the end, I want to start at index 0 again. That is, I want a convenient way of selecting x elements, starting at index i. Now, if x == 6, I can simply do i = 3 np.hstack((arr[i:], arr[:i])) Out[9]: array([3, 4, 5, 0, 1, 2]) But is there a convenient way of generally doing this, even if x &gt; 6, without having to manually breaking the array apart and thinking through the logic? For example: print(roll_array_arround(arr)[2:17]) should return. array([2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0])
upvote count: 2
has comment: http://stackoverflow.com/comment/86597096
tagged with: arrays
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49791588
has answer: http://stackoverflow.com/a/49791456
possible better answer: http://stackoverflow.com/a/49791456
downvote count: 0
has answer: http://stackoverflow.com/a/49791250
has answer: http://stackoverflow.com/a/49791708
favorite count: 0
accepted answer: http://stackoverflow.com/a/49791708
type: Question
tagged with: numpy
has title: Rolling array around

http://stackoverflow.com/comment/86822687
type: AnswerComment
comment on: http://stackoverflow.com/a/49903431
has text: Sorry, but my question was unclear. I updated it. I wanted to find the padding for cases where the final length needs to be some arbitrary multiple of `N`, where I don't know the multiple. Unfortunately, I've basically invalidated your answer. My apologies.
type: Comment
score: 0

http://stackoverflow.com/q/49896007
tagged with: arrays
has body: My aim is to get a more elegant unpacking of a sub-tuple or sub-list for longer tuples or longer lists. For example, I have an array with sub-arrays s = [['yellow', 1,5,6], ['blue', 2,8,3], ['yellow', 3,4,7], ['blue',4,9,1], ['red', 1,8,2,11]] Experimenting with an array and sub-tuple or sub-list with 2 elements,I have the following: s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] OR s = [['yellow', 1], ['blue', 2], ['yellow', 3], ['blue', 4], ['red', 1]] I can unpack 's' whether it has tuples or lists: for k, v in s: print('k = {0}, v = {1}'.format(k,v)) Produces the result k = yellow, v = 1 k = blue, v = 2 k = yellow, v = 3 k = blue, v = 4 k = red, v = 1 Suppose I have the following array with sub-arrays of four elements each: bongo = [[1, 2, 3, 4], [6, 3, 2, 3], [5, 7, 11, 15], [2, 4, 7, 8]] I can unpack 'bongo' using the variables a,b,c,d for a,b,c,d in bongo: print('a = {0}, b = {1}, c={2}, d={3}'.format(a,b,c,d)) a = 1, b = 2, c=3, d=4 a = 6, b = 3, c=2, d=3 a = 5, b = 7, c=11, d=15 a = 2, b = 4, c=7, d=8 Despite being able to unpack the mixed chr/number sub-array I seem to have a problem unpacking a mixed 'chr' and number sub-list (or sub-tuple (not shown, but get the same result)): s = [['yellow', 1,5,6], ['blue', 2,8,3], ['yellow', 3,4,7], ['blue', 4,9,1], ['red', 1,8,2,11]] That is, doing an unpacking I get the desired result with an error: for a,b,c,d in s: print('a = {0}, b = {1}, c = {2}, d = {3} '.format(a,b,c,d)) a = yellow, b = 1, c = 5, d = 6 a = blue, b = 2, c = 8, d = 3 a = yellow, b = 3, c = 4, d = 7 a = blue, b = 4, c = 9, d = 1 Traceback (most recent call last): File "&lt;pyshell#288&gt;", line 1, in &lt;module&gt; for a,b,c,d in s: ValueError: too many values to unpack (expected 4) My question: Is there a more elegant way of unpacking, such that I would like to get the first element, say as a key, and the rest? To illustrate with pseudo-code - it does not work directly in python: for k[0][0], v[0][1:4] in s: print('k[0…
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49907628
tagged with: tuples
type: AnsweredQuestion
tagged with: list
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49937227
has answer: http://stackoverflow.com/a/49907628
has answer: http://stackoverflow.com/a/49896145
possible better answer: http://stackoverflow.com/a/49896145
type: Question
has title: Python: Unpacking arrays of tuples or of arrays - unpacking more than 2 elements per array or tuple

http://stackoverflow.com/a/49833707
score: 0
answers question: http://stackoverflow.com/q/49808127
type: AcceptedAnswer
has body: "Is fm related to the size of image?" Yes partially (at least in regard of your question), because if you scale an image, you have to interpolate pixel values. Downscaling will not only lose information but create new information by pixel interpolation (if it's not nearest-neighbor interpolation) and thus influence the variance of the resulting image. But this only applies to scaled images, not to images which are different in the first place.
accepted answer of: http://stackoverflow.com/q/49808127
type: Answer

http://stackoverflow.com/comment/86757005
has text: Particularly see the [`nohup` solution by @cizixs](https://stackoverflow.com/a/32861743/850848). In general, this is not a Python nor Paramiko question, but rather a general Linux/SSH/shell question.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49859822

http://stackoverflow.com/q/49889225
linked to: http://stackoverflow.com/q/11692613
has comment: http://stackoverflow.com/comment/86794692
possible better answer: http://stackoverflow.com/a/49889480
has body: What is the most Pythonic way to take a list of dicts and sum up all the values for matching keys from every row in the list? I did this but I suspect a comprehension is more Pythonic: from collections import defaultdict demandresult = defaultdict(int) # new blank dict to store results for d in demandlist: for k,v in d.iteritems(): demandresult[k] = demandresult[k] + v In Python - sum values in dictionary the question involved the same key all the time, but in my case, the key in each row might be a new key never encountered before.
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49889480
answer count: 4
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86794628
upvote count: 3
has comment: http://stackoverflow.com/comment/86794639
has answer: http://stackoverflow.com/a/49889489
accepted answer: http://stackoverflow.com/a/49889308
has comment: http://stackoverflow.com/comment/86794712
downvote count: 1
has answer: http://stackoverflow.com/a/49889308
has title: How to sum a list of dicts
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49889368

http://stackoverflow.com/q/49792820
answer count: 2
tagged with: deep-learning
downvote count: 0
accepted answer: http://stackoverflow.com/a/49823483
score: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49823483
tagged with: python
tagged with: pygame
has title: Error when running a DQN pygame script in Google Colab
tagged with: google-colaboratory
tagged with: jupyter-notebook
has body: When I am running a DQN script using Pygame on Google Colab it is throwing error - pygame.error: No available video device I am trying to run this GitHub repo on Google Colab. pong_neural_network_live Installed the Pygame using following code- import os !git clone https://github.com/ntasfi/PyGame-Learning-Environment.git os.chdir('PyGame-Learning-Environment') !pip install -e . !pip install pygame os.chdir('/content') On trying to initialize and run the following code it import pygame pygame.init() pygame.display.list_modes() I get error: video system not initialized PS: I also enabled third party cookies in Google Chrome.
has answer: http://stackoverflow.com/a/63938150
possible better answer: http://stackoverflow.com/a/63938150
type: AnsweredQuestion

http://stackoverflow.com/a/49789334
answers question: http://stackoverflow.com/q/49788197
type: Answer
has comment: http://stackoverflow.com/comment/86629034
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49788197
has body: Too considerably improve the speed of your program, especially for larger data set. The key is to use a hash table, or a dictionary in Python's term, to store different numbers as the key, and the lines each unique number exist as value. Then in the second pass, merge the lists for each line based on the dictionary and count unique elements. def gen_haplotype_blocks(input): unique_numbers = {} for i, numbers in enumerate(input): for number in numbers: if number in unique_numbers: unique_numbers[number].append(i) else: unique_numbers[number] = [i] output = [[] for _ in range(len(input))] for i, numbers in enumerate(input): for number in numbers: for line in unique_numbers[number]: output[i] += input[line] counts = [len(set(x)) for x in output] return sorted(counts, reverse=True) In theory, the time complexity of your algorithm is O(N*N), N as the size of the input list. Because you need to compare each list with all other lists. But in this approach the complexity is O(N), which should be considerably faster for a larger data set. And the trade-off is extra space complexity.
has comment: http://stackoverflow.com/comment/86665344

http://stackoverflow.com/a/49790157
score: 0
answers question: http://stackoverflow.com/q/49790049
has body: First you define matrix with full range like a = [[0 for i in range(n] for i in range(n)] a[i][j] = any value I hope it's work
type: Answer

http://stackoverflow.com/comment/86713856
comment on: http://stackoverflow.com/q/49849494
score: 0
type: Comment
has text: @pissall I am not sure which data you meant, but if you meant the data for each RDD, I already put up in the writings such as [((u'BibNum', u'ItemCollection', u'CheckoutDateTime'), 1), ((u'1842225', u'namys', u'05/23/2005 03:20:00 PM'), 1)]
type: QuestionComment

http://stackoverflow.com/q/49799549
has comment: http://stackoverflow.com/comment/86617055
type: Question
score: 0
has comment: http://stackoverflow.com/comment/86617798
tagged with: python
has comment: http://stackoverflow.com/comment/86624147
has body: I'm working in Flask and have prevented default with javascript in order to send all the data I need via an AJAX request. The problem now is that my view has all the data (I have confirmed with console outputs) but the front-end will not update with the passed through data. It was working before, but adding in this javascript function broke the application. It also doesn't allow the alert flashed messages to show like it used to on invalid form. Any thoughts? $(document).ready(function(){ // get old values var old_num_components = $("input[name='number_components']:checked").val(); var old_method = $("#method_select").val(); // get new values var new_num_components; var new_method; var data = {'new_num_components':'none','old_num_components':'none', 'new_method':'none','old_method':'none'}; // var data = {}; $("#submit_form_button").click(function(e){ e.preventDefault(); new_num_components= $("input[name='number_components']:checked").val(); data.new_num_components = new_num_components; data.old_num_components = old_num_components; old_num_components=new_num_components; new_method= $("#method_select").val(); //alert(old_method + " : " + new_method); data.new_method = new_method; data.old_method = old_method; old_method=new_method; console.log(data); $.ajax({ type:"POST", url:"{{url_for('similar')}}", data:$("#main_form").serialize()+"&amp;"+$.param(data) }); }); }); EDIT: I have tried reloading the window within the ajax call itself success: function(msg){window.location.reload(true);}
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86630268
has comment: http://stackoverflow.com/comment/86614301
answer count: 1
tagged with: javascript
has comment: http://stackoverflow.com/comment/86622896
has title: Prevent default to send AJAX form data doesn't update front end?
tagged with: jquery
tagged with: flask
has answer: http://stackoverflow.com/a/49807694
accepted answer: http://stackoverflow.com/a/49807694
has comment: http://stackoverflow.com/comment/86621256

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/49776333

http://stackoverflow.com/comment/86663157
comment on: http://stackoverflow.com/q/49823033
score: 5
has text: Rather that specifying the full path, the purpose of the `--use-local` is to go and look at the `conda-bld` folder. I suspect the cause is that you've listed the full path to the file rather than just the name of the package, since full paths to files don't install dependencies. Try with `conda install -n my_env --use-local my_pkg`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50046123
downvote count: 0
has comment: http://stackoverflow.com/comment/87368563
has body: You can use networkx library and graphs: import networkx as nx G = nx.from_pandas_edgelist(df, source='side_a',target='side_b') df2.apply(lambda x: [nx.shortest_path(G, x.side_a,x.end_point)[0], nx.shortest_path(G, x.side_a,x.end_point)[1:]], axis=1) Output: side_a end_point 0 a [b, c] 1 b [c] 2 c [] 3 k [l, m] 4 k [l, n] 5 l [m] 6 l [n] 7 p [q, r, s] 8 q [r, s] 9 r [s]
has comment: http://stackoverflow.com/comment/87144467
has comment: http://stackoverflow.com/comment/87144643
accepted answer of: http://stackoverflow.com/q/49887144
type: Answer
answers question: http://stackoverflow.com/q/49887144
upvote count: 4
score: 4
type: AcceptedAnswer

http://stackoverflow.com/q/49896915
has answer: http://stackoverflow.com/a/49899756
downvote count: 0
tagged with: apscheduler
has answer: http://stackoverflow.com/a/49897064
possible better answer: http://stackoverflow.com/a/49897064
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49899756
has answer: http://stackoverflow.com/a/66027601
answer count: 3
linked to: http://stackoverflow.com/q/9449101
tagged with: cron
score: 1
tagged with: python
has title: APScheduler jobs run several times when jobs are set to be run at the same time
type: AnsweredQuestion
has body: I want to schedule and run jobs using APScheduler and the cron format. from apscheduler.schedulers.background import BackgroundScheduler def test_func(): print("Test job func") scheduler = BackgroundScheduler() today_str = datetime.today().strftime('%Y-%m-%d') today_with_time = datetime.strptime(today_str + " " + "12:07:00", "%Y-%m-%d %H:%M:%S") scheduler.add_job( test_func, "cron", id="test", name="test", day_of_week="2", hour=today_with_time.hour, minute=today_with_time.minute, replace_existing=False) Let's say I do this twice, with two different job IDs. There are two jobs, set to run at the exact same time. With one job, it runs once as expected. With two jobs, it runs 4 times. The same happens with other triggers such as DateTrigger. Note that this is set-up within a Flask app. Normally, the app makes a call to another API to fetch jobs, then schedules them one by one. EDIT: my actual app fetches 3 jobs and schedules them, all at the same time. When I fetch 1 job instead of 3, the bug does not occur. When I have 3 jobs, the function is run 9 times. With 1 job, it is run once.

http://stackoverflow.com/comment/86775837
score: 0
has text: @Alfe: I tried. Where I am stuck is the data (p1,p2,p3,p4) is not constant through out.Like one tuple have p1,p2,p3 other have p4,p5,p6.Had it been same ,I could have easily read the list and first read the index of the string and read the value of the index in list.I actually did this for other data of my project.
comment on: http://stackoverflow.com/q/49879865
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49767087
has body: I want to find out what the total score is that you give each sport in my coding. Just to note that I have previously asked them to enter a state in a different function. STATES = ["California", "New Mexico", "Ohio", "Maryland"] SPORTS = ["Football", "Baseball", "Basketball"] def results(any_state): SCORE = [] STATES.remove("{}" .format(any_state.title())) for i in range(len(STATES)): for j in range(len(SPORTS)): scores = int(raw_input("What do you score {} in {}?".format(SPORTS[j], STATES[i]))) SCORE.append(STATES[i]) SCORE.append(scores) return(SCORE) If California was entered I would like it to end up printing. What do you score Football in New Mexico? What do you score Football in Ohio? What do you score Football in Maryland? You scored Football a total of ____. What do you score Baseball in New Mexico? What do you score Baseball in Ohio? What do you score Baseball in Maryland? You scored Baseball a total of ____. What do you score Basketball in New Mexico? What do you score Basketball in Ohio? What do you score Basketball in Maryland? You scored Basketball a total of ____.
type: Question
has answer: http://stackoverflow.com/a/49767341
type: UnansweredQuestion
tagged with: sum
tagged with: python
tagged with: variables
has answer: http://stackoverflow.com/a/49767278
score: 0
tagged with: list
answer count: 2
has title: Calculating sum of variables

http://stackoverflow.com/a/78446587
score: 4
has comment: http://stackoverflow.com/comment/138308545
has body: import xlsxwriter df.to_excel('abc.xlsx', engine='xlsxwriter')
upvote count: 4
answers question: http://stackoverflow.com/q/49844925
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86695757
comment on: http://stackoverflow.com/a/49826833
score: 0
has text: Well I would imagine you have have a bunch of imports at the top of your code like `import tensorflow as tf`, `import numpy as np` etc. Right after those, before any meaningful code runs, set the random seed.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49783940
answers question: http://stackoverflow.com/q/49773411
has body: You can do it like this as provided by @Aran-Fey in comments: grid = [[char == '0' for _, char in zip(range(width), input())] for _ in range(height)] But it is not reccomended and makes your code harder to understand.
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49773411

http://stackoverflow.com/a/49800061
score: 93
has comment: http://stackoverflow.com/comment/89695449
accepted answer of: http://stackoverflow.com/q/49794432
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/104220749
answers question: http://stackoverflow.com/q/49794432
has body: Either manually write the version you need in your Pipfile: [requires] python_version = "3.6" Or install it on your system. But I guess you will need the version to be installed if you plan to actually run pipenv install. I would suggest to use pyenv: https://github.com/pyenv/pyenv. Follow the installation instructions, then installing Python 3.6 is just a matter of pyenv install 3.6.3 Then you can set the order of preference with pyenv global system 3.6.3 Besides, if pyenv is available, pipenv will automatically use it to install the required version. From pipenv README: Automatically install required Pythons, if pyenv is available.
has comment: http://stackoverflow.com/comment/86668480
upvote count: 93
has comment: http://stackoverflow.com/comment/123643882
has comment: http://stackoverflow.com/comment/89695242
type: Answer
has comment: http://stackoverflow.com/comment/123605950
has comment: http://stackoverflow.com/comment/92132455

http://stackoverflow.com/comment/86651584
comment on: http://stackoverflow.com/a/49817843
score: 0
type: AnswerComment
has text: My issue isn't with the hardcoded version, it works just fine with `[ ]`, in fact i got an error when i switched to `{ }` just now to test.
type: Comment

http://stackoverflow.com/a/49879165
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/49879111
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49879111
has body: Since you mention matrices, you should use 3rd party library numpy: import numpy as np matrix_1 = np.array([[1, 2], [3, 4], [5, 6]]) matrix_2 = np.array([[1, 3, 5], [2, 4, 6]]) res = np.array_equal(matrix_1, matrix_2.T) # True res = (matrix_1 == matrix_2.T).all() # True
has comment: http://stackoverflow.com/comment/86774601
has comment: http://stackoverflow.com/comment/86774373
type: Answer
has comment: http://stackoverflow.com/comment/86774411

http://stackoverflow.com/q/49781559
has answer: http://stackoverflow.com/a/49781598
has comment: http://stackoverflow.com/comment/86578498
tagged with: key-value
has comment: http://stackoverflow.com/comment/86578440
tagged with: parsing
has comment: http://stackoverflow.com/comment/86578477
has body: I have the following JSON Data: json_data = {"window_string": "X=-10 H=30 Y=20 W=40"} How would I split the values to a list that is similar to this: window_string = ["X = -10", "Y = 20", "W=40"]
favorite count: 0
type: Question
answer count: 2
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
has title: Python: How to spilt string in dictionary
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49781584

http://stackoverflow.com/comment/86532166
score: 1
type: QuestionComment
type: Comment
has text: `What should I do?`- that's simple, post a [mcve], if you want me to have a chance to help you ;-) You don't even mention what library you are using...
comment on: http://stackoverflow.com/q/49758593

http://stackoverflow.com/comment/86645691
comment on: http://stackoverflow.com/q/49814731
type: QuestionComment
has text: yeah still I'm getting the same error
score: 0
type: Comment

http://stackoverflow.com/q/49902914
has answer: http://stackoverflow.com/a/49903399
has comment: http://stackoverflow.com/comment/86821461
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/86822531
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86821458
score: 0
has title: Django IntegrityError with CreateView
answer count: 1
has body: I am trying to add a feature to a website to add new song information. The problem arises after the user fills out a song_form.html and tries to submit the new song and it returns an IntegrityError. It says NOT NULL constraint failed: music_song.album_id. Any help would be appreciated. Thanks. #models.py class Album(models.Model): album_title = models.CharField(max_length=500) artist = models.CharField(max_length=250) genre = models.CharField(max_length=50) album_cover = models.FileField() def __str__(self): return self.album_title def get_absolute_url(self): return reverse('music:detail', kwargs={'pk': self.pk}) class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) song_title = models.CharField(max_length=250) file_type = models.CharField(max_length=50) def __str__(self): return self.song_title #views.py class CreateSong(generic.CreateView): model = Song fields = ['song_title', 'file_type']
accepted answer: http://stackoverflow.com/a/49903399
type: Question

http://stackoverflow.com/q/49868980
has answer: http://stackoverflow.com/a/49869052
possible better answer: http://stackoverflow.com/a/49869052
downvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49869001
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86753386
answer count: 3
has title: Printing from a list of lists
has answer: http://stackoverflow.com/a/49869019
accepted answer: http://stackoverflow.com/a/49869019
score: -1
has body: What is the best way to print elements from a list of lists? I have a list that looks like this: l1 = [['hello', 'world', 'bye'], ['name', 'tour', 'now']] I would like to print from this, element by element, so something like: hello name world tour bye now I was thinking of using a while loop, something like: while i &lt; 3: print(l1[0][i], l1[1][i]) i -= 1 But instead of providing the [0] and [1], I would personally prefer it to be coded for a general case.
type: Question
upvote count: 0

http://stackoverflow.com/q/49785133
has title: Keras: Dice coefficient loss function is negative and increasing with epochs
score: 4
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/50086454
tagged with: deep-learning
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51845820
downvote count: 0
tagged with: machine-learning
tagged with: keras
has body: According to this Keras implementation of Dice Co-eff loss function, the loss is minus of calculated value of dice coefficient. Loss should decrease with epochs but with this implementation I am , naturally, getting always negative loss and the loss getting decreased with epochs, i.e. shifting away from 0 toward the negative infinity side, instead of getting closer to 0. If I use (1- dice co-eff) instead of (-dice co-eff) as loss, will it be wrong? Here's the full Keras implementation (which I was talking about): https://github.com/jocicmarko/ultrasound-nerve-segmentation/blob/master/train.py smooth = 1. def dice_coef(y_true, y_pred): y_true_f = K.flatten(y_true) y_pred_f = K.flatten(y_pred) intersection = K.sum(y_true_f * y_pred_f) return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth) def dice_coef_loss(y_true, y_pred): return -dice_coef(y_true, y_pred) I have shared a log of my experiment with you, although only for 2 epochs: Train on 2001 samples, validate on 501 samples Epoch 1/2 Epoch 00001: loss improved from inf to -0.73789, saving model to unet.hdf5 - 3229s - loss: -7.3789e-01 - dice_coef: 0.7379 - val_loss: -7.9304e-01 - val_dice_coef: 0.7930 Epoch 2/2 Epoch 00002: loss improved from -0.73789 to -0.81037, saving model to unet.hdf5 - 3077s - loss: -8.1037e-01 - dice_coef: 0.8104 - val_loss: -8.2842e-01 - val_dice_coef: 0.8284 predict test data 9/9 [==============================] - 4s 429ms/step dict_keys(['val_dice_coef', 'loss', 'val_loss', 'dice_coef'])
favorite count: 0
type: Question
tagged with: loss-function
tagged with: python

http://stackoverflow.com/q/49825205
has comment: http://stackoverflow.com/comment/86667330
type: AnsweredQuestion
has body: So I have a large data set where the strings are surrounded with " symbols but in some cases they have been replaced with ” symbols, the issue with that is, it's causing pandas to think my separators are part of the elements therefore joining to elements together. I'm hoping to find a way to replace the ” symbol with " without fixing up the csv file since the code will be used by someone who will most likely have a version of the dataset with those special characters and won't be fixing it up. The dataset is quite large (21 columns, over 4000 rows) but here is a small example with the issue: "a";"b";"c";"d";"e";"f" 30;"yes";4.4;"Monday";"no";"yes" 39;"no";3.4;"Tuesday";"no";"no" 47;"no";2.1;"Tuesday”;”no";"yes” 25;"yes";4.5;"wednesday";"no";"yes" Below is the code I've been trying to use but I can't seem to get that to work: import pandas as pd from StringIO import StringIO dataset = 'datafile.csv' sio = StringIO(dataset) v = sio.getvalue() v = v.replace('”',"",) sio.write(dataset) df = pd.read_csv(dataset, sep=';', decimal='.', skiprows = 1, header= None, names=['a', 'b', 'c', 'd', 'e', 'f'])
has comment: http://stackoverflow.com/comment/86666807
tagged with: pandas
has comment: http://stackoverflow.com/comment/86666395
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86666293
has comment: http://stackoverflow.com/comment/86667553
has title: How to change a special character in a csv file before uploading into a dataframe in python with pandas
downvote count: 1
has comment: http://stackoverflow.com/comment/86666835
accepted answer: http://stackoverflow.com/a/49825636
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86666380
has answer: http://stackoverflow.com/a/49825636
has comment: http://stackoverflow.com/comment/86667013
has comment: http://stackoverflow.com/comment/86667343
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86667550
has comment: http://stackoverflow.com/comment/86666853
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86666516

http://stackoverflow.com/comment/86794295
has text: Thanks for pointing out, wasted hours because of a silly mistake.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49889085
type: Comment

http://stackoverflow.com/comment/86531988
comment on: http://stackoverflow.com/q/49758227
type: QuestionComment
score: 0
type: Comment
has text: There's really not enough context available to provide a decent answer, though.

http://stackoverflow.com/comment/86575426
type: Comment
has text: Profile is linked to Reports through user_reported and sent_by attributes,where Profile Model is the foreign key. `user_reported = models.ForeignKey( 'Profile', on_delete=models.PROTECT, blank=False, null=False, related_name='user_reported_report', ) sent_by = models.ForeignKey( 'Profile', on_delete=models.PROTECT, blank=False, null=False, related_name='sent_by_report', )`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49779080

http://stackoverflow.com/a/49827152
score: 1
has comment: http://stackoverflow.com/comment/86686559
has comment: http://stackoverflow.com/comment/86678009
answers question: http://stackoverflow.com/q/49826642
downvote count: 0
upvote count: 1
has body: Can you provide the framework you are using? tensorflow? pytorch? which web tutorials specifically? Assuming you are going tensorflow, you can copy and paste code from one of these, test that it works on the provided dataset, then modify the input encoding functions to fit your dataset, then run on your dataset. https://github.com/llSourcell/How-to-Predict-Stock-Prices-Easily-Demo (best) https://github.com/sebastianheinz/stockprediction https://github.com/talolard/MarketVectors/blob/master/preparedata.ipynb (you will have to replace fc layers with lstm, and fiddle with inputs) In general procedure is something like (assuming tensorflow): Download Dataset Create a function to load batches of data Create a function to encode batch of data (normalization, other transforms) Create LSTM layer to recieve series of inputs. Create output layer (usually fully connected) to take last lstm state and predict output of your desired size. Create a tf session to wire everything together, and hit run. Some questions to ask conceptually about which network use: How many inputs to how many outputs - see this excellent http://cs231n.stanford.edu/slides/2016/winter1516_lecture10.pdf by Karpathy How far back do you consider the stock prices eg {t-100... t} or {t-10 ...t} which may dictate size of hidden layers. What other information do you think is relevant to the model? does stock A influence stock B? in which case you may have 2 lstms outputing a state to your fully connected layer...
type: Answer
has comment: http://stackoverflow.com/comment/86696881

http://stackoverflow.com/a/49876908
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49876077
has comment: http://stackoverflow.com/comment/86771470
has body: You could use pd.read_excel('C:\Users\MyFolder\MyFile.xlsx', sheet_name='Sheet1') as it ignores empty excel cells. Your DataFrame should then look like this: A B C 0 Start NaN NaN 1 3 2 4 2 7 8 4 3 11 2 17 Then drop the first row by using df.drop([0]) to get A B C 0 3 2 4 1 7 8 4 2 11 2 17
score: 3
type: Answer

http://stackoverflow.com/a/73863942
answers question: http://stackoverflow.com/q/49903037
type: Answer
has comment: http://stackoverflow.com/comment/130425572
score: 0
has body: I think some examples may overcomplicate? The inverse of differentiating is simple integrating. But for this you need a starting value, so to say the const part when integrating dx = f(x) + const: import pandas as pd import matplotlib.pyplot as plt # some example data input = pd.Series([5., 1., 2., 1., 2., 9.]) # saving the offset ('const' part of integral) to reconstruct offset = input[0] # differentiating diff = input.diff() # the first row after diff() will always be NaN, it is reasonable to set this to zero diff[0] = 0 # => reconstruct (reverse diff / integrate) <= reverse_diff_no_offset = diff.cumsum() reverse_diff = reverse_diff_no_offset + offset # plot: You can see why a offset is needed. Any other offset will shift the line up/down plt.plot(input, color='green', linestyle=None, marker="o") plt.plot(reverse_diff_no_offset, color='grey') plt.plot(reverse_diff, color='blue') Also numpy has cumsum, so it will work there as well

http://stackoverflow.com/comment/86764534
score: 0
comment on: http://stackoverflow.com/q/49869559
type: Comment
has text: @omijn: I think the word "exception" was misleading - I have edited it. See the homework text for what was meant. I fell into that trap too `:-)`
type: QuestionComment

http://stackoverflow.com/comment/86700932
score: 0
comment on: http://stackoverflow.com/a/49841308
type: AnswerComment
type: Comment
has text: Yes, I'd earlier looked at using dictionaries as they seemed the obvious choice (and at that stage I only had a limited awareness of classes), but couldn't figure how to associate more than one value with each key. I gather you can store tuples as values, which would allow me to do what I want, but I couldn't figure how to store the tuples or only one out of the two values in the tuple.

http://stackoverflow.com/comment/94208554
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50152554
has text: Last second line is missing the End of Line. could you please fill the missing part?
score: 0

http://stackoverflow.com/a/49902660
accepted answer of: http://stackoverflow.com/q/49902509
has comment: http://stackoverflow.com/comment/86845840
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/49902509
downvote count: 1
has comment: http://stackoverflow.com/comment/86821223
has comment: http://stackoverflow.com/comment/86821428
has comment: http://stackoverflow.com/comment/86845394
has body: Simply return the contents of the configuration file you read in openfile, and pass the contents of the file to a Label constructor. Note that since the Label constructor takes a single string, that's what you'll have to convert your list to: def openfile(): filename = filedialog.askopenfilename(parent=root) return list(open(filename)) ... config_file_contents = ''.join(openfile()) label = Label(root, text=config_file_contents) label.place(...) Or if you want to display each element in your configuration list individually, you can loop through each element in your configuration file list and pass each element into it's own separate Label object: for config in openfile(): label = Label(root, text=config) label.place(...)
type: Answer
score: 0

http://stackoverflow.com/a/49853525
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49852474
has comment: http://stackoverflow.com/comment/86721671
accepted answer of: http://stackoverflow.com/q/49852474
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: Change target to current or just remove the key from your return, because current is the default.
has comment: http://stackoverflow.com/comment/86721795

http://stackoverflow.com/comment/86620670
score: 0
comment on: http://stackoverflow.com/q/49803081
type: QuestionComment
type: Comment
has text: Have you tried other random seeds?

http://stackoverflow.com/q/49861233
type: Question
has body: I'm trying to read a dict to put values in a jinja2 template: answers = {'obs_18': None, 'obs_1': 'jack', 'rot3': None, 'obs_4': None, 'rot10': None, 'obs_8': None, 'rot7': None, 'rot6': None, 'rot13': None, 'rot21': None, 'obs_13': None, 'rot9': None, 'rot20': None, 'rot11': None, 'obs_7': None, 'rot17': None, 'obs_9': None, 'obs_21': None, 'obs_11': None, 'rot12': None, 'obs_19': None, 'obs_20': None, 'rot16': None, 'rot1': None, 'obs_10': None, 'rot15': None, 'rot18': None, '_id': ObjectId('5ad4b9a7f1ccd84582282207'), 'obs_16': None, 'obs_15': None, 'rot22': None, 'rot19': None, 'rot4': None, 'obs_5': None, 'rot5': None, 'obs_6': None, 'rot8': None, 'obs_12': None, 'obs_14': None, 'rot14': None, 'obs_17': None, 'rot2': None, 'obs_2': None, 'obs_22': None, 'obs_3': None} using loop.index to populate a form with default values for input fields as strings, but the values shown are just as strings, like: answers['obs_1'] , instead of the correct value 'jack'. i'm using this: The values are displayed if i use: {{ answers }} Any clues? Passing args: @app.route('/checklist/<string:_id>', methods=['GET','POST']) def checklist(_id): form = CheckList() perguntas = mongo.db.perguntas.find() n_perguntas = mongo.db.perguntas.count() print(n_perguntas) perguntas.sort([('id',1)]) answers = mongo.db.checklists.find_one_or_404({'_id':ObjectId(_id)}) if request.method == 'POST': for k in range(1,n_perguntas+1): st = str(k) answers.append({"rot"+st: request.form.get('rot'+st), "obs_"+st: request.form.get('obs_'+st)}) print(answers) return render_template('checklist.html', form=form, perguntas=perguntas, answers=answers, logeduser=session['username']) template: {% extends 'layout.html' %} {% block content %} Check-list 912 {{ answers['_id']}} N.O. Pergunta Dispositivo Resultado Observação {% for p in perguntas %} {{ loop.index }} {{ p.pergunta }} {{ p.dispo }} Sim Não S/I {% endfor%} {{ answers }} {% endblock %}
has comment: http://stackoverflow.com/comment/86738286
has comment: http://stackoverflow.com/comment/86739137
has comment: http://stackoverflow.com/comment/86740088
has comment: http://stackoverflow.com/comment/86738933
has comment: http://stackoverflow.com/comment/86739794
accepted answer: http://stackoverflow.com/a/49861527
has comment: http://stackoverflow.com/comment/86737885
has comment: http://stackoverflow.com/comment/86738369
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/86739233
has comment: http://stackoverflow.com/comment/86740162
has comment: http://stackoverflow.com/comment/86738558
has comment: http://stackoverflow.com/comment/86739931
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86739578
has comment: http://stackoverflow.com/comment/86740269
has comment: http://stackoverflow.com/comment/86738053
answer count: 1
has title: Jinja2 concatenate string to get values to input
has comment: http://stackoverflow.com/comment/86740233
has comment: http://stackoverflow.com/comment/86739741
has comment: http://stackoverflow.com/comment/86738494
has answer: http://stackoverflow.com/a/49861527
has comment: http://stackoverflow.com/comment/86739498
tagged with: jinja2

http://stackoverflow.com/q/49786109
tagged with: unit-testing
has title: Python: unittest not running
type: Question
accepted answer: http://stackoverflow.com/a/49786131
has comment: http://stackoverflow.com/comment/86587662
has body: I am working on a transpiler and wanted to try out TDD, but the tests don't seem to run. After running python test_transpiler.py, I get: 15 ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK The code is: import unittest import transpiler class TranspilerTDD: def test_adds_encoding(self): source = "" result = transpile(source); expected = "#coding: utf-8\n" self.assertEqual(result, expected) if __name__ == '__main__': unittest.main() Where transpile is a function in transpiler (which I'm sure is working). What's wrong?
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49786131
answer count: 1

http://stackoverflow.com/a/49772783
answers question: http://stackoverflow.com/q/49772706
upvote count: 1
score: 1
type: Answer
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49772706
has body: I believe you need convert output to Series if need columns of lists: df = pd.DataFrame({'col_text':range(5)}) def func(text): a = (['1','2','3'],['abc','def','efg']) return pd.Series(a) df'col1','col2' = df.col_text.apply(func) print (df) col_text col1 col2 0 0 [1, 2, 3] [abc, def, efg] 1 1 [1, 2, 3] [abc, def, efg] 2 2 [1, 2, 3] [abc, def, efg] 3 3 [1, 2, 3] [abc, def, efg] 4 4 [1, 2, 3] [abc, def, efg]

http://stackoverflow.com/q/49840499
tagged with: python
tagged with: regex
tagged with: replace
score: 0
answer count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86695784
upvote count: 1
duplicate of: http://stackoverflow.com/q/43096522
downvote count: 1
duplicate of: http://stackoverflow.com/q/49823631
favorite count: 0
has body: I have the below data where the column values contain $. This makes the dummies created to be of dtype unsigned integer. I am trying to replace the '$' with '' resolve the dtype issue. INPUT grp_m1 grp_m2 grp_m3 grp_m4 $50-$75 $50-$75 $50-$75 $50-$75 $50-$75 $50-$75 $50-$75 $50-$75 $150-$175 $150-$175 $150-$175 $150-$175 $100-$125 $100-$125 $100-$125 $100-$125 $150-$175 $125-$150 $125-$150 $125-$150 My code for replacing '$' with '': if ('$' in str(df_column[column]) == True): new_val = [x.strip('$') for x in df_column[column].astype('str')] df_column.replace(column.values,values = new_val, inplace = True) I am trying to do for a single column as of now, ideally would want to deal with all columns containing '$'. So df_column is thedataframe and and column is a list containing the column names grp_m1---grp_m4. Result: There is no error thrown but there are no changes in the column values. Expected Output: grp_m1 grp_m2 grp_m3 grp_m4 50-75 50-75 50-75 50-75 50-75 50-75 50-75 50-75 150-175 150-175 150-175 150-175 100-125 100-125 100-125 100-125 150-175 125-150 125-150 125-150 Can someone please help me with this? I had used the solution provided : if ('$' in str(df_column[column]) == True): df_column.values.replace('\$', '',inplace = True, regex=True) But there is no change in the values in the dataframe.
type: Question
has comment: http://stackoverflow.com/comment/86705538
has title: Replacing $ in column values while creating dummies in python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/49823631

http://stackoverflow.com/comment/86690353
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49837539
has text: I'd assume it's because you'd need more compute (horizontal scale out) power to justify all the extra overhead that dask has.

http://stackoverflow.com/q/49849936
accepted answer: http://stackoverflow.com/a/49850068
has comment: http://stackoverflow.com/comment/86714435
type: AnsweredQuestion
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49849976
upvote count: 1
score: 1
has body: I'm new to python, coming from a basic knowledge of perl. I'm trying to capture a substring with regex. &gt;&gt;&gt; a='Question 73 of 2943' &gt;&gt;&gt; import re &gt;&gt;&gt; re.match("Question.*(\d+)\s+of", a).group(0) 'Question 73 of' &gt;&gt;&gt; re.match("Question.*(\d+)\s+of", a).group(1) '3' What I wanted to do was to catch 73 in the group. I assumed that the parenthesis would do that.
has answer: http://stackoverflow.com/a/49850068
has answer: http://stackoverflow.com/a/49849985
favorite count: 0
type: Question
has title: Python capture group from string, with regex
linked to: http://stackoverflow.com/q/2301285
possible better answer: http://stackoverflow.com/a/49849976
tagged with: python
tagged with: regex

rss
type: Tag
tag name: rss
tags question: http://stackoverflow.com/q/49884912

http://stackoverflow.com/comment/86558177
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49771481
has text: while using "\" getting invalid syntax

http://stackoverflow.com/q/49794165
has comment: http://stackoverflow.com/comment/86602985
score: 0
type: Question
has title: Django exception: Improperly configured SECRET_KEY
has body: While executing migrate command 'python manage.py migrate' on mac os, I get the following error Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 61, in execute super(Command, self).execute(*args, **options) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 72, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Users/jeetpatel/final-tribute/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 129, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I have mentioned a SECRET_KEY = 'fooo' in my base.py file base.py import os import smtplib BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(…
has answer: http://stackoverflow.com/a/49794341
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49795261
answer count: 2

http://stackoverflow.com/comment/86833366
score: 0
comment on: http://stackoverflow.com/q/49908444
type: Comment
has text: @DavidO, the frequency is very low.
type: QuestionComment

python-multiprocessing
tags question: http://stackoverflow.com/q/49822090
tags question: http://stackoverflow.com/q/49837539
tags question: http://stackoverflow.com/q/49916315
tags question: http://stackoverflow.com/q/49821166
tag name: python-multiprocessing
tags question: http://stackoverflow.com/q/49908058
tags question: http://stackoverflow.com/q/49842290
tags question: http://stackoverflow.com/q/49884167
tags question: http://stackoverflow.com/q/49858968
tags question: http://stackoverflow.com/q/49857233
tags question: http://stackoverflow.com/q/49843903
tags question: http://stackoverflow.com/q/49779340
type: Tag

http://stackoverflow.com/a/49863886
accepted answer of: http://stackoverflow.com/q/49863759
type: Answer
answers question: http://stackoverflow.com/q/49863759
has body: One approach def filterList(numList, threshold): return list(filter(lambda x: x &lt; threshold, numList)) Another approach: filteredList = [x for x in numList if x &lt; threshold]
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/86751496
score: 0
has text: I'll follow up with this, thank you @ImportanceOfBeingErnest !
comment on: http://stackoverflow.com/q/49866506
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49857746
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86755177
downvote count: 0
has comment: http://stackoverflow.com/comment/86730030
has comment: http://stackoverflow.com/comment/86753381
upvote count: 1
tagged with: python
has body: When I do: from PIL import Image It gave: ImportError: libopenjp2.so.7: cannot open shared object file: No such file or directory There is a similar question that suggests to do sudo apt-get install libopenjp2-7-dev However, in my case, it is not doable since I'm operating a remote computation system and I am not able to do sudo command. Since I found there are many .so files in lib directory under Miniconda, I wonder whether can I install this libopenjp2.so.7 via conda install? How?
tagged with: conda
has comment: http://stackoverflow.com/comment/86737622
tagged with: .so
has title: How to install .so file via conda?
score: 1
tagged with: dependencies
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86753702
linked to: http://stackoverflow.com/q/48012582

http://stackoverflow.com/a/76627337
answers question: http://stackoverflow.com/q/49844925
score: 1
type: Answer
upvote count: 2
has body: The best easy solution is to install Xlwriter. pip install XlsxWriter
downvote count: 1

http://stackoverflow.com/comment/86716761
type: AnswerComment
has text: That unfortunately doesn't work for me. For the image in b), it does exactly the same as the command Image.open('image.png').resize((244, 138)).save('image2.png') . For a bigger JPG image (3456x5184 with desired_w 5184 and desired_h 3456, similar to example b but with a lot bigger images in JPG format), it stretches and rotates, while my original code just rotates. Neither is what I want, I don't want to stretch nor rotate, but the codes do it anyway :( -- (By 'stretch' I mean change aspect ratio of the original not-necessarily-black part of the image)
comment on: http://stackoverflow.com/a/49846220
type: Comment
score: 0

http://stackoverflow.com/a/66195530
type: Answer
answers question: http://stackoverflow.com/q/49787022
has body: actually , when I just have the problem as you are. but when I access the Class Define class RequestsCookieJar(cookielib.CookieJar, MutableMapping): I found a func called def get_dict(self, domain=None, path=None): you can simply write code like this raw = "rawCookide" print(len(cookie)) mycookie = SimpleCookie() mycookie.load(raw) UCookie={} for key, morsel in mycookie.items(): UCookie[key] = morsel.value
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49848962
tagged with: pandas
type: AnsweredQuestion
tagged with: scipy
has body: I have measurements (PPI arc scans) taken with a doppler wind lidar. The data is stored in a pandas dataframe where rows represent azimuth angle and columns represent radial distance (input shape = 30x197). Link to example scan, (csv). I want to transform this to a cartesian coordinate system, and output a 2d array which is re-gridded into x,y coordinates instead of polar with the values stored in the appropriate grid cell. Interpolation (nearest neighbor) is ok and so is zero or NaN padding of areas where no data exists. Ideally the X and Y grid should correspond to the actual distances between points, but right now I'm just trying to get this working. This shouldn’t be terribly difficult, but I’m having trouble obtaining the result I want. So far, I have working code which plots on a polar axis beautifully (example image) but this won't work for the next steps of my analysis. I have tried many different approaches with scipy.interpolate.griddata, scipy.ndimage.geometric_transform, and scipy.ndimage.map_coordinates but haven't gotten the correct output. Here is an example of my recent attempt (df_polar is the csv file linked): # Generate polar and cartesian meshgrids r = df_polar.columns theta = df_polar.index theta = np.deg2rad(theta) # Polar meshgrid rad_c, theta_c = np.meshgrid(r,theta) # Cartesian meshgrid X = rad_c * np.cos(theta_c) Y = rad_c * np.sin(theta_c) x,y = np.meshgrid(X,Y) # Interpolate from polar to cartesian grid new_grid = scipy.interpolate.griddata( (rad_c.flatten(), theta_c.flatten()), np.array(df_polar).flatten(), (x,y), method='nearest') The result is not correct at all, and from reading the documentation and examples I don't understand why. I would greatly appreciate any tips on where I have gone wrong. Thanks a lot!!
favorite count: 0
linked to: http://stackoverflow.com/q/16750618
tagged with: numpy
linked to: http://stackoverflow.com/q/47146855
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86714425
downvote count: 0
accepted answer: http://stackoverflow.com/a/49850304
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/49850304
has comment: http://stackoverflow.com/comment/86826605
has comment: http://stackoverflow.com/comment/86752387
has title: Python/SciPy: Issues converting DataFrame from polar to Cartesian grid
type: Question

http://stackoverflow.com/comment/86893256
type: Comment
comment on: http://stackoverflow.com/a/49916506
type: AnswerComment
has text: Do you want to mock the module? Or do you want to mock what you actually import from it (`Modifiers` class)? Check out [my other answer](https://stackoverflow.com/a/48847105/2650249) for the mocking possibilities for the imported stuff.
score: 0

http://stackoverflow.com/q/49762240
has title: What is max size of the file in 64-bit system using numpy memory mapping
tagged with: numpy-memmap
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86539933
has answer: http://stackoverflow.com/a/49762447
tagged with: memory-mapping
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
has body: I am trying to work with a large file ~ roughly 50 GB. I am trying to access iterate through the file using numpy memory mapping. I see that there is a limitation on the size of the file to be used for memory mapping which is 2GB for 32 bit systems. Here is the link : https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.memmap.html I would like to know if there is a hard limit on file size using numpy memory mapping for a good performance.
linked to: http://stackoverflow.com/q/726471
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/86540174
has comment: http://stackoverflow.com/comment/86540487
tagged with: memory-mapped-files
answer count: 1

string
tags question: http://stackoverflow.com/q/49835155
tags question: http://stackoverflow.com/q/49825551
type: Tag
tags question: http://stackoverflow.com/q/49887198
tags question: http://stackoverflow.com/q/49874500
tags question: http://stackoverflow.com/q/49807976
tags question: http://stackoverflow.com/q/49798888
tags question: http://stackoverflow.com/q/49834133
tags question: http://stackoverflow.com/q/49836434
tags question: http://stackoverflow.com/q/49786837
tags question: http://stackoverflow.com/q/49873769
tags question: http://stackoverflow.com/q/49874287
tags question: http://stackoverflow.com/q/49762063
tags question: http://stackoverflow.com/q/49819328
tags question: http://stackoverflow.com/q/49837475
tags question: http://stackoverflow.com/q/49849921
tags question: http://stackoverflow.com/q/49870482
tags question: http://stackoverflow.com/q/49900145
tags question: http://stackoverflow.com/q/49888736
tags question: http://stackoverflow.com/q/49909027
tags question: http://stackoverflow.com/q/49848597
tags question: http://stackoverflow.com/q/49787417
tags question: http://stackoverflow.com/q/49911185
tags question: http://stackoverflow.com/q/49826481
tags question: http://stackoverflow.com/q/49901863
tags question: http://stackoverflow.com/q/49848688
tags question: http://stackoverflow.com/q/49769706
tags question: http://stackoverflow.com/q/49808835
tags question: http://stackoverflow.com/q/49819880
tags question: http://stackoverflow.com/q/49865442
tags question: http://stackoverflow.com/q/49799931
tags question: http://stackoverflow.com/q/49774943
tags question: http://stackoverflow.com/q/49792393
tags question: http://stackoverflow.com/q/49795529
tags question: http://stackoverflow.com/q/49898403
tags question: http://stackoverflow.com/q/49806790
tags question: http://stackoverflow.com/q/49791920
tags question: http://stackoverflow.com/q/49889379
tags question: http://stackoverflow.com/q/49872710
tags question: http://stackoverflow.com/q/49773486
tags question: http://stackoverflow.com/q/49874090
tags question: http://stackoverflow.com/q/49869559
tags question: http://stackoverflow.com/q/49888634
tags question: http://stackoverflow.com/q/49815091
tags question: http://stackoverflow.com/q/49832076
tags question: http://stackoverflow.com/q/49831654
tags question: http://stackoverflow.com/q/49818754
tags question: http://stackoverflow.com/q/49895423
tags question: http://stackoverflow.com/q/49775130
tags question: http://stackoverflow.com/q/49892621
tags question: http://stackoverflow.com/q/49912730
tags question: http://stackoverflow.com/q/49765985
tags question: http://stackoverflow.com/q/49785742
tags question: http://stackoverflow.com/q/49848711
tag name: string
tags question: http://stackoverflow.com/q/49831048
tags question: http://stackoverflow.com/q/49776834
tags question: http://stackoverflow.com/q/49789556
tags question: http://stackoverflow.com/q/49900511
tags question: http://stackoverflow.com/q/49901164
tags question: http://stackoverflow.com/q/49771963
tags question: http://stackoverflow.com/q/49854755
tags question: http://stackoverflow.com/q/49832684
tags question: http://stackoverflow.com/q/49788154
tags question: http://stackoverflow.com/q/49793212
tags question: http://stackoverflow.com/q/49791658
tags question: http://stackoverflow.com/q/49848978
tags question: http://stackoverflow.com/q/49758413
tags question: http://stackoverflow.com/q/49901753
tags question: http://stackoverflow.com/q/49827637
tags question: http://stackoverflow.com/q/49879569
tags question: http://stackoverflow.com/q/49861201

http://stackoverflow.com/q/49820173
tagged with: pentaho
downvote count: 0
has answer: http://stackoverflow.com/a/76294506
tagged with: python-requests
tagged with: gevent
has answer: http://stackoverflow.com/a/49929345
has answer: http://stackoverflow.com/a/65492838
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79045165
upvote count: 30
has answer: http://stackoverflow.com/a/63188677
accepted answer: http://stackoverflow.com/a/52130355
has answer: http://stackoverflow.com/a/52130355
answer count: 7
tagged with: python
favorite count: 0
score: 30
has answer: http://stackoverflow.com/a/78928895
possible better answer: http://stackoverflow.com/a/63188677
type: Question
has comment: http://stackoverflow.com/comment/96925761
has comment: http://stackoverflow.com/comment/96925760
has title: "RecursionError: maximum recursion depth exceeded" from ssl.py: `super(SSLContext, SSLContext).options.__set__(self, value)`
has body: I am using Python 3.6.5 on the following remote server setup: Server: Windows 10 Python: 3.6.5 Requests: 2.18.4 Pentaho: 8.0 When I run request.get against URLs in the server's command prompt, it gets the JSON as expected: &gt;&gt;&gt; import requests &gt;&gt;&gt; response = requests.get(url, headers=headers) &gt;&gt;&gt; json = response.json() &gt;&gt;&gt; print(json) {'d': {'results': [{'_ ... However when I run the same script in CPython for Pentaho 8.0, I get RecursionError: maximum recursion depth exceeded Full log: 2018/04/13 15:02:17 - Get SP Doc List.0 - ERROR (version 8.0.0.0-28, build 8.0.0.0-28 from 2017-11-05 07.27.50 by buildguy) : Unexpected error 2018/04/13 15:02:17 - Get SP Doc List.0 - ERROR (version 8.0.0.0-28, build 8.0.0.0-28 from 2017-11-05 07.27.50 by buildguy) : org.pentaho.di.core.exception.KettleException: 2018/04/13 15:02:17 - Get SP Doc List.0 - Traceback (most recent call last): File "C:\Users\ADMINI~1\AppData\Local\Temp\2\pyServer.py", line 299, in execute_script exec (script, _global_env) File "&lt;string&gt;", line 16, in &lt;module&gt; File "C:\Program Files\Python36\lib\site-packages\requests\api.py", line 72, in get return request('get', url, params=params, **kwargs) File "C:\Program Files\Python36\lib\site-packages\requests\api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "C:\Program Files\Python36\lib\site-packages\requests\sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "C:\Program Files\Python36\lib\site-packages\requests\sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "C:\Program Files\Python36\lib\site-packages\requests\adapters.py", line 440, in send timeout=timeout File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen chunked=chunked) File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 346, in _make_request self._validate_conn(conn) File "C:\Program Files…

http://stackoverflow.com/comment/86703907
has text: the above link helped. thanks a lot, Joost! You're a savior.
comment on: http://stackoverflow.com/a/49844492
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49869562
type: Question
has body: So I am trying to get this output No Column Sum 0 Company 28 1 Booth 28 2 Full-Time 25 3 Full-Time Visa Sponsor 5 4 Part-Time 1 5 Internship 18 6 Freshman 7 7 Sophomore 9 8 Junior 17 9 Senior 24 10 Post-Bacs 17 11 MS 17 12 PhD 6 13 Alumni 15 However, I am getting this error TypeError: tuple indices must be integers or slices, not str My code is the following data_employer = {'No': ('Column', 'Sum')} for vari in range(14): sum = 0 for row in ReadyColumn: if row[vari] != '': sum =+1 data_employer = (companies[vari], sum) for num in data_employer: print(num, data_employer [num][0], data_employer[num][1]) outData = [] Is it because I need to not call num but the row number? I thought it could work this way though. Any input would be appreciated. Thank you! Traceback (most recent call last): File "/Prj3Assignt3.py", line 42, in &lt;module&gt; print(num, data_employer[num][0], data_employer[num][1]) TypeError: tuple indices must be integers or slices, not str Added with error import csv filename = "CFSpring2018Employers.csv" #I assigned the file to a variable f = open(filename) #I couldn't leave it default due to UTF-8 error from orginial reader = csv.reader(f) f.close #Dictionary for part 1 'Companies' companies = {} countComp = 0 #Sets the 'rows to 0 for row in reader: #reader has assigned value to read csv info if row[0] == 'Company': #Searches row called 'Company' for item in row: companies[countComp] = item #Everytime it shows it puts it into the dictionary countComp += 1 break for i in companies: #Allows me to print numbers next to the companies dict print(i, companies[i]) ReadyColumn = [] #Making a new list for cleaned up data NumCow = 0 for row in reader: NumCow +=1 if NumCow &gt; 0 and NumCow &lt; 31 and row[0] != '': #This will read the rows between 0-31, and if the row contains 'Nothing' it skips ReadyColumn.append(row) #Updates the list rowNum = -1 #Resets the counter for row in ReadyColumn: rowNum += 1 print(rowNum, ','.join(row)) #Joins any weird marks and p…
score: 0
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86754348
tagged with: tuples
has answer: http://stackoverflow.com/a/49869630
has comment: http://stackoverflow.com/comment/86754374
has answer: http://stackoverflow.com/a/49869671
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: dictionary
has title: TypeError from data gathering

http://stackoverflow.com/q/49893574
has answer: http://stackoverflow.com/a/49898232
type: UnansweredQuestion
has title: How to get only json value using jquery from calling an API?
has comment: http://stackoverflow.com/comment/86802620
tagged with: python
tagged with: jquery
has comment: http://stackoverflow.com/comment/86803243
has comment: http://stackoverflow.com/comment/86802758
tagged with: flask
has body: The API returns both JSON and also render the template and when i call $.getJSON it will only return that render template but not JSON value. I have tried this if request.args['type'] == 'json': return json.dumps(group) else: return render_template("/c.., summary=json.dumps(group)) but it says bad request Is there any way I can get that JSON value whenever I need it? This is my view @cms.route('/add/asset/&lt;client_id&gt;', methods=["GET"]) @login_required def asset_add(client_id): if int(current_user.id_) == int(client_id): group = {} group['id'] = [] group['pid'] = [] group['name'] = [] for index in range(len([r.id_ for r in db.session.query(Assetgroup.id_)])): for asset in (Assetgroup.query.filter_by(parent_id=(index or ''))): group['id'].append(asset.id_) group['pid'].append(asset.parent_id) group['name'].append(asset.name) if request.args['type'] == 'json': return json.dumps(group) else: return render_template("/cms/asset_add.html", action="/add/asset", asset=None, client_id=client_id, types=Type.query.all()) else: return 'permission denied' and this is my ajax request $(document).ready(function () { $('#group_id').click(function () { $.getJSON( '/add/asset/' + {{ client_id }}, function (data) { $('#group_id').find('option').remove(); var len = data.id.length; for (var i = 0; i &lt; len; i++) { var option_item = '&lt;option value="' + data.id[i] + '"&gt;' + data.name[i] + "&lt;/option&gt;"; $('#group_id').append(option_item); } } ); }); });
has comment: http://stackoverflow.com/comment/86807053
score: 0
has comment: http://stackoverflow.com/comment/86802967
has comment: http://stackoverflow.com/comment/86802896
has comment: http://stackoverflow.com/comment/86805618
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/86806031
has answer: http://stackoverflow.com/a/49895284
has comment: http://stackoverflow.com/comment/86805718
type: Question
answer count: 2

http://stackoverflow.com/comment/86701696
type: QuestionComment
has text: the version is 2.0.2
comment on: http://stackoverflow.com/q/49843218
score: 0
type: Comment

multiprocess
tags question: http://stackoverflow.com/q/49916315
tags question: http://stackoverflow.com/q/49806945
tag name: multiprocess
type: Tag

http://stackoverflow.com/a/49788235
type: Answer
has body: That just isn't how to index regular python lists, that is a numpy() slicing convention. Simply use sys.argv[1][:5] to get your desired result.
answers question: http://stackoverflow.com/q/49788154
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49788154

http://stackoverflow.com/comment/86618180
type: QuestionComment
comment on: http://stackoverflow.com/q/49801773
score: 1
has text: I don't see anything wrong with your solution.
type: Comment

http://stackoverflow.com/a/49851444
answers question: http://stackoverflow.com/q/49851375
score: 0
has body: x[0]+=1 and y[0]+=1 just modify the existing object, while L+=1 is an assignment and creates a new local reference. See https://stackoverflow.com/a/11867500/7662112
type: Answer

http://stackoverflow.com/comment/86660956
has text: Yup it is!Edited!
comment on: http://stackoverflow.com/q/49822676
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86799442
score: 1
type: Comment
type: AnswerComment
has text: you have already converted the unicode to string at some point of time. Either not do it, or convert it back to unicode so decoding to `ascii` can be proper. `test['token'].apply(lambda val: val.decode('utf-8'))`
comment on: http://stackoverflow.com/a/49891818

http://stackoverflow.com/comment/86801366
has text: I don't see any attempt to **install** *keras*, only attempt(s) to use it, failed because *tensorflow* (which is a dependency) is missing or incorrectly installed. Try `pip install keras` first.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49892136
type: Comment

http://stackoverflow.com/a/49795936
has body: You can find start command syntax in this documentation : START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED] [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL] [/NODE &lt;NUMA node&gt;] [/AFFINITY &lt;hex affinity mask&gt;] [/WAIT] [/B] [command/program] [parameters] So I would suggest to execute : @echo off cmd /k "cd /d C:\Users\user1\Desktop\Website\code\myenvironment\Scripts &amp; activate &amp; cd /d C:\Users\user1\Desktop\Website\code\myapp &amp; python manage.py runserver" start "" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "http://localhost:8000/"
score: 0
answers question: http://stackoverflow.com/q/49793932
type: Answer

http://stackoverflow.com/comment/86773574
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49878068
has text: No, you're returning `None` from `returnCsvFileDir`. And even if you are returning a directory, you can't open a directory as if it were a csv file.

http://stackoverflow.com/q/49876794
accepted answer: http://stackoverflow.com/a/49881281
has answer: http://stackoverflow.com/a/49881281
tagged with: python
tagged with: bokeh
has title: ImportError: cannot import name PolyDrawTool (Not able to Import - PolyDrawTool)
type: AnsweredQuestion
tagged with: python-2.7
has body: I am Trying to run this example (Not able to Import - PolyDrawTool) https://docs.bokeh.org/en/latest/docs/user_guide/examples/tools_poly_draw.html Python 2.7 bokeh v0.12 Got Import Error : ImportError Traceback (most recent call last) &lt;ipython-input-1-cc6a3ae44bb8&gt; in &lt;module&gt;() 1 from bokeh.plotting import figure, output_file, show ----&gt; 2 from bokeh.models import PolyDrawTool 3 4 output_file("tools_poly_draw.html") 5 ImportError: cannot import name PolyDrawTool
score: 0
answer count: 1
type: Question
tagged with: importerror

http://stackoverflow.com/comment/86693054
type: Comment
comment on: http://stackoverflow.com/a/49838983
type: AnswerComment
score: 0
has text: @data_garden this should be your validation set, not training

http://stackoverflow.com/q/49888318
has body: I've been developing a face detection app integrated with ROS to be used with DRONES (bebop parrot to be exact). The code itself can be found on google and what it does is, basically, shows every face that appear on screen. My problem is: I want the drone to follow my face (and only mine) but as i said before, the code can detect multiples faces at time. Here's the code: face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # some people can just use the haarcascade_frontalface_default.xml without specifying the path test = face_cascade.load('../../../../opencv/data/haarcascades/haarcascade_frontalface_default.xml') # start the video capture video_capture = cv2.VideoCapture(0) # while-loop to detect face on webcam until you press 'q'. while not rospy.is_shutdown(): # Capture frame-by-frame ret, frame = video_capture.read() frame = imutils.resize(frame, width=600) #convert the frame (of the webcam) to gray) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) mask = cv2.erode(gray, None, iterations=2) mask = cv2.dilate(mask, None, iterations=2) # detecting the faces faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) x_imagem = x + (w/2) y_imagem = y + (h/2) cv2.circle(frame, (x+(w/2), y+(h/2)), 5, (0,0,255), -1) #600 x 450; if(x_imagem &gt; 200 and x_imagem &lt; 400): rospy.loginfo("CENTRO") elif(x_imagem &lt; 200): #ROSTO PRA ESQUERDA, ENTAO VAI PARA DIREITA rospy.loginfo("ROSTO NA ESQUERDA") pub_face.publish("esq") elif(x_imagem &gt; 400): #ROSTO PRA DIREITA, ENTAO VAI PARA ESQUERDA rospy.loginfo("ROSTO NA DIREITA") pub_face.publish("dir") # Display the resulting frame cv2.imshow('Video', frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): rospy.loginfo("FIM DO PROGRAMA DE DETECCAO DE ROSTOS") break # When everything is done, release the capture video_capture.r…
tagged with: python
accepted answer: http://stackoverflow.com/a/49888367
type: AnsweredQuestion
score: 0
tagged with: face-detection
has answer: http://stackoverflow.com/a/49888367
answer count: 1
has title: Face Detection: show only one face at a time
type: Question
tagged with: opencv

http://stackoverflow.com/a/49840898
has body: You can iterate the string character-wise and accumulate characters in a part-list until your last char in that list is 'u' and your current char is '1' or '2'. You then join the part-list together again, omitting its last character (the 'u') and stuff it either in u1 or u2 and clear part: a = "Hi thereu1hello ?u1Whatu2Goodu1Work worku2Stacku2" u1 = [] u2 = [] part = [] # iterate your string character-wise for c in a: # last character collected == u and now 1 or 2? if part and part[-1] == "u" and c in ["1","2"]: if c == "1": u1.append(''.join(part[:-1])) # join all collected chars, omit 'u' part=[] else: u2.append(''.join(part[:-1])) # see above, same. part=[] else: part.append(c) # you have no end-condition if your string ends on neither u1 nor u2 the # last part of your string is not added to any u1 or u2 print(u1) print(u2) Output: ['Hi there', 'hello ?', 'Good'] ['What', 'Work work', 'Stack'] Second way to go would be to remembers certain indexes (where ended last slice, where are we now) and just slice the correct part from the input: u1 = [] u2 = [] oldIdx = 0 # where to start slicing, update on append to either u1 or u2 lastOne = "" # character in last iteration for i,c in enumerate(a): # get the index (i) and the character (c) from enumerate if lastOne == "u" and c in ["1","2"]: if c == "1": u1.append(a[oldIdx:i-1]) # slice the correct part from a else: u2.append(a[oldIdx:i-1]) # slice the correct part from a oldIdx = i+1 # update slice starting position lastOne = "" # reset last one else: lastOne = c # remeber char as lastOne You do not need as much "memory/time" to store a single integer and a character as you need when storing / appending to a part list - you also do not need to join the parts for appending as you directly slice from the source - so its slightly more efficient.
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49840710
type: Answer
answers question: http://stackoverflow.com/q/49840710

http://stackoverflow.com/comment/86631619
comment on: http://stackoverflow.com/q/49803518
score: 0
has text: Why don't you use POST method and put the json payload in the request body?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49898842
has comment: http://stackoverflow.com/comment/86852078
has comment: http://stackoverflow.com/comment/86815387
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has comment: http://stackoverflow.com/comment/86852368
has comment: http://stackoverflow.com/comment/86813478
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86814073
has comment: http://stackoverflow.com/comment/86864460
has title: Flask/Python render only a table in template
upvote count: 0
score: -2
downvote count: 2
accepted answer: http://stackoverflow.com/a/49924630
tagged with: python
tagged with: flask
has body: I want a search bar in my site. This get data from a postgresql database with the user input, return the results and show it in a table. How i can send the data to my .py and return the new data and render only the table with the results? I'm using python 2.7 EDIT: edit_person.html {% extends "layouts/layout_logged.html"%} {% block body%} TEST # here can the user add something from the search results {% include "searches/clothings_search_result.html" %} {% endblock %} person.py @app.route('/macro_test', methods=['GET']) @login_required def test(): user_input = request.form["search"] search_result = # here the query search_result = [dict(r) for r in search_result ] result = get_template_attribute('searches/clothings_search_result.html', 'result ') return result('search_result') clothing_search_result.html {% macro result (search_result) -%} {{ search_result[0] }} # here is the table i want to render {%- endmacro %}
has answer: http://stackoverflow.com/a/49924630
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/a/49891818
has comment: http://stackoverflow.com/comment/86799237
accepted answer of: http://stackoverflow.com/q/49891778
has comment: http://stackoverflow.com/comment/86799442
type: Answer
has body: If the unicode conversion you are trying to do is standard then you can directly convert to ascii. import unicodedata test['ascii'] = test['token'].apply(lambda val: unicodedata.normalize('NFKD', val).encode('ascii', 'ignore').decode()) Example: import unicodedata data = [{'name': 'saylı'}, {'name': 'öhdəliyi'}] df = pd.DataFrame.from_dict(data, orient='columns') df['name'].apply(lambda val: unicodedata.normalize('NFKD', val).encode('ascii', 'ignore').decode()) output: 0 sayl 1 ohdliyi
has comment: http://stackoverflow.com/comment/86799212
upvote count: 14
score: 14
answers question: http://stackoverflow.com/q/49891778
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86799463

http://stackoverflow.com/comment/86625004
type: Comment
score: 0
has text: Hi Austin, could you give feedback on whether your issue was solved?
type: QuestionComment
comment on: http://stackoverflow.com/q/49761406

http://stackoverflow.com/q/49826242
has body: I'm trying to build a TensorFlow extension that uses the DatasetOpKernel in TensorFlow 1.6. I'm building on Ubuntu 16.04. Weirdly, the DatasetOpKernel symbols are not present in the shared library in TensorFlow 1.6, though they are for TensorFlow 1.7. My plugin fails to load due to symbol not found errors related to the DatasetOpKernel and I've confirmed using nm that no DatasetOpKernel symbols are present in the TensorFlow provided shared library. I'm using the shared library that's installed during a pip install tensorflow==1.6.0 The DatasetOpKernel is clearly part of TensorFlow 1.6 (https://github.com/tensorflow/tensorflow/blob/r1.6/tensorflow/core/kernels/data/dataset.h#L548) so I'd like to know how to properly link to it in my extension.
tagged with: python
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: tensorflow
type: Question
has title: TensorFlow DatasetOpKernel symbols missing from shared library in TensorFlow 1.6.0
has answer: http://stackoverflow.com/a/49848294

http://stackoverflow.com/comment/86749819
has text: https://blog.miguelgrinberg.com/post/using-celery-with-flask check out this example. You can easily run the task as microservice if processing is involved. In the mean time update user on the progress and once task completes you can display it to the user.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49864298
type: QuestionComment

http://stackoverflow.com/a/49910581
downvote count: 0
upvote count: 1
has body: try printing x[i] and y[i] seperaterly so you know which of the 2 causes the keyerror. Also please post the function because without it we have no clue what's going on.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49909524

http://stackoverflow.com/q/49901047
type: Question
accepted answer: http://stackoverflow.com/a/49901989
has body: I'm playing around with different transform coding such as the DWT, DCT and DFT. I've been questioning my approach to the data structure I'm using when it comes to execution time. Here is an example below, say I want to analyze every individual pixel in an image, perhaps to perform encoding of some sort. All I'm doing here is loading each pixel on the same variable "a" to demonstrate a very generic example. This code snippet takes around 66mS which is quite slow for me. Is there a better approach to Image processing when it comes to individual reading and writing of pixels? class Example(): def __init__(self): self.load_image("lena_312.png") #312 by 312 def load_image(self, directory): self.img = cv2.imread(directory) self.height,self.width,self.channel = self.img.shape self.img_org = np.matrix(self.img[:,:,0]) #Image is greyscale def test(self): for j in range(0,self.height): for i in range(0,self.width): a = self.img_org[j,i] if __name__ == "__main__": EX = Example() start = time.time() EX.test() print time.time()-start
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49901989
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86819362
has title: Python image pixel access is very slow
tagged with: image-processing

http://stackoverflow.com/a/49885668
type: Answer
has comment: http://stackoverflow.com/comment/86820486
has comment: http://stackoverflow.com/comment/86787933
has body: The problem is the feed you’re using does not include an image. If you print d.feed you’ll see the available fields for the feed. Or you can see that by looking directly at the source https://www.thenews.com.pk/rss/1/1 (there’s no image tag for the channel).
has comment: http://stackoverflow.com/comment/86903439
has comment: http://stackoverflow.com/comment/86787551
has comment: http://stackoverflow.com/comment/86787644
score: 0
answers question: http://stackoverflow.com/q/49884912
has comment: http://stackoverflow.com/comment/86787948
has comment: http://stackoverflow.com/comment/86787976
has comment: http://stackoverflow.com/comment/86787442
has comment: http://stackoverflow.com/comment/86787673

http://stackoverflow.com/comment/86740714
type: AnswerComment
has text: I think you mean "python -m pip install [module name]?" I tried it before (also now), it does not work :'(
comment on: http://stackoverflow.com/a/49862657
type: Comment
score: 0

http://stackoverflow.com/q/49823631
tagged with: pandas
tagged with: python
tagged with: regex
score: 8
has answer: http://stackoverflow.com/a/49823695
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86663330
answer count: 2
has title: Pythonic way of applying regex to all columns of dataframe
has answer: http://stackoverflow.com/a/49845505
possible better answer: http://stackoverflow.com/a/49845505
downvote count: 0
has body: I have a dataframe containing keywords and value in all columns. See the example below. I want to apply regex to all the columns. So I use for loop and apply the regex: for i in range (1,maxExtended_Keywords): temp = 'extdkey_' + str(i) Extended_Keywords[temp] = Extended_Keywords[temp].str.extract(":(.*)",expand=True) And I get the desired final result. No issues there. However, just curios is there a pythonic way to apply regex to entire dataframe instead of using for loop and applying to column wise. Thanks,
upvote count: 8
has comment: http://stackoverflow.com/comment/86663215
favorite count: 0
accepted answer: http://stackoverflow.com/a/49823695
type: Question

http://stackoverflow.com/comment/86761955
score: 0
comment on: http://stackoverflow.com/q/49872844
type: QuestionComment
has text: You should provide some more information about the actual code, the error traceback etc
type: Comment

http://stackoverflow.com/comment/86795562
score: 0
type: AnswerComment
has text: @AlexHall that is a good point. In addition to being simpler, checking `word != other` is also more robust because it will handle the case of a repeated word in the list.
comment on: http://stackoverflow.com/a/49886591
type: Comment

http://stackoverflow.com/a/49878765
downvote count: 0
upvote count: 1
has body: Using str.join s = ['https://test.com/test.jpg', 'https://test.com/test.jpg'] print(" ".join(s)) Output: https://test.com/test.jpg https://test.com/test.jpg
answers question: http://stackoverflow.com/q/49878746
score: 1
type: Answer

http://stackoverflow.com/a/49818791
type: Answer
accepted answer of: http://stackoverflow.com/q/49808684
has body: You cannot mix and match "bind by position" and "bind by name", which is what you are doing in the above code. My suggestion would be to do something like this instead: output_list=[] catlist = ','.join(":x%d" % i for i, _ in enumerate(category_list)) bindvals = category_list + [arguser] db_cursor = connection.cursor() db_cursor.execute(""" SELECT LWEX_WORD_EXCLUDE FROM WCG_SRC_WORD_EXCLUDE WHERE LWEX_CATEGORY IN (%s) and LWIN_USER_UPDATED = :did""" % catlist, bindvals) for word in db_cursor : output_list.append(word[0])
answers question: http://stackoverflow.com/q/49808684
downvote count: 0
upvote count: 1
type: AcceptedAnswer
score: 1
has comment: http://stackoverflow.com/comment/86660972

http://stackoverflow.com/comment/86804310
comment on: http://stackoverflow.com/a/49893723
type: Comment
type: AnswerComment
score: 0
has text: You need to give me more info about what is happening on your side, added image for proof.

http://stackoverflow.com/a/49802991
answers question: http://stackoverflow.com/q/49802357
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: I haven't tried very hard to read your code. I note that you can solve that system symbolically using sympy. As usual with sympy terms in function definitions and equations must all be moved to one side of equals sign. The initial conditions are passed in a dict. &gt;&gt;&gt; from sympy import * &gt;&gt;&gt; from sympy.solvers.recurr import rsolve &gt;&gt;&gt; var('n') n &gt;&gt;&gt; s = Function('s') &gt;&gt;&gt; f = s(n) - s(n-1) -s(n-2) &gt;&gt;&gt; rsolve(f, s(n), {s(0):1, s(1):1}) (1/2 + sqrt(5)/2)**n*(sqrt(5)/10 + 1/2) + (-sqrt(5)/2 + 1/2)**n*(-sqrt(5)/10 + 1/2)

http://stackoverflow.com/q/49831926
type: Question
has body: How do you route the root path (i.e., /) to a view? This is my simple setup: import sys import wsgiref.simple_server from pyramid.config import Configurator from pyramid.response import Response from pyramid.view import view_config def main(argv): # Create Application. with Configurator() as config: app = config.make_wsgi_app() # Serve HTTP requests. server = wsgiref.simple_server.make_server('localhost', 8080, app) server.serve_forever() return 0 @view_config(name='') def page(request): return Response("Root") if __name__ == '__main__': sys.exit(main(sys.argv)) When I request http://localhost:8080/, I'm just getting a 404 response. From the log: 127.0.0.1 - - [14/Apr/2018 09:14:50] "GET / HTTP/1.1" 404 153 Response body: 404 Not Found 404 Not Found The resource could not be found. I'm running Python 3.5 and Pyramid 1.9.1.
tagged with: python-3.x
tagged with: pyramid
has title: Why isn't the root path routing to my view?
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49832731
score: 0
has answer: http://stackoverflow.com/a/49832731
answer count: 1

http://stackoverflow.com/q/49903122
has body: I recently ran into the need to disable transaction requests in one of my views, in order to be able to call db.connection.close() and connect() during requests in an effort to improve performance. I have a DRF ViewSet, and used the following very simple view to verify that the non_atomic_requests decoractor seems to have no effect. ATOMIC_REQUESTS=True is enabled in settings.py, and DEBUG=False. from django.db import transaction @transaction.non_atomic_requests def create(self, *args, **kwargs): m = MyModel(stuff="hello") m.save() raise Exception('exception! row should still be saved though') return Response() After calling the view, I open Django shell, and verify that the amount of rows in the db has not grown, even though it should have. Also opening a debugger during the request to halt execution after the line m.save(), I can observe in Django shell that a new row is not visible yet. If I set ATOMIC_REQUESTS=False in settings.py, the code works as expected, and the number of rows in the db is grown by one, even if an error is raised before returning from the view. When ATOMIC_REQUESTS=False, using @transaction.atomic decorator does work as expected though. So as a workaround, I could use it to set every other view as atomic instead... I am currently thinking this is a bug in the framework. Can anybody verify my findings, or point out if I am misunderstanding how this decorator is meant to function? I am using Python 3.6, Django 2.0 and DRF 3.7.7.
tagged with: transactions
possible better answer: http://stackoverflow.com/a/75198894
tagged with: python
has comment: http://stackoverflow.com/comment/86822518
has answer: http://stackoverflow.com/a/75198894
has answer: http://stackoverflow.com/a/78061029
accepted answer: http://stackoverflow.com/a/49903525
score: 12
has answer: http://stackoverflow.com/a/49903525
answer count: 3
upvote count: 12
downvote count: 0
tagged with: django
tagged with: django-rest-framework
type: AnsweredQuestion
has title: Django decorator @transaction.non_atomic_requests not working in a ViewSet method
favorite count: 0
type: Question

http://stackoverflow.com/a/49885796
type: Answer
has body: You should first stringify your JSON data: $(document).ready(function() { var table = $('#example').DataTable(); $('button').click( function() { var TableData = new Array(); $('#example tr').each(function(row, tr){ TableData[row]={ "id" : $(tr).find('td:eq(0)').text() , "student_name" :$(tr).find('td:eq(1)').text() , "marks" : $(tr).find('td:eq(2) input', this).val() , "is_present" : $(tr).find('td:eq(3) select', this).val() } }); TableData.shift(); // first row will be empty - so remove alert(TableData); $.ajax({ type: "POST", url: "{% url 'result:ajax_update_result' %}", dataType: 'json', data: JSON.stringify({'TableData': TableData}), success: function(msg){ alert(msg); } }); return false; } ); }); And retrieve it from request.POST: import json def save_result(request): table_data = json.loads(request.POST.get('TableData')) print(table_data) return render(request, 'data/dummy.html', {'msg': 'Data Saved.'}) Note I'm using json.loads since your data is now stringified. EDIT: I just realized you were actually stringifying your TableData...however, you were trying to pull from a non-existent key TableData from request.GET. I believe my updated answer should work for you.
has comment: http://stackoverflow.com/comment/86788098
has comment: http://stackoverflow.com/comment/86797179
downvote count: 0
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/49885711

http://stackoverflow.com/a/49817613
score: 0
answers question: http://stackoverflow.com/q/49817500
type: Answer
has body: Try sorted(x_list) and sorted(rest_list) instead. x_list = sorted(x_list) rest_list = sorted(rest_list) return [x_list, rest_list]

http://stackoverflow.com/comment/86542293
has text: Where is that 'nginx conf' file located?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49760595
type: QuestionComment

http://stackoverflow.com/q/49808038
has body: I am looking to create a MultiIndex in pandas from a Cartesian product, with the catch that one of the levels is "special" and will be associated with an arbitrary number of additional levels that I would like to "unfold" in the same way as the special level. The end result is much easier to demonstrate than describe. The code below shows a case where I want to create a MultiIndex based on the Cartesian product of id and loc but have color and shape unfolded in the same way as 'id'. Two different methods for doing this are shown in the example. For this contrived case these are adequate solutions, but for my real use case where the DataFrame will have > 10 million rows neither of these approaches satisfies my performance requirements. What is the best approach for creating such a MultiIndex? import pandas as pd import numpy as np id = np.asarray([1,2,3,4,5]) color= np.asarray(['red','blue','green','orange','purple']) shape = np.asarray(['square','circle','triangle','rectangle','oval']) loc = np.asarray(['CA','OR']) idx = pd.MultiIndex.from_product([id,loc], names=['ID','LOC']) data = np.ravel(np.random.rand(5,2)) # Approach 1 df1 = pd.DataFrame(data, index=idx) df1['color'] = color[idx.labels[0]] df1['shape'] = shape[idx.labels[0]] df1.set_index(['color','shape'],append=True,inplace=True) print(df1) # Approach 2 idx2 = pd.MultiIndex.from_arrays([id[idx.labels[0]],loc[idx.labels[1]],color[idx.labels[0]],shape[idx.labels[0]]],names=['ID','LOC','color','shape']) df2 = pd.DataFrame(data, index=idx2) print(df2)
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 2
tagged with: pandas
has title: Create pandas MultiIndex from Cartesian Product but "Unfold" Several Levels in the Same way
answer count: 1
has answer: http://stackoverflow.com/a/49808113
favorite count: 0
type: Question

api
tags question: http://stackoverflow.com/q/49832952
tag name: api
tags question: http://stackoverflow.com/q/49839967
tags question: http://stackoverflow.com/q/49767387
tags question: http://stackoverflow.com/q/49830718
tags question: http://stackoverflow.com/q/49785006
tags question: http://stackoverflow.com/q/49826968
tags question: http://stackoverflow.com/q/49841793
tags question: http://stackoverflow.com/q/49768214
tags question: http://stackoverflow.com/q/49807373
tags question: http://stackoverflow.com/q/49764481
tags question: http://stackoverflow.com/q/49863164
tags question: http://stackoverflow.com/q/49761879
tags question: http://stackoverflow.com/q/49846559
type: Tag
tags question: http://stackoverflow.com/q/49849264
tags question: http://stackoverflow.com/q/49887198
tags question: http://stackoverflow.com/q/49786200
tags question: http://stackoverflow.com/q/49889379
tags question: http://stackoverflow.com/q/49763283
tags question: http://stackoverflow.com/q/49760858

http://stackoverflow.com/a/49825802
type: Answer
has body: I haven't really tested this but this is what I can come up just by reading the docs: import boto3 ddb = boto3.resource('dynamodb') table = ddb.Table('your_table') document = table.get_item(Key={'pKey': 10001})['Item'] for item in document['items']: item['value'] = 200 table.put_item(Item=document, ReturnValues='NONE')
answers question: http://stackoverflow.com/q/49825638
upvote count: 3
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/86668049
has comment: http://stackoverflow.com/comment/92223534

http://stackoverflow.com/q/49845195
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49845600
has body: In one program, I need to create a matrix, which can be of shape, e.g, matrix.shape(x,100). The first dimension of shape cannot be known beforehand, so I just use X here. In an iteration, the program will generate one dimensional array such as 'Y.shape = (100,1)`. So the program works as this matrix = [] index = 0 for i in range(XY): if something matrix[index,:] = Y index = index+1 I am not sure whether I can initialize matrix this way, and do I need to reshape Y when I assign matrix{index,:]=Y in some iterations shown as above.
has comment: http://stackoverflow.com/comment/86705646
has answer: http://stackoverflow.com/a/49845600
has comment: http://stackoverflow.com/comment/86705387
tagged with: python
score: -1
type: AnsweredQuestion
has title: define a matrix which does not know one dimension beforehand
downvote count: 2
answer count: 1

http://stackoverflow.com/comment/86715517
type: Comment
type: AnswerComment
has text: you mean dont know how create index? check edit and this one http://mysql.rjweb.org/doc.php/index_cookbook_mysql
comment on: http://stackoverflow.com/a/49846149
score: 0

http://stackoverflow.com/q/49847971
type: Question
tagged with: auc
type: UnansweredQuestion
tagged with: python
has body: I'm trying to find the AUC value using tf.contrib.metrics.streaming_auc. This issue is that after each epoch, I'm having AUC values as follows: (0.0, 0.37472612) (0.0, 0.57414174) (0.0, 0.5894814) ... If I understood the documentation correctly, the first value (i.e. 0.0) represents the auc, and the second value represents update_op. Which value is actually representing the AUC value after each epoch in this case? Thanks.
has answer: http://stackoverflow.com/a/49863630
score: 0
has title: tf.contrib.metrics.streaming_auc - what value represents my AUC
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/86632768
type: QuestionComment
comment on: http://stackoverflow.com/q/49808929
score: 0
has text: you really ought to minimize the provided code that it captures your problem without all the extra crap, and then clarify what you are trying to do.
type: Comment

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/49839924
tags question: http://stackoverflow.com/q/49764802
tags question: http://stackoverflow.com/q/49900875
tags question: http://stackoverflow.com/q/49853968
tags question: http://stackoverflow.com/q/49902066
tag name: python-packaging

http://stackoverflow.com/q/49914882
has body: This is the error : Solving environment: failed UnsatisfiableError: The following specifications were found to be in conflict: - numba -> numpy[version='>=1.14,&lt;1.15.0a0'] - tensorflow Use "conda info " to see the dependencies for each package.
answer count: 2
has comment: http://stackoverflow.com/comment/86853697
type: UnansweredQuestion
tagged with: python
tagged with: conda
has answer: http://stackoverflow.com/a/49915763
has comment: http://stackoverflow.com/comment/86847068
has answer: http://stackoverflow.com/a/55354760
score: 0
tagged with: anaconda
has title: I get the following error whenever I try to run conda install tensorflow
has comment: http://stackoverflow.com/comment/86857253
tagged with: tensorflow
tagged with: jupyter-notebook
type: Question

http://stackoverflow.com/a/56540890
score: 16
has comment: http://stackoverflow.com/comment/115532158
answers question: http://stackoverflow.com/q/49759940
upvote count: 16
type: Answer
has comment: http://stackoverflow.com/comment/115555784
has comment: http://stackoverflow.com/comment/129313985
has comment: http://stackoverflow.com/comment/100138174
downvote count: 0
has body: In order to get the size of an S3 folder, objects (accessible in the boto3.resource('s3').Bucket) provide the method filter(Prefix) that allows you to retrieve ONLY the files which respect the Prefix condition, and makes it quite optimised. import boto3 def get_size(bucket, path): s3 = boto3.resource('s3') my_bucket = s3.Bucket(bucket) total_size = 0 for obj in my_bucket.objects.filter(Prefix=path): total_size = total_size + obj.size return total_size So let's say you want to get the size of the folder s3://my-bucket/my/path/ then you would call the previous function like that: get_size("my-bucket", "my/path/") Then this of course is easily applicable to top level folders as well. UPDATE obj has other interesting fields like key - really helpful to get a list of object keys under a specified Prefix.
has comment: http://stackoverflow.com/comment/115544324

http://stackoverflow.com/q/49814881
has body: I'm looking for a smooth way to sort a pandas Series by data descending, followed by index ascending. I've been looking around in the docs and on Stackoverflow but couldn't find a straightforward way. The Series has approximately 5000 entries and is the result of a tf-idf analysis with NLTK. However, below I provide a very small sample of the data to illustrate the problem. import pandas as pd index = ['146tf150p', 'anytime', '645', 'blank', 'anything'] tfidf = [1.000000, 1.000000, 1.000000, 0.932702, 1.000000] tfidfmax = pd.Series(tfidf, index=index) For now I'm just converting the Series to a DataFrame, resetting the index, doing the sort and then setting the index, but I feel this is a big detour. frame = pd.DataFrame(tfidfmax , columns=['data']).reset_index().sort_values(['data','index'], ascending=[False, True]).set_index(['index']) 3.02 ms ± 102 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) I'm looking forward to your suggestions!
tagged with: python
tagged with: sorting
score: 4
downvote count: 1
linked to: http://stackoverflow.com/q/40850764
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has title: Sort Pandas Series on data descending then on index alphabetically, elegantly
accepted answer: http://stackoverflow.com/a/49814962
has answer: http://stackoverflow.com/a/49814962
possible better answer: http://stackoverflow.com/a/49815738
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49815035
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49815738
upvote count: 5

http://stackoverflow.com/q/49788769
has comment: http://stackoverflow.com/comment/86689769
has comment: http://stackoverflow.com/comment/86592985
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/86592774
answer count: 0
has body: How can I fix the error of: CMake Error at /usr/local/Cellar/cmake/3.11.0/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:137 (message): Could NOT find PythonInterp: Found unsuitable version "1.4", but required is at least "3" (found /usr/local/bin/python3) where CMake is finding the wrong version of python. How can I fix this, as python --version Python 2.7.14 geoheil@eduroam-078-104-029-050 ~ [17:34:02] &gt; $ python3 --version Python 3.6.5 already returns the right versions of python which were installed via home-brew? edit here some clarifications: - cmake also was installed via home-brew which python /usr/local/bin/python geoheil@geoheils-MacBook ~ [8:01:12] &gt; $ which python2 /usr/local/bin/python2 geoheil@geoheils-MacBook ~ [8:01:15] &gt; $ which python3 /usr/local/bin/python3 geoheil@geoheils-MacBook ~ [8:01:18] &gt; $ echo $PATH /Users/geoheil/development/flutter/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/usr/local/MacGPG2/bin:/opt/X11/bin:/Applications/Wireshark.app/Contents/MacOS:/usr/local/bin:/Library/oracle/instantclient_12_1 edit 2 some more clarifications &gt; $ which make /usr/bin/make geoheil@geoheils-MacBook ~ [11:20:25] &gt; $ which cmake /usr/local/bin/cmake geoheil@geoheils-MacBook ~ [11:20:27] &gt; $ ls -l /usr/local/bin/make ls: /usr/local/bin/make: No such file or directory ls /usr/local/bin |grep make automake automake-1.16 ccmake cmake cmakexbuild a detailed stack tracke CMake Error at /usr/local/Cellar/cmake/3.11.0/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:137 (message): Could NOT find PythonInterp: Found unsuitable version "1.4", but required is at least "3" (found /usr/local/bin/python3) Call Stack (most recent call first): /usr/local/Cellar/cmake/3.11.0/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:376 (_FPHSA_FAILURE_MESSAGE) /usr/local/Cellar/cmake/3.11.0/share/cmake/Modules/FindPythonInterp.cmake:155 (FIND_PACKAGE_HANDLE_STANDARD_ARGS) CMakeLists.txt:696 (FIND_PACKAGE) bre…
has comment: http://stackoverflow.com/comment/86595425
tagged with: homebrew
has comment: http://stackoverflow.com/comment/86882698
downvote count: 0
has comment: http://stackoverflow.com/comment/86687604
tagged with: cmake
favorite count: 0
has title: CMake finding wrong version of python
has comment: http://stackoverflow.com/comment/86687621
type: Question
has comment: http://stackoverflow.com/comment/86596970
tagged with: pythoninterpreter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86599902
tagged with: python

http://stackoverflow.com/comment/86741613
comment on: http://stackoverflow.com/a/49862669
type: AnswerComment
score: 0
has text: I don't know. There are *many* questions on SO on how to extract filenames using standard libraries, I suggest you look them up.
type: Comment

http://stackoverflow.com/comment/86544854
comment on: http://stackoverflow.com/q/49764606
has text: Also, if you use `with lock:` instead of `lock.acquire()`, it will automatically be released when you leave the `with` statement, so you don't need to put separate `lock.release()` calls all over the place (and you don't risk abandoning the lock if you get an exception, or just forget to `release` on one code path).
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49899208
has body: I want to break PumpWaitingMessages for every one hour and check for any unread mails and I tried with following code. However, if I increase time.time()-starttime&gt;10 then my outlook is hanging and not able to progress, Sometimes I am even able to get following error: This is related to How to continuously monitor a new mail in outlook and unread mails of a specific folder in python pTraceback (most recent call last): File "final.py", line 94, in &lt;module&gt; outlook_open=processExists('OUTLOOK.EXE') File "final.py", line 68, in processExists print('process "%s" is running!' % processname) IOError: [Errno 0] Error Please check the code and help me to resolve this. import win32com.client import ctypes # for the VM_QUIT to stop PumpMessage() import pythoncom import re import time import os import subprocess import pyodbc class Handler_Class(object): def __init__(self): # First action to do when using the class in the DispatchWithEvents outlook=self.Application.GetNamespace("MAPI") inbox=outlook.Folders['mymail@gmail.com'].Folders['Inbox'] messages = inbox.Items print "checking Unread mails" # Check for unread emails when starting the event for message in messages: if message.UnRead: print message.Subject.encode("utf-8") # Or whatever code you wish to execute. message.UnRead=False def OnQuit(self): # To stop PumpMessages() when Outlook Quit # Note: Not sure it works when disconnecting!! print "Inside handler onQuit" ctypes.windll.user32.PostQuitMessage(0) def OnNewMailEx(self, receivedItemsIDs): # RecrivedItemIDs is a collection of mail IDs separated by a ",". # You know, sometimes more than 1 mail is received at the same moment. for ID in receivedItemsIDs.split(","): mail = self.Session.GetItemFromID(ID) subject = mail.Subject print subject.encode("utf-8") mail.UnRead=False try: command = re.search(r"%(.*?)%", subject).group(1) print command # Or whatever code you wish to execute. except: pass # Function to check if outlook is open def processExists(processname):…
has comment: http://stackoverflow.com/comment/86817029
tagged with: win32com
has comment: http://stackoverflow.com/comment/86842687
tagged with: python
has answer: http://stackoverflow.com/a/49924466
accepted answer: http://stackoverflow.com/a/49924466
type: AnsweredQuestion
score: 0
tagged with: subprocess
has comment: http://stackoverflow.com/comment/86842935
linked to: http://stackoverflow.com/q/49695160
answer count: 1
has comment: http://stackoverflow.com/comment/86842844
has comment: http://stackoverflow.com/comment/86816918
has title: How to break PumpWaitingMessages for every one hour and check for any unread mails
type: Question
tagged with: pythoncom

http://stackoverflow.com/comment/86683954
type: AnswerComment
has text: Thanks folks for talking a look, I'm accepting jpp's answer as it does exactly what I'm looking for in a generic way.
comment on: http://stackoverflow.com/a/49834167
score: 0
type: Comment

http://stackoverflow.com/q/49894329
score: 3
upvote count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/50408178
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87831003
possible better answer: http://stackoverflow.com/a/50414656
has comment: http://stackoverflow.com/comment/87831968
tagged with: python
has answer: http://stackoverflow.com/a/50414656
has title: Customised start and end date of the month
has body: I have a data frame which contains date and value. I have to compute sum of the values for each month. i.e., df.groupby(pd.Grouper(freq='M'))['Value'].sum() But the problem is in my data set starting date of the month is 21 and ending at 20. Is there any way to tell that group the month from 21th day to 20th day to pandas. Assume my data frame contains starting and ending date is, starting_date=datetime.datetime(2015,11,21) ending_date=datetime.datetime(2017,11,20) so far i tried, starting_date=df['Date'].min() ending_date=df['Date'].max() month_wise_sum=[] while(starting_date&lt;=ending_date): temp=starting_date+datetime.timedelta(days=31) e_y=temp.year e_m=temp.month e_d=20 temp= datetime.datetime(e_y,e_m,e_d) month_wise_sum.append(df[df['Date'].between(starting_date,temp)]['Value'].sum()) starting_date=temp+datetime.timedelta(days=1) print month_wise_sum My above code does the thing. but still waiting for pythonic way to achieve it. My biggest problem is slicing data frame for month wise for example, 2015-11-21 to 2015-12-20 Is there any pythonic way to achieve this? Thanks in Advance. For Example consider this as my dataframe. It contains date from date_range(datetime.datetime(2017,01,21),datetime.datetime(2017,10,20)) Input: Date Value 0 2017-01-21 -1.055784 1 2017-01-22 1.643813 2 2017-01-23 -0.865919 3 2017-01-24 -0.126777 4 2017-01-25 -0.530914 5 2017-01-26 0.579418 6 2017-01-27 0.247825 7 2017-01-28 -0.951166 8 2017-01-29 0.063764 9 2017-01-30 -1.960660 10 2017-01-31 1.118236 11 2017-02-01 -0.622514 12 2017-02-02 -1.416240 13 2017-02-03 1.025384 14 2017-02-04 0.448695 15 2017-02-05 1.642983 16 2017-02-06 -1.386413 17 2017-02-07 0.774173 18 2017-02-08 -1.690147 19 2017-02-09 -1.759029 20 2017-02-10 0.345326 21 2017-02-11 0.549472 22 2017-02-12 0.814701 23 2017-02-13 0.983923 24 2017-02-14 0.551617 25 2017-02-15 0.001959 26 2017-02-16 -0.537112 27 2017-02-17 1.251595 28 2017-02-18 1.448950 29 2017-02-19 -0.452310 .. ... ... 243 2017-09-21 0.791439 244 2017-09…
type: AnsweredQuestion
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/50408178

http://stackoverflow.com/q/49881436
has body: im trying to execute an py file from php, using bat file . the whole code works fine and im trying to execute an file name dbConn.py the file executes when seperatly double clicked i.e executed and output is reflected the code from php is this: if ($conn-&gt;query($sql) === TRUE) { mysqli_close($conn); $cmd = "run_dbConn.bat" ; execInBackground($cmd); } else { echo "Error: " . $sql . "&lt;br&gt;" . $conn-&gt;error; } This is code for runcmd.php &lt;?php function execInBackground($cmd) { if (substr(php_uname(), 0, 7) == "Windows"){ pclose(popen("start /B ". $cmd, "r")); } else { exec($cmd . " &gt; /dev/null &amp;"); } } ?&gt; and code for run_dbConn.bat cd C:\xampp\htdocs\eclipse_workspace\Project python dbConn.py ECHO %1 echo even the above code make the file to run , which i have checked from task bar. but the output is not generated or reflected. the dbConn.py does not have something related to code and can be executed separately.... plzz help me out even a suggestion will be well.
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: cmd
tagged with: exec
downvote count: 1
favorite count: 0
type: Question
has title: py file call successful but no output
tagged with: python
score: -1
tagged with: php
has answer: http://stackoverflow.com/a/49881705
tagged with: batch-file

http://stackoverflow.com/comment/86538427
has text: @coquelicot Thanks. That makes more senes.
type: Comment
comment on: http://stackoverflow.com/a/49761398
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86665286
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49824630
has text: The proper way from the UX perspective: when the condition is met redirect the user to a view where he/she confirms the delete. Never do destructive operations implicitly and non-reversible at the same time.

http://stackoverflow.com/q/49831072
has title: Drop with condition
type: Question
duplicate of: http://stackoverflow.com/q/13851535
tagged with: python-3.x
has body: I have certain rows that I want to drop from the df1. I did write the conditions this way and showed me the exact rows that I wanted to delete. However, when I try to apply drop on this data, it doesn't work : to_be deleted = df1.loc[df1['barcode'].str.contains('....-..-....-11.', regex=True)] when I use to_be deleted.head() print(len(to_be deleted)) I can see the data that I want to delete, which means the code worked. However, when I try drop these rows, it doesn't work df2 = df1.drop([df1['barcode'].str.contains('....-..-....-11.', regex=True)], axis=1, inplace=True) also I tried df2 = df1.drop(to_be_deleted, axis=1, inplace=True) but it either shows : 'Series' objects are mutable, thus they cannot be hashed or /anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame How can I drop these rows I specified in (to_be_deleted) data frame? Thank you
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49831090
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/13851535
has comment: http://stackoverflow.com/comment/86677426
answer count: 1

http://stackoverflow.com/q/49837159
upvote count: 3
downvote count: 0
tagged with: floating-point
has body: It is well known that floating point values cannot exactly represent every decimal value. Thus, the floating point value for 1/3 is not exactly 1/3. For this reason, it is generally inadvisable to compare floating point values directly. However, in this application, I am trying to determine if two fractions a / b and c / d are equivalent. If they are, then there exist integers e and f such that a * e = c * f and b * e = d * f. Assume a, b, c, d, e, f are all positive integers which can be represented exactly in a floating point value. In practice, simply comparing a/b to c/d worked, but is it guaranteed to work? Is there something within Python and/or IEEE-754 that would guarantee such a scheme to work? Example code (that shows this scheme works for a reasonable number of values): a = 1.0 b = 3.0 for c in xrange(1, 999): assert a / b == (a * c) / (b * c) If this is not guaranteed, is there a counterexample with values a, b, c, d such that a/b = c/d (in math) but Python fails to compare a / b == c / d? Again, these are all positive integers which Python can exactly represent in its floating point value.
favorite count: 0
type: Question
has title: consistency of floating point division
has comment: http://stackoverflow.com/comment/86689695
has comment: http://stackoverflow.com/comment/86689658
has comment: http://stackoverflow.com/comment/86689650
has answer: http://stackoverflow.com/a/49837338
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86690153
tagged with: python
has answer: http://stackoverflow.com/a/49837292
has answer: http://stackoverflow.com/a/49837916
score: 3
answer count: 3

http://stackoverflow.com/q/49871124
has comment: http://stackoverflow.com/comment/86762064
has comment: http://stackoverflow.com/comment/86762373
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86767478
has comment: http://stackoverflow.com/comment/86767405
type: Question
tagged with: python-3.x
has title: Insert the CSV data into Elasticsearch in Python
has comment: http://stackoverflow.com/comment/86764933
type: UnansweredQuestion
has body: I am new to Elasticsearch I want to insert the bulk data from the CSV to Elasticsearch and my code is: class MyEncoder1(json.JSONEncoder): def default(self, obj): if isinstance(obj,datetime.date): obj= datetime.strptime(obj,"%Y-%m-%d ") elif isinstance(obj, datetime.datetime): obj= datetime.strptime(obj,"%Y-%m-%d %H:%M:%S.%f") elif isinstance(obj, datetime.time): obj = datetime.time.strftime(obj,"%H:%M:%S") elif isinstance(obj, Decimal): obj = float(obj) else: obj = super(MyEncoder1, self).default(obj) return obj Function to write data: def elastic(): FILE = "C:\\Users\\home\\Downloads\\elasticsearch-6.2.3\\test.csv" ES_HOST = { "host" : "localhost", "port" : 9200 } INDEX_NAME = 'listusers' TYPE_NAME = 'users' ID_FIELD = 'id' f = open(FILE, 'r') reader = csv.reader(f) header=["id","title"] bulk_data = [] for row in reader: data_dict = {} for i in range(len(row)): data_dict[header[i]] = row[i] print(data_dict) op_dict = {"index": { "_index": INDEX_NAME, "_type": TYPE_NAME, "_id": data_dict[ID_FIELD]}} bulk_data.append(op_dict) bulk_data.append(data_dict) json_array = dumps(bulk_data,cls=MyEncoder1) request_body = { "settings" : { "number_of_shards": 1, "number_of_replicas": 0 }} es = Elasticsearch(hosts = [ES_HOST]) ##print("creating '%s' index..." % (INDEX_NAME)) res = es.indices.create(index = INDEX_NAME, body = request_body) print(" response: '%s'" % (res)) ##res = es.bulk(index = INDEX_NAME, body = json_array, refresh = True) And the JSON array output is: [{"index": {"_type": "users", "_index": "listusers", "_id": "1"}}, {"title": "I am in india", "id": "1"}, {"index": {"_type": "users", "_index": "listusers", "_id": "2"}}, {"title": "I am in america", "id": "2"}, {"index": {"_type": "users", "_index": "listusers", "_id": "3"}}, {"title": "I am in japan", "id": "3"}] And the error I am getting is: elasticsearch.exceptions.TransportError: TransportError(406, 'Content-Type header [] is not supported')
tagged with: elasticsearch
tagged with: python

http://stackoverflow.com/comment/86777177
comment on: http://stackoverflow.com/a/49880587
score: 0
type: AnswerComment
has text: A slight improvement: only add `a[0]` to `found` if it is not already in there (i.e. increase the indentation by one level for `found.add(a[0])`).
type: Comment

http://stackoverflow.com/q/49862614
favorite count: 0
type: Question
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49862741
tagged with: byte
tagged with: twos-complement
tagged with: java
has body: The byte 0xea is equal to 234 in base 10. In Python, bytes are represented using unsigned integers, but in Java, they are signed, two's complement integers. For example, in Java, if I cast (byte)234, I get the signed integer -22. When I use those bytes in a MessageDigest, I get the same exact hash output as when I use the unsigned 234 in python. So I am confident that these represent the same byte. However, in Clojure, the function (byte 234) should cast to -22, but instead it throws a clojure.lang.RT.byteCast exception. How can I cast integers to bytes in Clojure?
tagged with: python
tagged with: clojure
upvote count: 2
has answer: http://stackoverflow.com/a/49862741
downvote count: 0
answer count: 1
has title: How to cast an int larger than 127 to a byte in Clojure

http://stackoverflow.com/q/49879758
upvote count: 1
tagged with: function
tagged with: python
has answer: http://stackoverflow.com/a/49879793
type: AnsweredQuestion
has title: pandas.DataFrame: difference between inplace = True and assigning the same variable?
downvote count: 0
tagged with: pandas
score: 1
tagged with: in-place
tagged with: variable-assignment
has body: I am replacing -np.inf and np.inf with np.nan within a pandas data frame. However, using the inplace = True, I get a warning: df.replace([np.inf, -np.inf], np.nan, inplace = True) SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame whereas just re-assigning the variable to itself (not sure whether this is a smart idea), but that seems to "solve" the issue: df = df.replace([np.inf, -np.inf], np.nan) I have read in another question that python distinguish between a copy and a view, and if it's not clear somehow modifying one variable could affect the other too. Should restrain from making use of inplace? Just as background: I have a data frame with stock prices, however with missing value. I have a function that uses this data frame, but "cleans" up the data before processing. def func(df): df_aux = df.dropna(axis = 1) df_aux.replace([np.inf, -np.inf], np.nan, inplace = True) df_aux.fillna(method = 'ffill', inplace = True) some calculation with df_aux return x
favorite count: 0
possible better answer: http://stackoverflow.com/a/60074072
type: Question
accepted answer: http://stackoverflow.com/a/49879793
answer count: 2
has answer: http://stackoverflow.com/a/60074072

http://stackoverflow.com/q/49849185
type: Question
has comment: http://stackoverflow.com/comment/86713049
type: UnansweredQuestion
has body: I installed Python 3.6.3 on Windows with Anaconda packages. I tried several times to install tensorflow by creating new environments and following the ways people mentioned in this forum. I always receive the message "No module named tensorflow". I was wondering if the tensorflow is developed for this version of Python.
has comment: http://stackoverflow.com/comment/86738670
tagged with: python
score: 0
answer count: 0
has title: I receive the message "No module named tensorflow" in every attempt to install tensorflow
has comment: http://stackoverflow.com/comment/86713000
tagged with: tensorflow

http://stackoverflow.com/comment/86838061
type: AnswerComment
comment on: http://stackoverflow.com/a/49910937
has text: Thanks for your suggestion. But I would need something like `df.query('index == 8, 18')` and this will not work.
type: Comment
score: 0

http://stackoverflow.com/a/49764532
downvote count: 0
has body: This is from the logical short-cuts that many languages take. The and operator in this case appears in the low-level code as if it were: a = 2 b = 4 return b if a else a ... or if not a: return a else: return b This works as expected with Boolean values. With other data types, the result is non-intuitive (until you get used to it).
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49764495

http://stackoverflow.com/comment/86736305
has text: @AaronMazie You've set tags in Your question: `node.js` and `forever` and You wrote that error says `Unexpected token import` that means in some part of Your code use such line: `import SomePackage from 'some-library'` that is not supported natively by nodejs and it's being converted using transpilers (babel). But now You're saying that You use Python? How come? Whaaat (: Can You share `app.js` file in Your question?
comment on: http://stackoverflow.com/a/49837485
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49813964
score: 1
has body: I have a table with about 200 columns. I need to take a dump of the daily transaction data for ETL purposes. Its a MySQL DB. I tried that with Python both using pandas dataframe as well as basic write to CSV file method. I even tried to look for the same functionality using shell script. I saw one such for oracle Database using sqlplus. Following are my python codes with the two approaches: Using Pandas: import MySQLdb as mdb import pandas as pd host = "" user = '' pass_ = '' db = '' query = 'SELECT * FROM TABLE1' conn = mdb.connect(host=host, user=user, passwd=pass_, db=db) df = pd.read_sql(query, con=conn) df.to_csv('resume_bank.csv', sep=',') Using basic python file write: import MySQLdb import csv import datetime currentDate = datetime.datetime.now().date() host = "" user = '' pass_ = '' db = '' table = '' con = MySQLdb.connect(user=user, passwd=pass_, host=host, db=db, charset='utf8') cursor = con.cursor() query = "SELECT * FROM %s;" % table cursor.execute(query) with open('Data_on_%s.csv' % currentDate, 'w') as f: writer = csv.writer(f) for row in cursor.fetchall(): writer.writerow(row) print('Done') The table has about 300,000 records. It's taking too much time with both the python codes. Also, there's an issue with encoding here. The DB resultset has some latin-1 characters for which I'm getting some errors like : UnicodeEncodeError: 'ascii' codec can't encode character '\x96' in position 1078: ordinal not in range(128). I need to save the CSV in Unicode format. Can you please help me with the best approach to perform this task. A Unix based or Python based solution will work for me. This script needs to be run daily to dump daily data.
possible better answer: http://stackoverflow.com/a/49814091
tagged with: python
has answer: http://stackoverflow.com/a/49814091
has title: What is the best way to dump MySQL table data to csv and convert character encoding?
tagged with: unix
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49815667
has comment: http://stackoverflow.com/comment/86643685
answer count: 3
tagged with: pandas
downvote count: 0
linked to: http://stackoverflow.com/q/12040816
tagged with: mysql
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49814081
has answer: http://stackoverflow.com/a/49814081
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/86683628
comment on: http://stackoverflow.com/a/49834107
score: 1
has text: @ShahzadKhan That statement is contradictory. Use the tool that gives you the desired output, but `append` is not that tool.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86693019
type: Comment
type: QuestionComment
has text: @WarrenWeckesser List is a 2D list of lists. Each internal list will be 2 elements long. The total list will contain more than 90,000 such 2 element lists.
comment on: http://stackoverflow.com/q/49838872
score: 0

http://stackoverflow.com/comment/86652454
type: QuestionComment
score: 0
has text: @Stu your code has an error `channel_type = str(channel['mediaStream'])` ? Post more code with JSON data to validate.
comment on: http://stackoverflow.com/q/49818754
type: Comment

http://stackoverflow.com/comment/86791496
type: AnswerComment
has text: For [this](https://www.drugbank.ca/drugs/DB01048.xml) example, I can replicate above to get cas-number, but to get the information in the drug-interactions section (e.g. a list of interacting drug ids), why do neither of these codes work? `print {'drug interactions':child.find('{http://www.drugbank.ca}drug-interaction/name').text}` (or variations of that line) or `for node in drugbank.findall('.//drug-interactions/drug-interaction/drugbank-id'): print node`? For some tag names (e.g. 'name' could appear multiple times in different contexts), is there a way to be more specific about tag path?
comment on: http://stackoverflow.com/a/49778942
score: 0
type: Comment

http://stackoverflow.com/comment/86635694
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49810175
has text: I would like to add the map in the image to my code...
type: Comment

http://stackoverflow.com/comment/86582022
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49783229
type: Comment
has text: @Jtseng526: sure, we can construct 3-tuples as well.

http://stackoverflow.com/comment/86541009
type: Comment
type: QuestionComment
has text: Is there a reason you are attempting to do this? There's plenty of ways to accomplish this without writing your own code.
score: 0
comment on: http://stackoverflow.com/q/49762347

http://stackoverflow.com/q/49759993
tagged with: parallel-processing
type: AnsweredQuestion
has title: How to code an animation to run mutliple times in parallel in tkinter?
answer count: 2
tagged with: tkinter
score: 0
has answer: http://stackoverflow.com/a/49760543
possible better answer: http://stackoverflow.com/a/49763857
has body: I am trying to wrap my head around parallel animations. In the following code, clicking on a square will cause a small animation. But declaring 2 boxes (or more) makes things more difficult: The animation called last will run and cause the other to pause and resume only after it is complete. How to change my code so that all animation calls can run independently and in parallel? #!python3 import tkinter as tk import time class Example(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) # create a canvas self.canvas = tk.Canvas(width=400, height=400) self.canvas.pack() # create a couple of movable objects self._create_token(100, 100, "green") self._create_token(200, 100, "black") def _create_token(self, x, y, color): self.canvas.create_rectangle(x-25, y-25, x+25, y+25, outline=color, fill=color, tags=color) self.canvas.tag_bind(color, "&lt;ButtonPress-1&gt;", self.on_token_press) def on_token_press(self,event): Rx = self.canvas.find_closest(event.x, event.y) x = 0 y = 5 for i in range(25): time.sleep(0.025) self.canvas.move(Rx, x, y) self.canvas.update() for i in range(25): time.sleep(0.025) self.canvas.move(Rx, x, -y) self.canvas.update() if __name__ == "__main__": root = tk.Tk() Example(root).pack() root.mainloop()
has answer: http://stackoverflow.com/a/49763857
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49760543
tagged with: animation
has comment: http://stackoverflow.com/comment/86542171
tagged with: python

http://stackoverflow.com/comment/86749304
comment on: http://stackoverflow.com/a/49865243
type: Comment
score: 0
has text: Yay, it's working! Too bad I have no influence concerning the source of the data..
type: AnswerComment

http://stackoverflow.com/comment/86702151
score: 0
comment on: http://stackoverflow.com/q/49843280
has text: show us a sample data of thw csv file. the column date_added is defined as timestamp which will accept data in this format. '1970-01-01 00:00:01'
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86562375
type: QuestionComment
has text: Can you share a link to the website you are trying to parse or upload an HTML to any file exchange website and post here a link?
score: 0
comment on: http://stackoverflow.com/q/49772495
type: Comment

http://stackoverflow.com/comment/86667554
score: 0
has text: Are you asking what *algorithm* to use, or how to implement it?
comment on: http://stackoverflow.com/q/49825896
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49896402
has title: Matrix Factorization find from which users score is generated
has answer: http://stackoverflow.com/a/49896559
favorite count: 0
tagged with: matrix-factorization
answer count: 1
score: -2
has body: I am building a user based recommendation engine with Python and LightFM and I am trying to figure out how the score of a user to product is generated from the other users. Specifically, I am trying to answer the following questions: 1) Which users influence the predicted score of an another user over a product? 2) How can I find these users?
tagged with: recommendation-engine
type: Question
upvote count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python

http://stackoverflow.com/comment/86835465
comment on: http://stackoverflow.com/a/49909485
score: 2
type: Comment
type: AnswerComment
has text: This completely defeats the point of a dict though. Now you have linear lookup.

http://stackoverflow.com/comment/86832859
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49908444
has text: The above analysis is for 6 GB file only.

http://stackoverflow.com/comment/86754210
type: AnswerComment
comment on: http://stackoverflow.com/a/49869004
score: 0
has text: AWESOME NEWS! I am so excited. I carefully understood what you wrote to me and applied it to another try loop! perfect parsing now! Now on to the next step applying the zip code dictionary and multiple requests for the entire USA
type: Comment

http://stackoverflow.com/q/49848517
has comment: http://stackoverflow.com/comment/86737803
has answer: http://stackoverflow.com/a/58650814
answer count: 14
has answer: http://stackoverflow.com/a/66666815
has answer: http://stackoverflow.com/a/63112976
has title: biopython no module named Bio
has body: FYI: this is NOT a duplicate! Before running my python code I installed biopython in the cmd prompt: pip install biopython I then get an error saying 'No module named Bio' when try to import it in python import Bio The same thing happens with import biopython It should be noted I have updated PIP and run python 3.5.2 I appreciate anyone's help.
has answer: http://stackoverflow.com/a/60753930
has answer: http://stackoverflow.com/a/60895283
tagged with: python
tagged with: biopython
favorite count: 0
has answer: http://stackoverflow.com/a/66727603
has answer: http://stackoverflow.com/a/62287552
has comment: http://stackoverflow.com/comment/86714096
tagged with: python-3.x
linked to: http://stackoverflow.com/q/24627525
has answer: http://stackoverflow.com/a/64504758
has comment: http://stackoverflow.com/comment/86733435
type: Question
has answer: http://stackoverflow.com/a/49848544
has answer: http://stackoverflow.com/a/70185762
tagged with: bioinformatics
downvote count: 0
has answer: http://stackoverflow.com/a/59184820
tagged with: pip
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/60856778
has comment: http://stackoverflow.com/comment/86713881
has answer: http://stackoverflow.com/a/60244116
upvote count: 19
score: 19
has answer: http://stackoverflow.com/a/60529858

http://stackoverflow.com/q/49868377
has body: I have the following df: dfdict = {'letter': ['a', 'a', 'a', 'b', 'b'], 'category': ['foo', 'foo', 'bar', 'bar', 'spam']} df1 = pd.DataFrame(dfdict) category letter 0 foo a 1 foo a 2 bar a 3 bar b 4 spam b I want it to output me an aggregated count df like this: a b foo 2 0 bar 1 1 spam 0 1 This seems like it should be an easy operation. I have figured out how to use df1 = df1.groupby(['category','letter']).size() to get: category letter bar a 1 b 1 foo a 2 spam b 1 This is closer, except now I need the letters a, b along the top and the counts coming down.
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49868407
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49868407
type: AnsweredQuestion
has title: Python: dataframe manipulation and aggregation in pandas
tagged with: pandas
score: 3
upvote count: 3
answer count: 1
tagged with: dataframe

http://stackoverflow.com/comment/86645350
type: AnswerComment
has text: What exactly do you mean by "I require QGraphicsItem"? [`QGraphicsItem`](http://doc.qt.io/qt-5/qgraphicsitem.html) doesn't inherit from `QObject` but `QGraphicsObject` inherits from both `QGraphicsItem` *and* `QObject`. So, as far as I can see replacing `QGraphicsItem` with `QGraphicsObject` should work just fine in this case.
score: 1
comment on: http://stackoverflow.com/a/49815397
type: Comment

http://stackoverflow.com/a/49876074
has body: You can filter by slicers first, then rename first level and use arithmetic operations, last concat together: #avoid UnsortedIndexError df = df.sort_index() idx = pd.IndexSlice c1 = chv.loc[idx['C',:,'mean'], :].rename({'C':'CH'}, level=0) h1 = chv.loc[idx['H',:,'mean'], :].rename({'H':'CH'}, level=0) ch1 = c1 - h1 c2 = chv.loc[idx['C',:,'std'], :].rename({'C':'CH'}, level=0)**2 h2 = chv.loc[idx['H',:,'std'], :].rename({'H':'CH'}, level=0)**2 ch2 = (c2 + h2)**.5 df = pd.concat([chv, ch1, ch2]).sort_index() print (df) 0 1 2 3 first second third C one mean 7.000000 5.000000 8.000000 3.000000 std 0.000000 4.000000 4.000000 4.000000 three mean 4.000000 2.000000 1.000000 6.000000 std 8.000000 7.000000 3.000000 3.000000 two mean 1.000000 8.000000 2.000000 5.000000 std 2.000000 2.000000 4.000000 2.000000 CH one mean 1.000000 2.000000 1.000000 2.000000 std 4.000000 7.211103 4.000000 7.211103 three mean 1.000000 0.000000 -4.000000 2.000000 std 8.062258 7.071068 4.242641 3.000000 two mean -1.000000 6.000000 -2.000000 3.000000 std 9.219544 7.280110 4.123106 2.000000 H one mean 6.000000 3.000000 7.000000 1.000000 std 4.000000 6.000000 0.000000 6.000000 three mean 3.000000 2.000000 5.000000 4.000000 std 1.000000 1.000000 3.000000 0.000000 two mean 2.000000 2.000000 4.000000 2.000000 std 9.000000 7.000000 1.000000 0.000000 V one mean 9.000000 5.000000 0.000000 5.000000 std 7.000000 9.000000 1.000000 1.000000 three mean 3.000000 0.000000 3.000000 4.000000 std 1.000000 4.000000 9.000000 2.000000 two mean 3.000000 6.000000 3.000000 2.000000 std 1.000000 3.000000 1.000000 4.000000
has comment: http://stackoverflow.com/comment/86785658
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86772072
accepted answer of: http://stackoverflow.com/q/49875793
has comment: http://stackoverflow.com/comment/86786134
score: 1
answers question: http://stackoverflow.com/q/49875793
has comment: http://stackoverflow.com/comment/86785577
type: Answer

http://stackoverflow.com/comment/86705441
has text: @Mr.T Thank you. but there is no `plt` in this code.
score: 0
comment on: http://stackoverflow.com/q/49845125
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49822358
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/86660241
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86660476
has body: I have the list of dicts like: list_of_dict = [{}, {'a': 2}, {'a': 3}, {'b': 2, 'c': 4}] and want to create a new list like: new_list = [{'a': 2, 'b': 2, 'c':4}, {'a': 3}] where dicts are combined if they don't have keys intersection or values of intersected keys are the same. I take first pair, check intersected keys (and values if intersection is) then delete this pair and replace with new dict. When should I stop? list_of_dict = [{}, {'a': 2}, {'a': 3}, {'b': 2, 'c': 4}] keys_a = set(list_of_dict[0].keys()) keys_b = set(list_of_dict[1].keys()) intersection = keys_a &amp; keys_b while ??: if not intersection or //check intersected is equal//: list_of_dict[0].update(list_of_dict[1]) list_of_dict.pop(1) print list_of_dict Solution for 2.7 import copy dcts = [] buffer = {} for i in list_of_dict: if not i or any(j in buffer for j in i.keys()): buffer = i else: new_ = copy.deepcopy(i) new_.update(buffer) buffer = copy.deepcopy(new_) dcts.append(buffer) print dcts
has comment: http://stackoverflow.com/comment/86660204
has comment: http://stackoverflow.com/comment/86660636
type: AnsweredQuestion
score: 2
upvote count: 3
has title: how to union list of dicts python
has comment: http://stackoverflow.com/comment/86660367
answer count: 1
accepted answer: http://stackoverflow.com/a/49822603
downvote count: 1
has answer: http://stackoverflow.com/a/49822603
has comment: http://stackoverflow.com/comment/86660291
favorite count: 0

http://stackoverflow.com/comment/86578982
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49781573
has text: I guess if you want to use that variable for more than logging, a Java kind of approach would be to store this variable inside a "config" class (which would store other configurations as well) @JoranBeasley Great minds think alike!

http://stackoverflow.com/a/49907987
type: Answer
answers question: http://stackoverflow.com/q/49903830
score: 0
has body: Here is a method that only works if your test and rows consist of not too large integers (non negative as well but this can be relaxed if need be). But then it's fast: &gt;&gt;&gt; rows = np.array([3, 4]) &gt;&gt;&gt; test = np.array([1, 3, 3, 4, 5]) &gt;&gt;&gt; data = np.array([-1, 2]) &gt;&gt;&gt; &gt;&gt;&gt; limit = 1&lt;&lt;20 &gt;&gt;&gt; assert all(a.dtype in map(np.dtype, np.sctypes['int']) for a in (rows, test)) &gt;&gt;&gt; assert np.all(rows&gt;=0) and np.all(test&gt;=0) &gt;&gt;&gt; mx = np.maximum(np.max(rows), np.max(test)) + 1 &gt;&gt;&gt; assert mx &lt;= limit &gt;&gt;&gt; lookup = np.empty((mx,), data.dtype) &gt;&gt;&gt; lookup[test] = 0 &gt;&gt;&gt; lookup[rows] = data &gt;&gt;&gt; result = lookup[test] &gt;&gt;&gt; result array([ 0, -1, -1, 2, 0])

http://stackoverflow.com/comment/87264462
type: AnswerComment
score: 1
has text: Downvoter care to explain? Don't worry, I don't retaliate, just want to know what we can improve..
type: Comment
comment on: http://stackoverflow.com/a/49772121

http://stackoverflow.com/q/49862247
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86788879
score: 0
answer count: 0
tagged with: templates
type: Question
has title: Django - Looping through a dictionary using a second variable in template
has comment: http://stackoverflow.com/comment/86780333
type: UnansweredQuestion
has body: I'm trying my best not to repeat myself in my code but I'm encountering a problem looping through a dictionary by key in my template. I have two dicts: exampledict={'firstkey':firstval, 'secondkey':secondval} keys=['firstkey', 'secondkey'] keydict={'keys':keys} In my template I want to loop over the exampledict using the keydict: {% for val in keydict %} {{ exampledict.val }} {% endfor %} I've noticed this kind of combination of variables doesn't work at all, I tried by using: {'firstkey':'firstkey'} And sending that through to the template and later trying {{ exampledict.firstkey }} Is there a better way to accomplish what I'm trying to do here? Edit 1: Manually going through each key as: {{ exampledict.firstkey }} {{ exampledict.secondkey }} Where firstkey and secondkey is the actual dictkey for exampledict works, although it makes for a lot of repetition. Edit 2: views.py def tabletest(request): exampledict={'firstkey':'firstval', 'secondkey': 'secondval'} keydict={ 'keys':['firstkey', 'secondkey'] } return render(request, 'MinaFakturor/tabletest.html', {'exampledict':exampledict, 'keydict':keydict}) template {% for val in keydict.keys %} {{ val }} {% endfor %} {% for val in keydict.keys %} {{ exampledict.val }} {% endfor %} {{ exampledict.firstkey }} Which produces this result: If I remove the exampledict.firstkey term, nothing is produced in the table body.
linked to: http://stackoverflow.com/q/49875924
tagged with: django

http://stackoverflow.com/comment/86707288
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49845987
type: Comment
has text: what happens when you ```print(interfaces)``` after printing candidateNet? Because it seems like interfaces can't be empty because it's successfully being used in the get_net_info function.

http://stackoverflow.com/comment/86577135
has text: Currently I only have this Intel GFX chip built-in into CPU, and I doubt it supports CUDA (does it?), so I stick with CPU version anyway. I know about cmd alternatives, but I like Cygwin because of its "linux" flavor, toolchain and stuff. So, as to TF, I have no choice, until I buy some decent NVIDA card, but then maybe I should generally upgrade my whole hardware. ;-)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49762985

http://stackoverflow.com/a/50847832
has body: It wasn't of topic, it was an error even if just a memory error. Anyway in the end I just exported to CSV rather than XSLX as Excel still opens it nicely, not worth the bother.
type: Answer
answers question: http://stackoverflow.com/q/49814616
score: 0

http://stackoverflow.com/q/49833244
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86681778
has answer: http://stackoverflow.com/a/49833329
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/86682386
has body: I'm having a problem with my code: when I make a search in the i-th column of the matrix it gives me the following error: if grades[:,i]!=-3: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() I have tried to read the older posts on this issue, but can't really relate to my problem I am trying to program a grading function according to danish grading-scale def computeFinalGrades(grades): #looping over the leth of grades for i in range(len(loopingrange)): #checking if any grade in the i-th coloumn is -3 if grades[:,i]==-3: #if a grade is equal to -3 then the output variabel gradesFinal is -3 gradesFinal = -3 else: #looping over all grade coloumns that do not contain one or more grades of -3 for i in range(len(loopingrange)): #Checking to see if any coloumn only contains 1 grade if (len(grades[:,i]) == 1): # if a coloumn only contains 1 grade - that is also the final grade gradesFinal = grades[:,i] #Checking to see if coloumn contains more than 1 grade and those grades are not -3 elif (len(grades[:,i]) &gt; 1): #storing all the grades in a variabel - in random order unsortedgrades = grades[:,i] #sorting all the grades from lowest to highest sortedgrades1 = np.sort(unsortedgrades) #slicing the lowest grade out using indexing sortedgrades = sortedgrades1[1::] #finding the final grade as the mean of the n-1 grades gradesFinal = np.mean(sortedgrades) return gradesFinal
answer count: 1
has title: Error_message: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

http://stackoverflow.com/comment/86709274
score: 0
comment on: http://stackoverflow.com/q/49846246
has text: There is a block diagonal method in scipy, maybe you could use that. Why do you need to construct the matrix in theano? https://docs.scipy.org/doc/scipy-1.0.0/reference/generated/scipy.linalg.block_diag.html#scipy.linalg.block_diag
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86631376
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49803270
score: 0
has text: I am not sure what alternatives I should try, thus the above is all I have to offer so far. I am using Windows 7, I experience the same problem on Win 10. 64 bit both.

http://stackoverflow.com/q/49853222
favorite count: 0
has title: Create a stacked graph or bar graph using plotly in python
type: Question
accepted answer: http://stackoverflow.com/a/49862327
upvote count: 2
has comment: http://stackoverflow.com/comment/86724913
has answer: http://stackoverflow.com/a/49862327
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86724059
type: AnsweredQuestion
has body: I have data like this : [ ('2018-04-09', '10:18:11',['s1',10],['s2',15],['s3',5]) ('2018-04-09', '10:20:11',['s4',8],['s2',20],['s1',10]) ('2018-04-10', '10:30:11',['s4',10],['s5',6],['s6',3]) ] I want to plot a stacked graph preferably of this data. X-axis will be time, it should be like this I created this image in paint just to show. X axis will show time like normal graph does( 10:00 ,April 3,2018). I am stuck because the string value (like 's1',or 's2' ) will change in differnt bar graph. Just to hard code and verify,I try this: import plotly import plotly.graph_objs as go import matplotlib.pyplot as plt import matplotlib plotly.offline.init_notebook_mode() def createPage(): graph_data = [] l1=[('com.p1',1),('com.p2',2)('com.p3',3)] l2=[('com.p1',1),('com.p4',2)('com.p5',3)] l3=[('com.p2',8),('com.p3',2)('com.p6',30)] trace_temp = go.Bar( x='2018-04-09 10:18:11', y=l1[0], name = 'top', ) graph_data.append(trace_temp) plotly.offline.plot(graph_data, filename='basic-scatter3.html') createPage() Error I am getting is Tuple Object is not callable. So can someone please suggest some code for how I can plot such data. If needed,I may store data in some other form which may be helpful in plotting. Edit : I used the approach suggested in accepted answer and succeed in plotting using plotly like this fig=df.iplot(kin='bar',barmode='stack',asFigure=True) plotly.offline.plt(fig,filename="stack1.html) However I faced one error: 1.When Time intervals are very close,Data overlaps on graph. Is there a way to overcome it.
tagged with: pandas
score: 1
tagged with: plotly
tagged with: bar-chart
answer count: 1
has comment: http://stackoverflow.com/comment/86722101
downvote count: 1

http://stackoverflow.com/comment/86808889
has text: @TomMakin yes I changed it and worked without any problem, thank you, but this time when I fit it to X, it created a (200,200) array. I was aiming to see the explained variance ratios to choose the first n components, but there is no such attribute for kernel PCA, unlike normal PCA. Is there any way to check the explained variance ratios to decide how many Principle Components to use?
type: QuestionComment
comment on: http://stackoverflow.com/q/49894411
score: 0
type: Comment

http://stackoverflow.com/comment/86820829
comment on: http://stackoverflow.com/q/49902448
score: 3
type: Comment
type: QuestionComment
has text: When pandas reads from the CSV it tries to infer the dtype. Columns can only have one dtype, so you can't have column of `int64` with a string in it. This would be stored as an object, the container for basically whatever. When it sees something like `1,760.60` it sees a comma and so it decides that it's not a number so it stores it as a string and gives that column `dtype=object`. If it's simply a comma which is messing things up try adding `thousands=','` to your `pd.read_csv()` arguments and it might get it on the initial read.

http://stackoverflow.com/comment/86656564
comment on: http://stackoverflow.com/q/49819309
score: 0
type: Comment
type: QuestionComment
has text: Can you please make your example clearer? Why is PersonnelDetails a list? I don't mind if you just call your columns A, B, C, D. Just make sure your inputs and desired output are *consistent* and this will encourage us to help.

http://stackoverflow.com/q/49861167
has title: How to get HTML Input using Python Flask
tagged with: input
has answer: http://stackoverflow.com/a/49861184
tagged with: python
accepted answer: http://stackoverflow.com/a/49861184
score: 4
tagged with: flask
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 1
tagged with: forms
favorite count: 0
type: Question
upvote count: 5
has body: I am planning to get input from an HTML Form when submitted, the input will be send over to Python. Here is the HTML File Send Message Now I don't know the best way to do this, I tried this in Python but doesn't seem to work @app.route('/', methods=['POST']) def form_post(): userEmail = request.form['userEmail'] userPassword = request.form['userPassword'] return userEmail, userPassword Can anyone help me out here?

http://stackoverflow.com/comment/86664451
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49823859
has text: Relevant: https://stackoverflow.com/questions/5626193/what-is-monkey-patching

http://stackoverflow.com/q/49805306
downvote count: 3
has body: I have three lists: list1 = [1, 5, 5, 4, 2] list2 = [1, 4, 5, 3, 4] list3 = [2, 5, 4, 3, 4] I want to return the most occurring number in each column so for example: Column 1 will return 1 since there are {1, 1, 2} and 1 is most occurring Column 2 will return 5 since there are {5, 4, 5} and 5 is most occurring Column 3 will return 5. For these lists, I want to get [1, 5, 5, 3, 4]. The list will always have equal length.
answer count: 1
has comment: http://stackoverflow.com/comment/86625543
has comment: http://stackoverflow.com/comment/86625480
has comment: http://stackoverflow.com/comment/86625490
has answer: http://stackoverflow.com/a/49805447
accepted answer: http://stackoverflow.com/a/49805447
linked to: http://stackoverflow.com/q/10797819
favorite count: 0
type: Question
has title: Compare multiple lists and return most frequently occurring number column-wise (most common value by index)
tagged with: python
score: -1
upvote count: 2
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/86656826
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49820886
has text: My initial thought too but OP is iterating over each character in the string, so the `elif`/`if` shouldn't make a difference.
type: Comment

http://stackoverflow.com/a/49835682
type: Answer
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49832036
upvote count: 1
has body: Try it: from PyQt5.QtWidgets import (QWidget, QApplication, QTabWidget, QLabel, QPushButton, QVBoxLayout, QMenuBar, QAction) class MainWidget(QWidget): def __init__(self, textLabel, *args, **kwargs): super(MainWidget, self).__init__(*args, **kwargs) layout = QVBoxLayout(self) self.label = QLabel(textLabel, self) self.btn = QPushButton('Next', self) layout.addWidget(self.label) layout.addWidget(self.btn) class Window(QWidget): def __init__(self): super().__init__() bar = QMenuBar(self) menu = bar.addMenu('File') action = QAction('Close activ tab', self) menu.addAction(action) action.triggered.connect(self.closeActivTab) self.tabwdg = QTabWidget() self.tabwdg.setTabsClosable(True) self.tabWidget = MainWidget('this is the first page') self.tabwdg.addTab(self.tabWidget, 'first') self.tabWidget.btn.clicked.connect(self.numTab) self.tabWidget = MainWidget('this is the second page') self.tabwdg.addTab(self.tabWidget, 'second') self.tabWidget.btn.clicked.connect(self.numTab) self.tabWidget = MainWidget('this is the third page') self.tabwdg.addTab(self.tabWidget, 'third') self.tabWidget.btn.clicked.connect(self.numTab) self.tabWidget = MainWidget('this is the fourth page') self.tabwdg.addTab(self.tabWidget, 'fourth') self.tabWidget.btn.clicked.connect(self.numTab) self.tabwdg.tabCloseRequested.connect(self.closeTab) box = QVBoxLayout() box.addWidget(bar) box.addWidget(self.tabwdg) self.setLayout(box) def numTab(self): nextTab = self.tabwdg.currentIndex()+1 if nextTab == self.tabwdg.count(): nextTab = 0 self.tabwdg.setCurrentIndex(nextTab) self.tabwdg.setCurrentWidget(self.tabwdg.currentWidget()) def closeActivTab(self): activ_tab_ind = self.tabwdg.currentIndex() self.closeTab(activ_tab_ind) def closeTab(self, ind): self.tabwdg.removeTab(ind) if __name__ == '__main__': import sys app = QApplication(['']) w = Window() w.resize(400, 300) w.show() sys.exit(app.exec_())
accepted answer of: http://stackoverflow.com/q/49832036
score: 1

http://stackoverflow.com/q/49849683
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86713954
has comment: http://stackoverflow.com/comment/86714195
has body: I tried reading through many similar questions (this seemed closest: Python sum dict values based on keys) but still struggling to answer the following question below. Boiling it down to basics I have the following 3 dictionaries with lists as keys: {'milk': ['gallons', 5, 10, 50]} {'eggs': ['cartons', 5, 2, 10]} {'bacon': ['packages', 5, 7, 35]} I want to be able to sum the last value of each nested list and have an expected, single value of 95 printed to the screen. I've seen answers to similar questions that involve lambdas but I know there has to be a way to do this with iterating through the list. I've seen the use of sum and Counter and am open to any explanations. Thank you in advance. UPDATE/ADDED CONTEXT Thank you to those who have already been responding. I realize more context may be needed to answer this. These entries are being made from this class: class GroceryCart(dict): def __init__(self): self = {} def addToCart(self, item, units, quantity, price): item_total = quantity*price self.update({item:[units, quantity, price, item_total]}) def returnCart(self): return self my_cart = GroceryCart() That is where you are getting the funky structure of info. I tried @ggorlan's response below but got traceback errors about not having str values to use .values() Traceback (most recent call last): File "grocery_store.py", line 156, in &lt;module&gt; total = sum(sum(y[-1] for y in x.values()) for x in my_cart) File "grocery_store.py", line 156, in &lt;genexpr&gt; total = sum(sum(y[-1] for y in x.values()) for x in my_cart) AttributeError: 'str' object has no attribute 'values'
linked to: http://stackoverflow.com/q/11692613
has answer: http://stackoverflow.com/a/49855319
has comment: http://stackoverflow.com/comment/86714003
linked to: http://stackoverflow.com/q/32632516
upvote count: 1
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49849906
has title: Python - List nested in dict - how to sum single value
has answer: http://stackoverflow.com/a/49849781
accepted answer: http://stackoverflow.com/a/49855319
type: AnsweredQuestion
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/86714251
tagged with: sum
has comment: http://stackoverflow.com/comment/86714497
has answer: http://stackoverflow.com/a/49850011
has comment: http://stackoverflow.com/comment/86714064
has comment: http://stackoverflow.com/comment/86713960
possible better answer: http://stackoverflow.com/a/49849781
has comment: http://stackoverflow.com/comment/86714494
downvote count: 1
answer count: 4

http://stackoverflow.com/a/49888865
has comment: http://stackoverflow.com/comment/86793855
accepted answer of: http://stackoverflow.com/q/49888643
type: Answer
answers question: http://stackoverflow.com/q/49888643
score: 3
has comment: http://stackoverflow.com/comment/86793899
upvote count: 3
has comment: http://stackoverflow.com/comment/86793839
has comment: http://stackoverflow.com/comment/86793925
type: AcceptedAnswer
downvote count: 0
has body: Try: cursor.execute("SELECT * from place WHERE typeOfPlace=?", (typeVar,)) The trailing comma after typeVar might look odd, but params expects a sequence, and adding the trailing comma makes the value passed a tuple of length 1. Never use string formatting to pass in values to an SQL query. Bad things can happen if the variable contains SQL syntax. Look up SQL injection attacks for more details on why you should not do this. Passing parameters separately as I’ve done here is the way to go.

http://stackoverflow.com/comment/86828008
has text: What have you tried yourself?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49906092
type: Comment

http://stackoverflow.com/a/49837502
has comment: http://stackoverflow.com/comment/86690299
answers question: http://stackoverflow.com/q/49837479
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/86690374
has comment: http://stackoverflow.com/comment/86690357
accepted answer of: http://stackoverflow.com/q/49837479
has body: You could use itertools.combinations(): import itertools a = [0,0,3,4,1,2,9] av = [int(sum(i)/2) for i in itertools.combinations(a, 2) if sum(i)%2 == 0] Output: [0, 2, 1, 2, 1, 2, 6, 3, 5]
score: 1

http://stackoverflow.com/q/49762941
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49766653
has title: Unable to select Chosen dropdown list with Selenium
has body: I am trying to click one of the tags in a Select Dropdown created with Chosen JQuery library. All languages English Arabic Chinese (Simplified) Chinese (Traditional) All languages All languages English Arabic Chinese (Simplified) Chinese (Traditional) Hungarian Italian <li id="languagesSelect_chzn_o_15" Below is how I attempt to select 'English' from the dropdown list: field_language_select = Select(driver.find_element_by_id('languagesSelect')) field_language_select.select_by_visible_text('English') However I receive this error: ElementNotVisibleException: element not visible: Element is not currently visible and may not be manipulated (Session info: chrome=65.0.3325.181) (Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Windows NT 10.0.16299 x86_64) I TRIED: Performing click() on the dropdown and sending down arrow keys followed by enter. I received WebDriverException: unknown error: cannot focus element Moving to the div of the select tag by actions.move_to_element(div_element) but it didn't change anything. How do I manage to select an element from that dropdown list?
has answer: http://stackoverflow.com/a/49765787
has answer: http://stackoverflow.com/a/70301261
score: 0
has answer: http://stackoverflow.com/a/49766715
has answer: http://stackoverflow.com/a/68603594
tagged with: python
tagged with: jquery-chosen
tagged with: selenium-webdriver
type: Question

http://stackoverflow.com/q/49906024
type: Question
has comment: http://stackoverflow.com/comment/86827969
has comment: http://stackoverflow.com/comment/86827999
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86828022
has comment: http://stackoverflow.com/comment/86832386
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86828151
has comment: http://stackoverflow.com/comment/86828273
tagged with: pandas
has comment: http://stackoverflow.com/comment/86828099
tagged with: python
has title: How Sort_index works in Pandas
has body: I was trying to undestand how sort_index works in pandas. I ma quite confused with the results I got when i tested with two dataframes. I have df1 sorted with index 'pid' df1: pid,day,score1,score2 100,Fri,200,108 ...... 221,Wed,546,789 221,Sat,123,456 The second data frame sorted with index 'pid' df2: pid,day,score1,score2 100,Fri,230,18 ...... 221,Sat,563,324 221,Wed,111,789 I couldn't understand why PID# 221 is sorted differently in both cases. Ideally both should follow same sorting as i am sorting by index. Any help on this is highly appreciated.

http://stackoverflow.com/a/49776145
score: 1
upvote count: 1
has body: import os import glob import csv from xlsxwriter.workbook import Workbook for csvfile in glob.glob(os.path.join('.', '*.csv')): workbook = Workbook(csvfile[:-4] + '.xlsx') worksheet = workbook.add_worksheet() with open(csvfile, 'rt', encoding='utf8') as f: reader = csv.reader(f) for r, row in enumerate(reader): for c, col in enumerate(row): worksheet.write(r, c, col) workbook.close()
answers question: http://stackoverflow.com/q/49775963
type: Answer
has comment: http://stackoverflow.com/comment/86634460
downvote count: 0

http://stackoverflow.com/a/50051575
score: 7
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49849164
has comment: http://stackoverflow.com/comment/87223888
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/87229175
has body: 1. The 'u\0080' problem First thing first, it seems that the interpretation of the 'u\0080' character depends on the platform you are using, it doesn't print on a Windows 7 machine but it works on a Linux machine... For completeness, I have assumed that you get your text from an html document containing the '&amp;#x80;' escape sequence (which should print as € in a browser), the '\u0080' character and some other arbitrary symbols we identify as currencies. Before passing the text content to spaCy, we can call html.unescape which will take care of translating &amp;#x80; to €, which in turn is going to be recognized by the default configuration as a currency. text_html = ("I just found out that CAD 1,000 is about 641.3 &amp;#x80. " "Some people call it 641.3 \u0080. " "Fantastic! But in the U.K. I'd rather pay 344 or \U0001F33B56.") text = html.unescape(text_html) Second, if there are symbols that are not recognized as a currency, like and for example, then we can change the Defaults of the language we use to qualify them as currencies. That consists in replacing the lex_attr_getters[IS_CURRENCY] function by a custom one which holds a list of symbols describing a currency. def is_currency_custom(text): # Stripping punctuation table = str.maketrans({key: None for key in string.punctuation}) text = text.translate(table) all_currencies = ["\U0001F385", "\U0001F33B", "\u0080", "CAD"] if text in all_currencies: return True return is_currency_original(text) # Keep a reference to the original is_currency function is_currency_original = EnglishDefaults.lex_attr_getters[IS_CURRENCY] # Assign a new function for IS_CURRENCY EnglishDefaults.lex_attr_getters[IS_CURRENCY] = is_currency_custom 2. The CAD 5,000 problem For this one, a simple solution would be to define a special case. We say to the tokenizer that, wherever it meets CAD, this is a special case and it needs to do as instructed by us. We can set the IS_CURRENCY flag amongst other things. special_case = [{ ORTH: u'CAD', …
accepted answer of: http://stackoverflow.com/q/49849164
has comment: http://stackoverflow.com/comment/87225834

http://stackoverflow.com/q/49910164
downvote count: 0
tagged with: pyqt5
has body: This is a function which is being called on a button click. It is supposed to display a line graph why is it not showing up. def plotk2(self): #----------------------------------------------------------------Data temp=full_dataset'country_txt','iyear','nkill' text = self.k_count.currentText() temp = temp[temp['country_txt'].str.match(text)] temp2=temp.groupby(['iyear'])['nkill'].count() temp2=temp2.to_frame() temp2['iyear']=temp2.index #---------------------------------------------------------------- self.figure.clear() ax = self.figure.add_subplot(111) plt.plot( 'nkill', 'iyear', data=temp2) #ax.axis('off') plt.show() self.canvas.draw()
upvote count: 1
answer count: 1
favorite count: 0
type: Question
tagged with: pandas
tagged with: matplotlib
has title: Why isn't my line graph showing up on GUI
tagged with: python
score: 1
accepted answer: http://stackoverflow.com/a/49910349
tagged with: pyqt
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49910349

http://stackoverflow.com/comment/86604372
type: Comment
has text: I cant seem to find anything like that. Can you please share a link. TIA
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49794765

http://stackoverflow.com/comment/86734067
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49859272
has text: Okay, thanks, It is a strategy I am trying to apply to find out best option among a lot of choices, but it is too long to say it here.

http://stackoverflow.com/a/49827025
downvote count: 0
answers question: http://stackoverflow.com/q/49827007
has comment: http://stackoverflow.com/comment/86669651
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49827007
type: Answer
has body: Python for loops are not like C for loops; the iteration value is replaced on each loop, discarding any changes made inside the loop. No matter what you do to i inside the for loop, when the for loop loops, you pull the next value from the iterator, so i will always progress through all the values in the range one at a time.
upvote count: 2
score: 2

http://stackoverflow.com/q/49812644
tagged with: toplevel
type: UnansweredQuestion
tagged with: python
has title: tkinter custom switch frame function difficulty
has answer: http://stackoverflow.com/a/49816868
score: 0
tagged with: tkinter
tagged with: switching
answer count: 1
has body: Using this code as a guide to try and make something of my own: https://stackoverflow.com/a/49325719/9543223 Trying to use the switch_frame function to set a new frame when a tkinter Toplevel widget is destroyed. The switching process is working, or at least its putting one frame in front of the other, however, I get this error at the end: line 49, in switch_frame self.frame.destroy() AttributeError: 'function' object has no attribute 'destroy' Now, I'm no expert, so its hard for me to follow all these 'self's... So I'm not quite sure why it can't destroy the previous frame... Is there something I need to change because I'm referencing the swtich_frame function inside another function in another class? Here's my code: import os import tkinter as tk from tkinter import ttk import sys import time Users = [('Admin','AdminPassword')] class main_window(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title('Pilot Flight and Duty Tracker') self.geometry('1000x700+250+50') self.resizable(width = False, height = False) self.frame = None self.switch_frame(Blank_Frame) Login_Window = Login(self) def switch_frame(self, frame_class): new_frame = frame_class() if self.frame is not None: self.frame.destroy() self.frame = new_frame self.frame.pack() else: self.frame = new_frame self.frame.pack() class Login(tk.Toplevel): def __init__(self, master, *args, **kwargs): tk.Toplevel.__init__(self, master, *args, **kwargs) self.resizable(width = False, height = False) self.title('User Login') self.attributes('-topmost', True) self.geometry('230x200+625+275') self.grab_set() self.transient(master) userlabel = tk.Label(self, text="Employee ID:", font='arial 10 bold') userlabel.place(x=25, y=5) self.user_entry = tk.Entry(self, relief='groove', width=25, font='arial 10', bd=1) self.user_entry.place(x=25, y=30) passwordlabel = tk.Label(self, text="Password:", font='arial 10 bold') passwordlabel.place(x=25, y=70) self.password_entry = tk.Entry(self, relie…
tagged with: frame
has comment: http://stackoverflow.com/comment/86649427
type: Question
linked to: http://stackoverflow.com/q/7546050

http://stackoverflow.com/comment/86575578
type: Comment
score: 0
type: AnswerComment
has text: Certainly :), sorry.
comment on: http://stackoverflow.com/a/49777827

http://stackoverflow.com/comment/86697496
has text: I'm sorry but it's unclear what you're asking... I don't know what is diceboard.index...
comment on: http://stackoverflow.com/q/49841155
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/86624086
has text: Looks like the build command line does say `--std=c++11`.
comment on: http://stackoverflow.com/q/49804654
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86591461
type: QuestionComment
type: Comment
has text: Try setting a pdb breakpoint inside `_init_data`.
score: 0
comment on: http://stackoverflow.com/q/49788025

http://stackoverflow.com/comment/86749322
score: 0
type: AnswerComment
has text: I like `np.stack`, even though for `axis=0` it behaves the same as `np.array. I don't like `np.append`. Too many novices misuse it. I prefer that they learn to use the underlying `np.concatenate`.
type: Comment
comment on: http://stackoverflow.com/a/49866794

http://stackoverflow.com/comment/86852514
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49848567
has text: @GordThompson I updated odbc to 5.3.10, and updated iodbc to 3.52, python3 is worked. So you can copy your comment to answer, I will accept it. Thanks for your help.
type: Comment

http://stackoverflow.com/q/49881299
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49881475
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49881583
has answer: http://stackoverflow.com/a/49881583
tagged with: dataframe
tagged with: python
tagged with: dictionary
has body: I currently have a dataframe and wish to input values using pairs of dictionaries. # create count dataframe range_of_years = range(2012, 2017) topics = ['ecology','evolution','mathematics','biogeography','neutral theory'] topic_count_timeline = pandas.DataFrame(index = topics, columns = range_of_years) # dictionary pair count_dict = {2012: 10, 2013: 20, 2014: 12, 2015: 8, 2016: 9} paper_topics_dict = {'ecology': 0.7, 'neutral theory': 0.3} I would like to iterate through the dictionary keys, selecting the dataframe cell with column and index that correspond to the keys, and then add the product of the dictionary values to that cell. Such that I would have the resultant dataframe: 2012 2013 2014 2015 2016 ecology 7 14 8.4 5.6 7.7 evolution NaN NaN NaN NaN NaN mathematics NaN NaN NaN NaN NaN biogeography NaN NaN NaN NaN NaN neutral theory 3 6 3.6 2.4 3.3 I intend to update the topic_count_timeline dataframe using many pairs of dictionaries like count_dict and paper_topic_dict such that new inputs are summed with the previous incumbent of the cell instead of overwriting. For example, if a further pair were used update the dataframe... # Additional dictionaries count_dict2 = {2012: 3, 2013: 2, 2014: 15, 2015: 16, 2016: 13} paper_topics_dict2 = {'mathematics': 0.6, 'neutral theory': 0.4} The dataframe would then look like this: 2012 2013 2014 2015 2016 ecology 7 14 8.4 5.6 7.7 evolution NaN NaN NaN NaN NaN mathematics 1.8 1.2 9 9.6 5.4 biogeography NaN NaN NaN NaN NaN neutral theory 4.2 6.8 9.6 8.8 8.5 Thank you.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49881467
has comment: http://stackoverflow.com/comment/86781411
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49881467
score: 1
downvote count: 0
has title: Using multiple dictionaries to populate a pandas dataframe
upvote count: 1
has comment: http://stackoverflow.com/comment/86780464

physics
tags question: http://stackoverflow.com/q/49867199
type: Tag
tag name: physics
tags question: http://stackoverflow.com/q/49882030

http://stackoverflow.com/q/49792746
type: Question
score: 0
has comment: http://stackoverflow.com/comment/86600448
has comment: http://stackoverflow.com/comment/86600326
answer count: 0
type: UnansweredQuestion
tagged with: function
upvote count: 1
has comment: http://stackoverflow.com/comment/86600596
has comment: http://stackoverflow.com/comment/86599975
downvote count: 1
has body: I'm currently working on an small banking application in python. I created functions that opens a txt file. I tested the function on its own so I know it works, however when implemented alongside the menu it seems not to work. def parse_in(): with open('bank.txt', 'r') as details: lines = details.read().splitlines() return lines Later on I have a simple menu with few options but here I will only show the one I'm having issues with. def menu(): print("Please selected one of the options" + "\n\t1: Open account" while True: try: selection = int(input("Please enter your choice: ")) if selection == 1: open_account(details) else: break except: print("Please enter number 1-6") if 1 is selected an open account should be ran def open_account(details): print("Welcome to your new account") new_account_number = randint(000000, 999999) while True: try: new_account_balance = float(input("Enter your sum of money: ")) if new_account_balance &lt; 0: print("please enter positive value") else: break except: print("Please Enter Number Only") while True: new_account_name = input("Enter your name: ") if " " in new_account_name: print("Please enter your full name") else: break details.append(new_account_number) details.append(new_account_balance) details.append(new_account_name) After the information was imputed the idea is that they're suppose to save to the same file using a function. def parse_out(details): with open('bank.txt', 'w') as file: for i in details: file.write(str(i) + '\n') and everything is ran in main function def main(): details = parse_in() welcome() menu() parse_out(details) When I press 1 the open account function seems not be running instead, the menu loops back to choosing one of the options. I'n not really sure why it does that as it seems it should run and take information from user fallowed by saving the info to file.
favorite count: 0
has title: Python: Functions is not running when called from a menu
tagged with: python
tagged with: menu
has comment: http://stackoverflow.com/comment/86600397

http://stackoverflow.com/a/49852268
upvote count: 1
has comment: http://stackoverflow.com/comment/89370765
answers question: http://stackoverflow.com/q/49834062
has body: Replace your nested if / else construct with a simple function. Below is an example: import pandas as pd, numpy as np df = pd.DataFrame({'A': ['enfpD', 'iNfp', 'sadintj', 'abc']}) choices = {'enfp', 'entj' , 'entp', 'esfj' , 'esfp', 'estj', 'estp', 'infj', 'infp', 'intj', 'intp', 'isfj', 'isfp', 'istj'} def changer(x): match = next((c for c in choices if c in x), None) if match: return match.title() else: return 'Istp' df['A'] = df['A'].apply(changer) print(df) # A # 0 Enfp # 1 Istp # 2 Intj # 3 Istp
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49834062
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86699091
comment on: http://stackoverflow.com/q/49842027
type: Comment
has text: Instead of a list of lists, I'd suggest using a list of [`namedtuple`](https://docs.python.org/3/library/collections.html) (provided that those entries can be immutable)
score: 1
type: QuestionComment

http://stackoverflow.com/q/49909792
accepted answer: http://stackoverflow.com/a/49909839
upvote count: 2
has answer: http://stackoverflow.com/a/49909839
tagged with: python
has body: Take this example object: class myObj: def __init__(self): self.a = 1 self.b = 2 self.c = 3 a = myObj() I can use vars(a) and I'll get {'a': 1, 'b': 2, 'c': 3} or dir(a) to get a list of the attributes plus all the functions in a. I can see everything that is stored within a. However, with a list its a different story. var([]) throws an error and dir([1, 2, 3]) only lists the functions that are implemented in list. Where does __getitem__ get the items in the list from?
score: 2
type: AnsweredQuestion
has title: Where are the elements in a python list stored?
tagged with: list
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86835597

http://stackoverflow.com/q/49767084
score: 7
has comment: http://stackoverflow.com/comment/86557266
has answer: http://stackoverflow.com/a/53965991
favorite count: 0
has answer: http://stackoverflow.com/a/49840566
has title: TypeError: reduction operation 'argmax' not allowed for this dtype
upvote count: 8
type: Question
linked to: http://stackoverflow.com/q/15891038
answer count: 2
tagged with: machine-learning
tagged with: python
type: UnansweredQuestion
downvote count: 1
has body: I don't actually know what is wrong with my code. Could anyone help? from sklearn.linear_model import LogisticRegression from sklearn.cross_validation import KFold, cross_val_score from sklearn.metrics import confusion_matrix,precision_recall_curve,auc,roc_auc_score,roc_curve,recall_score,classification_report def printing_Kfold_scores(x_train_data,y_train_data): fold = KFold(len(y_train_data),5,shuffle=False) # Different C parameters c_param_range = [0.01,0.1,1,10,100] results_table = pd.DataFrame(index = range(len(c_param_range),2), columns = ['C_parameter','Mean recall score']) results_table['C_parameter'] = c_param_range # the k-fold will give 2 lists: train_indices = indices[0], test_indices = indices[1] j = 0 for c_param in c_param_range: print('-------------------------------------------') print('C parameter: ', c_param) print('-------------------------------------------') print('') recall_accs = [] for iteration, indices in enumerate(fold,start=1): # Call the logistic regression model with a certain C parameter lr = LogisticRegression(C = c_param, penalty = 'l1') # Use the training data to fit the model. In this case, we use the portion of the fold to train the model # with indices[0]. We then predict on the portion assigned as the 'test cross validation' with indices[1] lr.fit(x_train_data.iloc[indices[0],:],y_train_data.iloc[indices[0],:].values.ravel()) # Predict values using the test indices in the training data y_pred_undersample = lr.predict(x_train_data.iloc[indices[1],:].values) # Calculate the recall score and append it to a list for recall scores representing the current c_parameter recall_acc = recall_score(y_train_data.iloc[indices[1],:].values,y_pred_undersample) recall_accs.append(recall_acc) print('Iteration ', iteration,': recall score = ', recall_acc) # The mean value of those recall scores is the metric we want to save and get hold of. results_table.ix[j,'Mean recall score'] = np.mean(recall_accs) j += 1 print('') print('Mean recall score '…

http://stackoverflow.com/comment/86585189
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49784513
type: QuestionComment
has text: Did you look at this? https://stackoverflow.com/questions/33229360/gensim-typeerror-doc2bow-expects-an-array-of-unicode-tokens-on-input-not-a-si#33230682

http://stackoverflow.com/q/49911982
type: UnansweredQuestion
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I've been having this problem for a couple weeks now and it's been causing me lots of stress in some of my classes. I have been using Ubuntu to use Python 3 to open a local server. I've tried using "sudo" and I still get access denied. I've asked professors for help but they have no idea whats wrong either. I had it work once and then after that it never worked again. Here is the error I keep getting. ____@DESKTOP-55VJC61:/mnt/c/Users/Julia/Desktop/p5/empty-example$ python3 -m http.server Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/usr/lib/python3.5/http/server.py", line 1221, in &lt;module&gt; test(HandlerClass=handler_class, port=args.port, bind=args.bind) File "/usr/lib/python3.5/http/server.py", line 1194, in test httpd = ServerClass(server_address, HandlerClass) File "/usr/lib/python3.5/socketserver.py", line 440, in __init__ self.server_bind() File "/usr/lib/python3.5/http/server.py", line 138, in server_bind socketserver.TCPServer.server_bind(self) File "/usr/lib/python3.5/socketserver.py", line 454, in server_bind self.socket.bind(self.server_address) PermissionError: [Errno 13] Permission denied If anyone has a solution to this problem please help!
score: 1
tagged with: windows
has title: Ubuntu wont allow me to open a server using python3
tagged with: python
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/86846365
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/86854333
upvote count: 1

http://stackoverflow.com/comment/87072658
type: AnswerComment
has text: Yeah unfortunately the actual document is some 10000 lines generated by an external source. I'm currently trying to figure out a way to back out the group structure by exploiting the value column.
comment on: http://stackoverflow.com/a/50027863
type: Comment
score: 0

http://stackoverflow.com/q/49887395
has comment: http://stackoverflow.com/comment/86790949
tagged with: virtualenv
tagged with: python-requests
downvote count: 1
has comment: http://stackoverflow.com/comment/86792812
score: 3
has answer: http://stackoverflow.com/a/49887463
tagged with: python-pex
tagged with: python
favorite count: 0
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/86790854
type: UnansweredQuestion
has body: pip install does not work when trying to install virtualenv, requests or pex on CentOS6. I am on python2.6 and pip 9.0.1. Can anyone tell me why is this happening? (pex_build)[root@pex pex_build]# pip install virtualenv Output: Traceback (most recent call last): File "/opt/pex_build/bin/pip", line 7, in &lt;module&gt; from pip._internal import main File "/opt/pex_build/lib/python2.6/site-packages/pip/_internal/__init__.py", line 42, in &lt;module&gt; from pip._internal import cmdoptions File "/opt/pex_build/lib/python2.6/site-packages/pip/_internal/cmdoptions.py", line 16, in &lt;module&gt; from pip._internal.index import ( File "/opt/pex_build/lib/python2.6/site-packages/pip/_internal/index.py", line 526 {str(c.version) for c in all_candidates}, ^ SyntaxError: invalid syntax Command: (pex_build) [root@pex pex_build]# pip install requests pex Output: Traceback (most recent call last): File "/opt/pex_build/bin/pip", line 7, in &lt;module&gt; from pip._internal import main File "/opt/pex_build/lib/python2.6/site-packages/pip/_internal/__init__.py", line 42, in &lt;module&gt; from pip._internal import cmdoptions File "/opt/pex_build/lib/python2.6/site-packages/pip/_internal/cmdoptions.py", line 16, in &lt;module&gt; from pip._internal.index import ( File "/opt/pex_build/lib/python2.6/site-packages/pip/_internal/index.py", line 526 {str(c.version) for c in all_candidates}, ^ SyntaxError: invalid syntax Also curl gives the similar error, when trying to get get-pip.py Command: (pex_build) [root@pex pex_build]# curl https://bootstrap.pypa.io/get-pip.py | python % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 1602k 100 1602k 0 0 7373k 0 --:--:-- --:--:-- --:--:-- 14.6M Traceback (most recent call last): File "&lt;stdin&gt;", line 20636, in &lt;module&gt; File "&lt;stdin&gt;", line 197, in main File "&lt;stdin&gt;", line 82, in bootstrap File "/tmp/tmp5zrn_f/pip.zip/pip/_internal/__init__.py", line 42, in &lt;module&gt;…
has title: pip install errors out: SyntaxError: invalid syntax
has answer: http://stackoverflow.com/a/49888058
tagged with: pip

http://stackoverflow.com/comment/86634853
has text: I tried above your code, but it did not work unfortunately with following error : ERROR scheduler.LiveListenerBus: Listener EventLoggingListener threw an exception java.lang.reflect.InvocationTargetException
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49809727
type: Comment

http://stackoverflow.com/q/49902236
answer count: 0
has comment: http://stackoverflow.com/comment/86825283
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86824451
has comment: http://stackoverflow.com/comment/86822473
tagged with: plot
has comment: http://stackoverflow.com/comment/86823575
score: 0
tagged with: pandas
has title: How can I combine these 2 Pandas dataframe linegraphs into a single matplotlib graph with 2 lines?
tagged with: matplotlib
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/86819943
has comment: http://stackoverflow.com/comment/86823973
has body: I have a single dataframe called sentimentJoin that contains all the values I want to plot in a line graph. I have a single constant y-axis (time), which is a string containing when the data was pulled, and 2 x-axis (sentiment and close), but I cannot get them to plot against each other. I am able to plot them separately, but when I try to combine them in the code below, I am getting the error, "ValueError: could not convert string to float: '09:37'. I'm not sure why I can plot the 'time' string in the separated line graphs, but not the combined graph. Any tips on what I could modify in the code? fig=plt.figure() ax=fig.add_subplot(111, label="1") ax2=fig.add_subplot(111, label="2", frame_on=False) ax.plot(sentimentJoin['time'], sentimentJoin['sentiment'], color="C0") ax.set_xlabel("x label 1", color="C0") ax.set_ylabel("y label 1", color="C0") ax.tick_params(axis='x', colors="C0") ax.tick_params(axis='y', colors="C0") ax2.plot(sentimentJoin['time'], sentimentJoin['close'], color="C0") ax2.xaxis.tick_top() ax2.yaxis.tick_right() ax2.set_xlabel('x label 2', color="C1") ax2.set_ylabel('y label 2', color="C1") ax2.xaxis.set_label_position('top') ax2.yaxis.set_label_position('right') ax2.tick_params(axis='x', colors="C1") ax2.tick_params(axis='y', colors="C1") Data Shown Here: close/ open/ unixTime/ time/ sentiment/ 8109.1/ 8114.92/ 1524058380/ 9:33/ -0.284848/
type: Question

ssl
tags question: http://stackoverflow.com/q/49900521
tags question: http://stackoverflow.com/q/49889788
tags question: http://stackoverflow.com/q/49913002
tags question: http://stackoverflow.com/q/49882684
tags question: http://stackoverflow.com/q/49784924
type: Tag
tags question: http://stackoverflow.com/q/49769927
tags question: http://stackoverflow.com/q/49861597
tags question: http://stackoverflow.com/q/49803221
tags question: http://stackoverflow.com/q/49766627
tags question: http://stackoverflow.com/q/49852738
tags question: http://stackoverflow.com/q/49774366
tags question: http://stackoverflow.com/q/49788677
tags question: http://stackoverflow.com/q/49787069
tags question: http://stackoverflow.com/q/49891625
tags question: http://stackoverflow.com/q/49825793
tags question: http://stackoverflow.com/q/49765098
tag name: ssl
tags question: http://stackoverflow.com/q/49844560

http://stackoverflow.com/comment/86536809
type: Comment
type: AnswerComment
has text: @MSanders https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html
comment on: http://stackoverflow.com/a/49758277
score: 0

http://stackoverflow.com/comment/86791545
score: 0
comment on: http://stackoverflow.com/q/49854669
has text: @Dave uninstall eventlet from your virtual environment if you don't want to use it.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86561554
type: Comment
has text: Yeah, that's the problem, they aren't in a list or anything.. that's why I mentioned the API details in my main post, maybe those would help make sense of the response. I also believe there are no spaces between {information} {information} , it's just one continuous string.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49772948

http://stackoverflow.com/q/49798571
score: 0
has title: How can i correctly decorate PyQt callback function?
has answer: http://stackoverflow.com/a/54804402
answer count: 1
has body: In python PyQt signal's callback functions also have "hidden" parameter "state". This parameter is making harder function decoration by user-defined decorators. My example of code and a decorator. In my solution i have to admit TypeErrors, caused by incorrect parameters count, for every callback without lambda, otherwice i can't decorate. Is there a better way, in which i can exclude admitting TypeError ? Can i ignore "state" parametr somehow else in my decorator? Code example : decorator and program example. from PyQt4 import QtCore, QtGui def decor(func_fuc): def new_func(*args, **kwargs): #do something try: func_fuc(*args, **kwargs) except TypeError as TypE: if all(i in TypE.args[0] for i in ['takes', 'positional', 'argument' ,'but', 'given']): args = tuple([args[ar] for ar in range(len(args)-1)]) func_fuc(*args, **kwargs) else: raise TypE #etc return new_func class MainWind(QtGui.QMainWindow): @decor def __init__(self,parent=None,geometry = QtCore.QRect(100,100,800,800)): super(MainWind, self).__init__(parent,geometry=geometry) self.pushik = QtGui.QPushButton( self, clicked = self.vasa ,geometry = QtCore.QRect(100,100,50,50), text = 'vasa' ) self.petjaBtn = QtGui.QPushButton( self, clicked = lambda state : self.petja() ,geometry = QtCore.QRect(100,200,50,50), text = 'petja' ) self.someBtn = QtGui.QPushButton( self, clicked = self.someBtnClick ,geometry = QtCore.QRect(100,300,50,50), text = 'someBtn' ) self.show() #@decor def vasa(*args): print('vasa call') print(args) #(&lt;__main__.MainWind object at 0x018FF940&gt;, False) #@decor def petja(*args): print('petja call') print(args) #(&lt;__main__.MainWind object at 0x018FF940&gt;,) def someBtnClick(self): # usual usage print('someBtnClick call') # signature : accept only "self", but works fine on button click(with 2 params, self and state) # if i write empty decorator, that just returns original call, i will get typeError (reason - extra argument) #how to decorate without admitting "argument" TypeError? app=QtGui…
type: Question
tagged with: pyqt4
type: UnansweredQuestion
tagged with: python
tagged with: python-decorators

http://stackoverflow.com/comment/86632991
type: QuestionComment
comment on: http://stackoverflow.com/q/49808911
score: 0
has text: Meanwhile, why is this tagged both python-3.x and python-2.7? Do you need code that runs in both versions for some reason?
type: Comment

http://stackoverflow.com/q/49887159
tagged with: centos
has title: ajax request to a linux server sometimes returns me the answer, sometimes returns me error 500
tagged with: gunicorn
has comment: http://stackoverflow.com/comment/86792241
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/86790665
has comment: http://stackoverflow.com/comment/86790798
has body: I have a python application with gunicorn and flask on a centos machine. I access the application from another machine in the following way: http://host:port/nameOfFunction?path=https://site/directory1/directory2/directory3/file.pdf The path is correct, because it works. When i enter the same path multiple times, sometimes it works, others, don't. I am using gunicorn (with the follow command): gunicorn -b 0.0.0.0:8080 start:app to start my application. When the answer returns, the screen showing gunicorn prints some piece of code that i put to see some informations. When it returns me error 500, the code from start isn't printed at all. I dont have a clue what is the cause of this. the beginning of the code is: @app.route("/call", methods=['POST', 'GET']) def call(): print '\n============================BEGINS======================\n' path =request.args.get('path') newPath = path.rsplit('/',1)[1] directoriesRoot(root) directoriesRoot(pdfs) parameters = ["curl", path.replace(' ','%20'), '--output',pdfs+newPath] p = subprocess.Popen(parameters, stdout=subprocess.PIPE) output, err = p.communicate() if err: return 'ERROR' person= functionSecundaryWithNoImportance([newPath]) return jsonify(person) Someone has some clue or already pass for a similar problem?
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49899375
has comment: http://stackoverflow.com/comment/86790829
has answer: http://stackoverflow.com/a/49899375
answer count: 1
has comment: http://stackoverflow.com/comment/86813988
has comment: http://stackoverflow.com/comment/86790589
has comment: http://stackoverflow.com/comment/86791207
type: Question

http://stackoverflow.com/comment/86826727
comment on: http://stackoverflow.com/q/49905415
score: 1
type: Comment
type: QuestionComment
has text: You can't set the environment variable for a parent process (i.e., the shell that invoked your Python process). See https://stackoverflow.com/a/38982936

http://stackoverflow.com/comment/86851417
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49915894
type: Comment
has text: @ZdaR fair enough. the expected output is a set of pixelpoints that lies on the border of the contour. by the way, i tried to find extreme points of the contours, the statements provided for extreme points also throws an error https://docs.opencv.org/3.4.1/d1/d32/tutorial_py_contour_properties.html

http://stackoverflow.com/comment/86646801
comment on: http://stackoverflow.com/q/49816144
has text: @pilu center and label come from the opencv method, kmeans. I've added the line where they are initialized to that it's clearer
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86805019
type: Comment
score: 0
type: QuestionComment
has text: {"created_at":"Wed Apr 18 08:10:56 +0000 2018","id":986517420478087168,"id_str":"986517420478087168","text":"\u0e23\u0e35+\u0e40\u0e21\u0e19\u0e0a\u0e31\u0e48\u0e19\u0e1e\u0e34\u0e21\u0e1e\u0e4c\u0e40\u0e25\u0e02\u0e2d\u0e30\u0e44\u0e23\u0e01\u0e47\u0e44\u0e14\u0e49\u0e2b\u0e49\u0e32\u0e21\u0e0 This is what i get in my json
comment on: http://stackoverflow.com/q/49894665

http://stackoverflow.com/q/49800714
answer count: 0
has comment: http://stackoverflow.com/comment/86616475
type: UnansweredQuestion
tagged with: scrapy
has body: I would like to retrieve the contents of a dynamic HTML table after each timer, but the response is always the same after each scrapping; But I do not know how to do it then I'm new with scrapy; here is my code content # redirection sur la page def parse_x(self,response): for q in response.xpath('//*[@id="sessions"]/tbody/tr'): # recuperation des informations localisé dans la tableau user_session sur la page instance_name = q.xpath('td[2]//text()').extract_first() username = q.xpath('td[3]//text()').extract_first() client_address = q.xpath('td[4]//text()').extract_first() environnement = q.xpath('td[5]//text()').extract_first() Timer(5, self.parse_x, [response]).start()
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/86620846
has comment: http://stackoverflow.com/comment/86619399
score: 0
has title: how to reload response content in scrapy after in each timer?

http://stackoverflow.com/comment/86717235
comment on: http://stackoverflow.com/a/49849385
has text: Thank you for the detailed answer. It is very nicely explained. May I also ask if there were n number of dice, what would be the situation? Do you use a float conversion or just assume that there are a number of dice like 10 ** 6 or 10 ** 7?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49825636
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86667391
has body: str.replace returns the updated string. You should wrap that in a StringIO and then pass it to pandas. Your code appears to be python 2, but python 3 is much better at unicode issues. Here is a python 3 solution that works on the example data set: import pandas as pd from io import StringIO dataset = 'datafile.csv' sio = StringIO(open(dataset).read().replace('”','"')) df = pd.read_csv(sio, sep=';', decimal='.', skiprows = 1, header= None, names=['a', 'b', 'c', 'd', 'e', 'f']) print(df) Here is a solution that works for python 2.7. I am assuming that the CSV file is UTF-8 encoded and that you are using a UTF-8 enabled editor to write the python script. That's normal for unixy systems but may be problematic on windows. # coding=utf-8 import pandas as pd from StringIO import StringIO import codecs dataset = 'datafile.csv' sio = StringIO(codecs.open(dataset, encoding="utf-8").read().replace(u'”',u'"')) df = pd.read_csv(sio, sep=';', decimal='.', skiprows = 1, header= None, names=['a', 'b', 'c', 'd', 'e', 'f']) print(df)
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49825205
type: Answer
has comment: http://stackoverflow.com/comment/86667614
answers question: http://stackoverflow.com/q/49825205
score: 2

http://stackoverflow.com/a/49875490
has body: Your function diff_validation() is returning a string not a variable. So when you are printing you should get the string printed not the list. To get the list variable from the matching variable name you can use dictionary like this: # Global variables. fillers = ["__1__", "__2__", "__3__", "__4__"] difficulties = ["easy", "medium", "hard"] easy_text = "The Three Little Pigs is a fable about three __1__ who build three __2__ of different materials. A big bad __3__ blows down the first two pigs' houses, made of straw and sticks respectively, but is unable to destroy the third pig's house, made of __4__." easy_answers = ["pigs", "houses", "wolf", "bricks"] lists = {"easy_text":easy_text, "easy_answers":easy_answers} Then to retrieve: fl_text, fl_answers = diff_validation() print lists[f1_answers]
answers question: http://stackoverflow.com/q/49874965
has comment: http://stackoverflow.com/comment/87003841
type: Answer
has comment: http://stackoverflow.com/comment/86983371
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49874965
has comment: http://stackoverflow.com/comment/86797340
has comment: http://stackoverflow.com/comment/86771936

http://stackoverflow.com/comment/86770857
score: 1
type: Comment
has text: I'd advise you also look up HDF5 if you have larger data. This has native compression and, on top, is accessible across languages.
type: AnswerComment
comment on: http://stackoverflow.com/a/49877674

http://stackoverflow.com/comment/86792097
score: 0
comment on: http://stackoverflow.com/q/49887524
has text: So in order to create a six item list this creates an empty list, then a brand new two item list, then a brand new four item list, then finally a six item list. All previous lists are thrown away. At each step all the references are copied. The performance is horrible. You might not notice it with list this small, but indescriminate use of algorithms like this kill performance even if you're using the fastest of languages.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86755122
type: Comment
type: QuestionComment
score: 0
has text: I am sorry I am not aware of any inbuilt transformer which can handle the json to 2-d array conversion if thats what you wanted.
comment on: http://stackoverflow.com/q/49860969

http://stackoverflow.com/comment/86650118
comment on: http://stackoverflow.com/q/49817778
score: 1
type: Comment
has text: @pilu gives you the right answer, don't try to do something already done by powerful libs :)
type: QuestionComment

http://stackoverflow.com/comment/86606464
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49787916
has text: Are there only 2-tuples? Or can this have an arbitrary depth?
type: QuestionComment

http://stackoverflow.com/a/49785532
has body: [Update: cx_Oracle was renamed to python-oracledb. See the release announcement - use this version instead of cx_Oracle. Also the old makedsn() function was obsoleted by the ConnectParams object.] Use the TNS alias in the connection string: conn_str = 'chris/mypassword@db_alias' # use the entry from the tnsnames.ora file self.con = cx_Oracle.connect(conn_str) or use the alias with the other form of connect() like this: self.con = cx_Oracle.connect(user='chris', password='mypassword', dsn='db_alias') If you know the actual connect descriptor then you could do: cs = """(DESCRIPTION= (FAILOVER=on) (ADDRESS_LIST= (ADDRESS=(PROTOCOL=tcp)(HOST=sales1-svr)(PORT=1521)) (ADDRESS=(PROTOCOL=tcp)(HOST=sales2-svr)(PORT=1521))) (CONNECT_DATA=(SERVICE_NAME=sales.example.com)))""" self.con = cx_Oracle.connect(user="chris", password='mypassword', dsn=cs) See Connection Strings
downvote count: 0
has comment: http://stackoverflow.com/comment/86698116
has comment: http://stackoverflow.com/comment/86591326
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/86659060
type: Answer
has comment: http://stackoverflow.com/comment/123149972
has comment: http://stackoverflow.com/comment/86612387
answers question: http://stackoverflow.com/q/49780694
has comment: http://stackoverflow.com/comment/123150172

http://stackoverflow.com/q/49887968
has body: Something went wrong with the homebrew-installed python 2.7.13 installation, so I cleaned out everything installed with homebrew and started from scratch. I still get the error below, referencing a file from PIL (Pillow has been installed with pip). How can I fix this library which seems to be corrupted, yet was just reinstalled? $ python2 src/ks.py --- module "start" Traceback (most recent call last): File "src/ks.py", line 29, in &lt;module&gt; from PIL import ImageTk, Image File "/usr/local/lib/python2.7/site-packages/PIL/ImageTk.py", line 42, in &lt;module&gt; from . import Image File "/usr/local/lib/python2.7/site-packages/PIL/Image.py", line 60, in &lt;module&gt; from . import _imaging as core ImportError: dlopen(/usr/local/lib/python2.7/site-packages/PIL/_imaging.so, 2): Symbol not found: _clock_gettime Referenced from: /usr/local/lib/python2.7/site-packages/PIL/.dylibs/liblzma.5.dylib (which was built for Mac OS X 10.12) Expected in: /usr/lib/libSystem.B.dylib in /usr/local/lib/python2.7/site-packages/PIL/.dylibs/liblzma.5.dylib Here's everything I've done getting to this point: - check brew list is empty - install python@2 - list the pip-installed items - update pip - uninstall Pillow (just to make sure) - list the pip-installed items (make sure uninstall succeeded) - reinstall Pillow - list the pip-installed items (make sure reinstall succeeded) - run my script - I also checked python2 --version and pip --version and both confirm the homebrew install is separate from the system-installed python. +++++++++++++++++++++++++++++++++++++++++ $ brew list gdbm python readline xz openssl python@2 sqlite [user@host] $ brew install python@2 ==&gt; Downloading https://homebrew.bintray.com/bottles/python@2-2.7.14_3.el_capitan.bo Already downloaded: /Users/benfound/Library/Caches/Homebrew/python@2-2.7.14_3.el_capitan.bottle.1.tar.gz ==&gt; Pouring python@2-2.7.14_3.el_capitan.bottle.1.tar.gz ==&gt; /usr/local/Cellar/python@2/2.7.14_3/bin/python -s setup.py --no-user-cf…
tagged with: python
score: -1
has title: What does `Symbol not found: _clock_gettime` mean when calling a python 2.7 script?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49991726
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/50706154
tagged with: pip
possible better answer: http://stackoverflow.com/a/50706154
has comment: http://stackoverflow.com/comment/89225822
tagged with: macos
linked to: http://stackoverflow.com/q/49969800
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49991726

http://stackoverflow.com/a/50164666
answers question: http://stackoverflow.com/q/49890866
type: Answer
accepted answer of: http://stackoverflow.com/q/49890866
has body: That is a dramatic difference so perhaps there's a bug in the code or something unexpected in the data but reproducing Keras results from R in Python is more difficult than it may seem since setting the seed on the R side is insufficient. Instead of set.seed you should use use_session_with_seed, which comes with the R libraries for tensorflow and keras. Note that for full reproducibility you need to use_session_with_seed(..., disable_gpu=TRUE, disable_parallel_cpu=TRUE). See also stack and tf docs. Also, here is an example using the github version of kerasformula and a public dataset. Also, watch out for functions like layer_dropout that accept seed as a parameter.
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3

http://stackoverflow.com/a/49777381
type: Answer
answers question: http://stackoverflow.com/q/49777262
upvote count: 2
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49777262
has comment: http://stackoverflow.com/comment/86570866
type: AcceptedAnswer
has body: Use starmap and zip_longest from itertools with None as the fillvalue in zip_longest to fill the missing value position: In [34]: from itertools import zip_longest, starmap In [35]: list(starmap(eq, zip_longest(a, b, fillvalue=None))) Out[35]: [True, True, False]
has comment: http://stackoverflow.com/comment/86571549

http://stackoverflow.com/q/49805975
tagged with: python
has body: When using Matplotlib's polar plot, the default zero position for the theta axis is or the right with the angle increasing counter-clockwise, as shown in this example. How do you specify the zero position and reverse the direction of increasing theta? As of writing this, the documentation is relatively limited.
type: AnsweredQuestion
has title: How do you reverse the axis and set the zero position for a polar plot in Matplotlib?
downvote count: 0
answer count: 1
favorite count: 0
tagged with: polar-coordinates
score: 8
upvote count: 8
accepted answer: http://stackoverflow.com/a/49805976
type: Question
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49805976

http://stackoverflow.com/a/49766033
score: 2
has comment: http://stackoverflow.com/comment/86547659
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49765985
has comment: http://stackoverflow.com/comment/86547476
has comment: http://stackoverflow.com/comment/86547665
has body: Yeah ... assuming every value has a / like your example, this is superior: &gt;&gt;&gt; from ast import literal_eval &gt;&gt;&gt; &gt;&gt;&gt; val = '["10249/54","10249/147","10249/187","10249/252","10249/336"]' &gt;&gt;&gt; [int(i.split('/')[1]) for i in literal_eval(val)] [54, 147, 187, 252, 336] *edited to insert a forgotten bracket
type: Answer

http://stackoverflow.com/q/49840657
favorite count: 0
has comment: http://stackoverflow.com/comment/86696114
has comment: http://stackoverflow.com/comment/86699855
type: Question
tagged with: lmfit
has comment: http://stackoverflow.com/comment/86696632
has comment: http://stackoverflow.com/comment/86696241
tagged with: curve-fitting
tagged with: python
has body: I am fairly new to python and I am trying to do some curve fitting using lmfit. The code works pretty well but I would like to force the fit through the origin (0,0). I've seen here in stakoverlow that using "curve_fit" you can add and attribute "sigma" that does the trick but this does not work in "minimize". Do you have any workaround to this??? So far, this is my code: ############################################################################## ###################### IMPORT MODULES ######################################## ############################################################################## import numpy as np import matplotlib.pyplot as plt from lmfit import minimize, Parameters from lmfit import report_fit ############################################################################## ##################### DATA ################################## ############################################################################## x=np.array([0,1, 4, 6, 8, 9, 11, 13, 15, 18, 20, 27]) data=np.array([0, 67, 208, 339, 460, 539, 599, 635, 659, 685, 701, 731]) ############################################################################## ######################## GOMPERTZ FUNCTION DEFINITION######################### ############################################################################## def BMP_Gompertz(params, x, data): BMPmax=params['BMPmax'].value Rmax=params['Rmax'].value Lambda=params['Lambda'].value model=BMPmax*np.exp(-np.exp(Rmax*np.exp(1)/BMPmax*(Lambda-x)+1)) global model_data model_data=[BMPmax,Rmax,Lambda] return data-model params=Parameters() params.add('BMPmax', value=300., min=0.) params.add('Rmax', value=25., min=0.) params.add('Lambda',value=0.5, min=0.) model_data=[] ############################################################################## ###################### GOMPERTZ CURVE FITTING &amp; REPORT ####################### ############################################################################## result=minimize(BMP_Gompertz, params, …
has comment: http://stackoverflow.com/comment/86696265
accepted answer: http://stackoverflow.com/a/49843706
has answer: http://stackoverflow.com/a/49843706
type: AnsweredQuestion
downvote count: 0
score: 1
has title: lmfit minimize weighting initial data
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/86800069
score: 0
has text: TextBlob is an API for NLP.
type: Comment
comment on: http://stackoverflow.com/q/49891686
type: QuestionComment

http://stackoverflow.com/q/49904694
has body: I have a dataframe like this: name_by_day name a b ------------------------------- 20170901 2017090101 118 241 20170901 2017090102 117 241 20170901 2017090103 88 241 20170901 2017090104 99 241 20170901 2017090105 87 241 And I just want the following: name_by_day a_x b_x a_y b_y a_z b_z ... --------------------------------------------------- 20170901 118 241 117 241 88 241 99 241 87 241 Any ideas?
has answer: http://stackoverflow.com/a/49904923
downvote count: 0
has title: Pandas - how to transpose columns correctly
favorite count: 0
type: Question
score: 3
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49906768
answer count: 2
tagged with: pandas
upvote count: 3

http://stackoverflow.com/a/49770091
accepted answer of: http://stackoverflow.com/q/49769297
answers question: http://stackoverflow.com/q/49769297
score: 1
type: Answer
has body: To use re.search in this way there need to be a match at each row, otherwise None is returned. Since None does not have a group attribute you will see the current error. One way to avoid the error would be to change the pattern slightly and use an empty alternative using |$: dff['User_Mentions'] = dff['content'].apply(lambda x: re.search("@([a-zA-Z0-9]{1,15})|$", x).group(1)) This will give a None value in the dataframe when there is no match. Another alternative would be to use Series.str.extract as mentioned in a comment: dff['User_Mentions2'] = dff['content'].str.extract('@([a-zA-Z0-9]{1,15})', expand=False) This would instead result in a NaN value in the rows with no match.
downvote count: 0
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/86592308
comment on: http://stackoverflow.com/q/49788555
has text: Also note, you cannot return multiple values, you return a single value, a `tuple`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49836895
tagged with: pandas
has title: pandas: Comparing dataframe rows and storing values
tagged with: dataframe
type: Question
has body: I have a dataframe with one row. The first 5 columns are ID columns and the rest is the data: 0 1 865694 C T 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 And another dataframe with many rows (of which here are a subset). The first three columns are ID columns and the rest are the data. 0 G C 3 3 3 3 3 3 3 3 ... 3 3 3 1 3 3 3 3 3 3 1 T G 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 2 G A 3 2 3 3 3 3 3 3 ... 3 3 2 1 1 1 2 0 3 3 3 A G 3 3 3 3 3 3 3 3 ... 3 3 3 1 3 3 3 3 3 3 4 C T 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 5 G A 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 6 A G 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 7 C T 3 3 3 3 3 3 3 3 ... 3 3 3 1 3 3 3 3 3 3 8 G A 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 9 C T 3 2 3 3 3 3 3 3 ... 3 3 2 0 1 1 2 0 3 3 10 G A 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 In both dataframes the data columns can take values of 0, 1, 2 or 3. I want to compare the first dataframe row with each row from the second data frame, counting occurrences of each combination. E.g. the number of 0,0 which would be the number of columns with 0 in the row of the first dataframe, and 0 in the row in question of the second dataframe. If this could be functionised it can be applied to each row. What I would like returned is counts of the number of 00, 01, 02, 03, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33. This could be in the form of a list or a dataframe, the bigger issue is comparing the rows as I have ~2500 data columns.
answer count: 0
has comment: http://stackoverflow.com/comment/86689361
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86689276
has comment: http://stackoverflow.com/comment/86689042
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/86689265

http://stackoverflow.com/comment/86808621
has text: Regarding question (1), can you please clarify it a bit more. Regarding (2), what are the expected number of channels in the new layers that you want to add? I mean, currently in the encoder the number of channels are (8, 16, 32) respectively. If you want to add something on top of it, is it going to have 4 channels? If yes, continuing likewise, is there some threshold (like 4) for all the newly added layers, or you keep on decreasing by two times, until you reach some minimum number of channels (say, 2)? (On similar note, for the decoder part also)
comment on: http://stackoverflow.com/q/49890135
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49811492
linked to: http://stackoverflow.com/q/27999934
downvote count: 0
score: 4
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/86641249
accepted answer: http://stackoverflow.com/a/49813412
type: AnsweredQuestion
tagged with: many-to-many
answer count: 1
has title: Flask - SQLAlchemy many to many causes sqlalchemy.orm.exc.FlushError
tagged with: python
has comment: http://stackoverflow.com/comment/86637656
tagged with: sqlalchemy
favorite count: 0
linked to: http://stackoverflow.com/q/3174979
type: Question
upvote count: 4
has body: class Show(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(200), unique=True, nullable=False) studio = db.relationship("ShowStudio", backref="show", cascade="delete") class Studio(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), unique=True, nullable=False) show = db.relationship("ShowStudio", backref="studio", cascade="delete") class ShowStudio(db.Model): show_id = db.Column(db.Integer, db.ForeignKey(Show.id, ondelete="CASCADE"), primary_key=True) studio_id = db.Column(db.Integer, db.ForeignKey(Studio.id, ondelete="CASCADE"), primary_key=True) studio = Studio(name="asd") db.session.add(studio) s = Show(title="a", studio=[studio]) db.session.flush() db.session.add(s) db.session.commit() When I run it, it throws sqlalchemy.orm.exc.FlushError: Attempting to flush an item of type as a member of collection "Studio.show". Expected an object of type or a polymorphic subclass of this type. I follow the answer from here. I do not understand what cause the error. Any helps are welcome.
has answer: http://stackoverflow.com/a/49813412

http://stackoverflow.com/q/49763779
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/49763834
score: 1
has body: AttributeError: module 're' has no attribute '_pattern_type' I am getting the above error while trying to replace categorical data in a dataset with numerical values using Pandas replace module. My code is as follows. housng_dataframe is a dataframe created on a housing dataset using Pandas. ordinal_mapping_dict = {"LotShape": {"Reg": 3,"IR1": 2,"IR2": 1,"IR3": 0}, "ExterQual":{"Ex": 4,"Gd": 3,"TA": 2,"Fa": 1,"Po": 0}, "HeatingQC":{"Ex": 4,"Gd": 3,"TA": 2,"Fa": 1,"Po": 0}, "KitchenQual":{"Ex": 4,"Gd": 3,"TA": 2,"Fa": 1,"Po": 0}, "Functional":{"Typ":7,"Min1":6,"Min2":5,"Mod":4,"Maj1":3,"Maj2":2,"Sev":1,"Sal":0}, "PavedDrive":{"Y": 2,"P": 1,"N": 0 }} housing_dataframe = housing_dataframe.replace(ordinal_mapping_dict) Output: AttributeError Traceback (most recent call last) &lt;ipython-input-106-d0830be43fa5&gt; in &lt;module&gt;() 6 "PavedDrive":{"Y": 2,"P": 1,"N": 0 }} 7 ----&gt; 8 housing_dataframe = housing_dataframe.replace(ordinal_mapping_dict) c:\users\diro\appdata\local\programs\python\python37\lib\site-packages\pandas\core\generic.py in replace(self, to_replace, value, inplace, limit, regex, method, axis) 4529 4530 return self.replace(to_replace, value, inplace=inplace, -&gt; 4531 limit=limit, regex=regex) 4532 else: 4533 c:\users\diro\appdata\local\programs\python\python37\lib\site-packages\pandas\core\generic.py in replace(self, to_replace, value, inplace, limit, regex, method, axis) 4548 value=value[c], 4549 inplace=False, -&gt; 4550 regex=regex) 4551 return None if inplace else res 4552 c:\users\diro\appdata\local\programs\python\python37\lib\site-packages\pandas\core\generic.py in replace(self, to_replace, value, inplace, limit, regex, method, axis) 4578 dest_list=value, 4579 inplace=inplace, -&gt; 4580 regex=regex) 4581 4582 else: # [NA, ''] -&gt; 0 c:\users\diro\appdata\local\programs\python\python37\lib\site-packages\pandas\core\internals.py in replace_list(self, src_list, dest_list, inplace, regex, mgr) 3500 convert = i == src_len 3501 result = b.repl…
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/138452644
type: UnansweredQuestion
answer count: 1
has title: Error during replacement of categorical values in data with numerical values using Pandas replace module
downvote count: 0

http://stackoverflow.com/comment/86605782
type: QuestionComment
has text: If it freezes, it is likely because you are mixing `grid` and `pack` in the same frame. Please show us a [mcve].
comment on: http://stackoverflow.com/q/49788230
score: 1
type: Comment

http://stackoverflow.com/q/49823594
has comment: http://stackoverflow.com/comment/86724835
tagged with: python
has title: Flask-SQLalchemy second layer query
has comment: http://stackoverflow.com/comment/86726398
has answer: http://stackoverflow.com/a/49865548
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49865548
score: 0
has comment: http://stackoverflow.com/comment/86724218
answer count: 1
has body: I'm trying to obtain the information contained in "DATA" with the following tables: class Table_1(db.Model): id = db.Column(db.Integer, primary_key=True) table_2_id = db.Column(db.Integer, db.ForeignKey('table_2.id')) table_4_id = db.Column(db.Integer, db.ForeignKey('table_4.id')) class Table_2(db.Model): id = db.Column(db.Integer, primary_key=True) table_3_id = db.Column(db.Integer, db.ForeignKey('table_3.id')) NAME = db.Column(db.String(60)) table_1 = db.relationship('Table_1', backref='table_1_table_2', lazy=True) class Table_3(db.Model): id = db.Column(db.Integer, primary_key=True) DATA = db.Column(db.String(60)) table_2 = db.relationship('Table_2', backref='table_2_table_3', lazy=True) I can get the value of of NAME with Table_1.query.join(Table_2).add_columns(Table_2.NAME).all(). How can i add_column(Table_3.Data)? Thanks in advance!
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/86725209
has comment: http://stackoverflow.com/comment/86725596
has comment: http://stackoverflow.com/comment/86723903

http://stackoverflow.com/comment/86830786
type: AnswerComment
comment on: http://stackoverflow.com/a/49882926
score: 0
type: Comment
has text: From the information you have given, we have no way to know what the ZEA projection parameters should be for your image. Can you talk to someone locally that took this image and knows FITS / WCS to help you figure this out?

http://stackoverflow.com/comment/129067395
type: AnswerComment
has text: Update: find_element_by_xpath is deprecated now and one should use the equivalent `browser.find_element(By.XPATH, '//button[normalize-space()="Outliers"]')` (need to `from selenium.webdriver.common.by import By`)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49906334

http://stackoverflow.com/comment/86848751
comment on: http://stackoverflow.com/q/49916452
has text: You should ask only 1 question per ticket! If you get 2 separate answers on each question, which one will be accepted?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49818664
has comment: http://stackoverflow.com/comment/131230705
answers question: http://stackoverflow.com/q/49818592
has body: I would create a script, e.g. a bash script. You would execute the script instead of pip install my_module
type: Answer
has comment: http://stackoverflow.com/comment/86652240
score: 0

http://stackoverflow.com/q/49760634
has answer: http://stackoverflow.com/a/49760697
has comment: http://stackoverflow.com/comment/86536385
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86536433
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/8725673
accepted answer: http://stackoverflow.com/a/49760697
has body: In Python a,b =b,a+b is there anything similar in Java? I tried the same thing in Java but it didn't work.
tagged with: java
tagged with: variable-assignment
has comment: http://stackoverflow.com/comment/86536456
downvote count: 1
has title: Does Java have multiple assignment as in Python?
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/6202818
upvote count: 0
answer count: 1

arff
tags question: http://stackoverflow.com/q/49828401
tags question: http://stackoverflow.com/q/49806439
tag name: arff
type: Tag

http://stackoverflow.com/a/49826466
has body: I would advise you structure your code as below. It's usually a good idea for your function to return something. def setup(): n = int(input('How many players would you like? (up to 4)')) names = [input('Give name #{0}'.format(i)) for i in range(1, n+1)] return [Player(name, 1500, 0) for name in names] players = setup()
has comment: http://stackoverflow.com/comment/86669205
has comment: http://stackoverflow.com/comment/86668631
upvote count: 1
answers question: http://stackoverflow.com/q/49826305
has comment: http://stackoverflow.com/comment/86668682
has comment: http://stackoverflow.com/comment/86668566
has comment: http://stackoverflow.com/comment/86668584
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/86741095
type: AnswerComment
score: 1
has text: @Roushan: xrange returns a lazy sequence object, not a generator. Also, the tags still say 3.x.
type: Comment
comment on: http://stackoverflow.com/a/49862949

http://stackoverflow.com/q/49784739
has comment: http://stackoverflow.com/comment/86594863
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/86589244
has comment: http://stackoverflow.com/comment/86584913
tagged with: python
has title: Python 3.6.5 - os.makedirs / os.mkdir doesn't create directory without any error
has body: I need any help for a weird problem with my Python 3.6.5 code. The error is only produced during my project execution, I haven't succeeded to recreate it during another script execution... I would like to create some folders during __init__ function into some class, with os.makedirs : self.working_folder = Preprocessor.prepare_folder(working_folder) # create final working folder self.previews_folder = Preprocessor.prepare_folder(previews_folder) # create previews folder Here the "working_folder" is created instead "previews_folder" isn't, without any error. If I try this code : self.working_folder = Preprocessor.prepare_folder(working_folder) # create final working folder Preprocessor.prepare_folder(previews_folder) # create previews folder Both folders are created correctly. Details about "Preprocessor.prepare_folder" : def prepare_folder(folder_path): print("Path to create: ", folder_path) while True: try: os.makedirs(folder_path) print("Folder created as: ", folder_path) return folder_path except FileExistsError: if folder_path[-1] in ("/", "\\"): folder_path = folder_path[:len(folder_path) - 1] if folder_path[-1].isdigit(): temp = folder_path[-1] for i in range(len(folder_path) - 2, -1, -1): try: if folder_path[i].isdigit(): temp = folder_path[i] + temp else: folder_path = folder_path[:i + 1] break except IndexError: raise EnvironmentError folder_path = folder_path + str(int(temp) + 1) else: folder_path += '1' Operating System : Windows 10 x64 Family Tracebacks: Path to create: C:\Users\MPuis\Downloads\Tests\classifier_temp Folder created as: C:\Users\MPuis\Downloads\Tests\classifier_temp Path to create: C:\Users\MPuis\Downloads\Tests\previews_temp Folder created as: C:\Users\MPuis\Downloads\Tests\previews_temp Process finished with exit code 0 DOS terminal with "dir" command: Répertoire de C:\Users\MPuis\Downloads\Tests 11/04/2018 23:42 &lt;DIR&gt; . 11/04/2018 23:42 &lt;DIR&gt; .. 11/04/2018 23:42 &lt;DIR&gt; classifier_temp 10/04/2018 12:18 &lt;DIR&gt; Models…
tagged with: python-3.6
has answer: http://stackoverflow.com/a/49789934
downvote count: 3
has comment: http://stackoverflow.com/comment/86585304
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/86585006
has comment: http://stackoverflow.com/comment/86585171
has comment: http://stackoverflow.com/comment/86585194
has comment: http://stackoverflow.com/comment/86584890
has comment: http://stackoverflow.com/comment/86585234
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/49853098
answers question: http://stackoverflow.com/q/49816503
type: Answer
has body: I think something like this could work: We define the loss function that has a layer as an input. Note that input to torch.norm should be torch Tensor so we need to do .data in the weights of the layer because it is a Parameter. Then, we compute the norm of the layer setting un p=1 (L1). def l1_loss(layer): return (torch.norm(layer.weight.data, p=1)) lin1 = nn.Linear(8, 64) l = l1_loss(lin1)
score: 0

http://stackoverflow.com/q/49838007
downvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/18160078
has comment: http://stackoverflow.com/comment/86704873
has body: I am trying to use unittest with a program that uses the argparse module and having some difficulties. I referenced this helpful post as a starting point but I'm clearly still missing something. Here is the basic program: #arg_test.py import sys import argparse class Thingy: def __init__(self, name): self.name = name def parse_args(args): parser = argparse.ArgumentParser(description='description here') parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1') parser.add_argument('-a', '--arg1', required=True, help='this is for arg1') parser.add_argument('-b', '--arg2', required=True, help='this is for arg2') return parser.parse_args() def main(): parser = Thingy.parse_args(sys.argv[1:]) print('the args are: {}'.format(parser)) if parser.arg1: print('the value of arg1 is : {}'.format(parser.arg1)) if parser.arg2: print('the value of arg2 is : {}'.format(parser.arg2)) if __name__ == '__main__': main() Running this: python arg_test.py --arg1 asdf --arg2 qwer Results in the expected output of: the args are: Namespace(arg1='asdf', arg2='qwer') the value of arg1 is : asdf the value of arg2 is : qwer Now here is the simple unittest program: #test/test_arg_test.py import unittest from arg_test import Thingy def test_parser(self): parser = Thingy.parse_args(['--arg1']) self.assertTrue(parser.arg1,'asdf') if __name__ == '__main__': main() Running this: python -m unittest -v test/test_arg_test.py --arg1 asdf --arg2 qwer Results in this: python -m unittest -v test/test_arg_test.py --arg1 asdf --arg2 qwer usage: python -m unittest [-h] [-v] [-q] [--locals] [-f] [-c] [-b] [tests [tests ...]] python -m unittest: error: unrecognized arguments: --arg1 asdf --arg2 qwer Can someone please point me in the right direction on how to run these tests? Thanks. Update #1 Here is the updated unittest program based on the helpful recommendations below but something is still missing. #import unittest from arg_test import Thingy class TestThingys(unittest.TestCase): def te…
tagged with: unit-testing
favorite count: 0
type: Question
upvote count: 9
has answer: http://stackoverflow.com/a/49838142
has comment: http://stackoverflow.com/comment/86691179
tagged with: argparse
tagged with: python
score: 8
has comment: http://stackoverflow.com/comment/86705766
has title: Python unittest with argparse
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49838142
has comment: http://stackoverflow.com/comment/86705071
has comment: http://stackoverflow.com/comment/86691409

http://stackoverflow.com/q/49808155
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/49808181
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/86631252
has answer: http://stackoverflow.com/a/49808181
has body: I want to draw a plot like the graph below As the top plot, ytick is [1,10,100,1000,10000,...]. It's not the same and ten times for each point. I want to do this because 0 group and 1 group is imbalance and 1 is too small to 0. If I'm not scale, group 1 is near zero. Please help me. Thank a lot.
score: -1
type: Question
tagged with: python-3.x
has title: How to change interval of yticks to not equally range?
upvote count: 0
answer count: 1
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/86643350
type: QuestionComment
has text: The reason, why you don't see anything, is that you plot a line from point (0,1) to point(0,1). It is just a point. The first parameter is a list of x-values, the second y-values. Please read [the matplotlib tutorials](https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py). If you want to provide a list of xy points, you should, well, provide a list like `[[0.,0.], [1.,1.]]`.
score: 2
comment on: http://stackoverflow.com/q/49814331
type: Comment

http://stackoverflow.com/comment/86718953
type: QuestionComment
has text: Ps: The way you named your model is incorrect. It should be named as just *Content*
score: 0
comment on: http://stackoverflow.com/q/49852108
type: Comment

http://stackoverflow.com/a/49839769
answers question: http://stackoverflow.com/q/49839622
has body: This way uses readlines to get file contents in a list line by line. readlines returns a list containing lines. Now iterate through list to check if user input matches with line content (which is a word in this case). with open ('/Users/someone/Desktop/input.txt', 'r') as myfile: words = myfile.readlines() while x &lt; len(words): if words[x] == input('Enter word to guess'): print('Predicted word correctly') else: print('Wrong word. Try again') x -= 1 x += 1
score: 0
type: Answer

http://stackoverflow.com/q/49837539
tagged with: pandas
has comment: http://stackoverflow.com/comment/86690801
score: 3
has comment: http://stackoverflow.com/comment/86690381
tagged with: python
has comment: http://stackoverflow.com/comment/86690785
accepted answer: http://stackoverflow.com/a/49843721
has title: why is multiprocessing slower than a simple computation in Pandas?
has comment: http://stackoverflow.com/comment/86690784
linked to: http://stackoverflow.com/q/37979167
has comment: http://stackoverflow.com/comment/86690730
tagged with: python-multiprocessing
has answer: http://stackoverflow.com/a/49843721
type: Question
tagged with: dask
has comment: http://stackoverflow.com/comment/86699828
upvote count: 3
has comment: http://stackoverflow.com/comment/86690353
downvote count: 0
answer count: 1
has body: This is related to how to parallelize many (fuzzy) string comparisons using apply in Pandas? Consider this simple (but funny) example again: import dask.dataframe as dd import dask.multiprocessing import dask.threaded from fuzzywuzzy import fuzz import pandas as pd master= pd.DataFrame({'original':['this is a nice sentence', 'this is another one', 'stackoverflow is nice']}) slave= pd.DataFrame({'name':['hello world', 'congratulations', 'this is a nice sentence ', 'this is another one', 'stackoverflow is nice'],'my_value': [1,2,3,4,5]}) def fuzzy_score(str1, str2): return fuzz.token_set_ratio(str1, str2) def helper(orig_string, slave_df): slave_df['score'] = slave_df.name.apply(lambda x: fuzzy_score(x,orig_string)) #return my_value corresponding to the highest score return slave_df.loc[slave_df.score.idxmax(),'my_value'] master Out[39]: original 0 this is a nice sentence 1 this is another one 2 stackoverflow is nice slave Out[40]: my_value name 0 1 hello world 1 2 congratulations 2 3 this is a nice sentence 3 4 this is another one 4 5 stackoverflow is nice What I need to do is simple: For every row in master, I lookup into the Dataframe slave for the best match using the string similarity score computed by fuzzywuzzy. Now let's make these dataframes a bit bigger: master = pd.concat([master] * 100, ignore_index = True) slave = pd.concat([slave] * 10, ignore_index = True) First, I have tried with dask #prepare the computation dmaster = dd.from_pandas(master, npartitions=4) dmaster['my_value'] = dmaster.original.apply(lambda x: helper(x, slave),meta=('x','f8')) and now here are the timings: #multithreaded %timeit dmaster.compute(get=dask.threaded.get) 1 loop, best of 3: 346 ms per loop #multiprocess %timeit dmaster.compute(get=dask.multiprocessing.get) 1 loop, best of 3: 1.93 s per loop #good 'ol pandas %timeit master['my_value'] = master.original.apply(lambda x: helper(x,slave)) 100 loops, best of 3: 2.18 ms per loop Second, I have tried with the good old multiprocessi…
has comment: http://stackoverflow.com/comment/86690372
has comment: http://stackoverflow.com/comment/86690767
favorite count: 0
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/86690743
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86690406

http://stackoverflow.com/comment/86716002
type: Comment
comment on: http://stackoverflow.com/a/49814091
score: 0
type: AnswerComment
has text: Thanks for the answer. It solved my problem. But its a bit slow with 300k records. Any idea how to speed it up?

http://stackoverflow.com/comment/86550230
comment on: http://stackoverflow.com/q/49766058
has text: Did you try to wrap an endpoint with try/except block and in case of error return traceback as response?
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/49845832
type: Answer
has comment: http://stackoverflow.com/comment/86717418
accepted answer of: http://stackoverflow.com/q/49845755
has body: use the tuple index to get the right element out of them. results_list = [tup[0] for tup in results]
answers question: http://stackoverflow.com/q/49845755
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/86617424
comment on: http://stackoverflow.com/q/49800835
has text: Hmmm. I'm using pandas 0.18, maybe this has been fixed?
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/95578216
type: Comment
type: QuestionComment
has text: You can check [this answer](https://stackoverflow.com/a/54382536/1534017) which - I think - solves your problem.
score: 0
comment on: http://stackoverflow.com/q/49904483

http://stackoverflow.com/a/49833828
upvote count: 1
has body: You can use a list comprehension with sum to construct C. C = [sum(elem in sub for sub in B) for elem in A] This has the same effect as using nested for loops: C = [] for elem in A: sum = 0 for sub in B: sum += elem in sub C.append(sum)
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49833668
downvote count: 0

http://stackoverflow.com/comment/86693910
type: Comment
comment on: http://stackoverflow.com/q/49837930
type: QuestionComment
score: 0
has text: I'm running on Windows 10 and I kinda follow this example : [link](https://github.com/line/line-bot-sdk-python/blob/master/examples/flask-kitchensink/app.py). Not sure what you mean how I run flask. Sorry @KlausD.

http://stackoverflow.com/a/49820885
has body: You can use str.replace directly. def correct(string): return string.replace('5','S').replace('0','O').replace('1','I')
score: 5
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49820806
downvote count: 0

http://stackoverflow.com/comment/86630187
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49807471
type: QuestionComment
has text: so i'm not the one who wrote the program... i'm just trying to run it to generate some accounts. perhaps if i post the python code it will help so i'll attach it.. ok put the code in! Thanks for any help

http://stackoverflow.com/comment/86724254
type: Comment
comment on: http://stackoverflow.com/q/49852972
has text: As for your question: when you generate your datetime from a string, are you taking timezone info into account? You’re likely storing dates in utc but when you construct your beginning time from a string, you may be involving your local timezone, hence the unexpected results
score: 0
type: QuestionComment

http://stackoverflow.com/q/49770999
tagged with: docker
has body: Being new to python &amp; docker, I created a small flask app (test.py) which has two hardcoded values: username = "test" password = "12345" I'm able to create a Docker image and run a container from the following Dockerfile: FROM python:3.6 RUN mkdir /code WORKDIR /code ADD . /code/ RUN pip install -r requirements.txt EXPOSE 5000 CMD ["python", "/code/test.py"]` How can I create a ENV variable for username &amp; password and pass dynamic values while running containers?
has answer: http://stackoverflow.com/a/62854381
has answer: http://stackoverflow.com/a/49771684
downvote count: 1
has title: Docker ENV for Python variables
favorite count: 0
type: Question
upvote count: 61
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49771791
has answer: http://stackoverflow.com/a/72911511
score: 60
tagged with: python
tagged with: flask
answer count: 4

http://stackoverflow.com/q/49796203
tagged with: pip
tagged with: python
tagged with: virtualenv
favorite count: 0
has title: bypass pkg_resources.DistributionNotFound
score: 2
answer count: 0
type: Question
has body: I have a python application that requires a package that uses newrelic. I want to test my application with a newer version of newrelic, but the package has a max version on newrelic which is lower then the one I want to test out. So before I update the package to use the newer version of newrelic I want to test it out. But I get a pkg_resources.DistributionNotFound when I start my application with the newer newrelic version. pkg_resources.DistributionNotFound: The 'newrelic&lt;3dev,&gt;=2.88.1.73' distribution was not found and is required by xxxx Is there a way to bypass this requirement by the package? If so - how? Or if there is an even easier way I just haven't thought of.
upvote count: 2
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/86826256
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49905056
has text: issue is that I need to add two such columns of pandas and combine it into one list. So i need to use a list comprehension and that makes it a list of lists if I use ast.literal_eval
type: Comment

http://stackoverflow.com/q/49767309
downvote count: 2
has comment: http://stackoverflow.com/comment/86553574
linked to: http://stackoverflow.com/q/3926451
linked to: http://stackoverflow.com/q/31915018
has comment: http://stackoverflow.com/comment/86601104
has comment: http://stackoverflow.com/comment/86587607
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/86553413
has body: My python regex using re is returning a list of tuples where I only expect a simple list. I am scraping over 100 webpages using beautiful soup to obtain software version information that is returned in a javascript array. The script loops over a list of IP addresses and version info is logged to file. Example source: &lt;script language="Javascript"&gt; var active='2'; Appname[0]='foobar'; Appversion[0]='6.02 TEST prod'; Appversion[0]='6.02 TEST '; Appname[1]='barfoo'; Appversion[1]='06.0001.00'; Appversion[1]='06.0001.00'; Appname[1]='barfoo'; Appversion[1]='06.0001.00'; Appversion[1]='06.0001.00'; &lt;/script&gt; As you can see the second array element is usually declared twice, and sometimes four times (but not on all instances of the retrieved web page). I would like to simply take the last value assigned. The active variable is one more than the required array element. There are other arrays and variables omitted for clarity. Desired output for the example: &lt;ip addr&gt; 1 barfoo 06.0001.00 My code is based on this post and this: jscript = soup.find("script", text=lambda text: "var Appversion" in text) # following lookaround regex; match but discard active=' and '; to return only the assigned value regex = r"(?&lt;=active=')((.*)(?=';))" pattern = re.compile(regex) active = pattern.search(jscript.get_text(), re.MULTILINE) index = int(active.group())-1 pstring = pstring + '\t' + str(index) array_names = ["Appname", "Appversion"] for name in array_names: regex=r"(?&lt;=" + name + r"\[" + str(index) + r"\]=')((.*)(?=';))" pattern = re.compile(regex) name_match = pattern.findall(jscript.get_text(), re.MULTILINE) last_index = len(name_match)-1 # no idea why we have tuples, what do we have print(name_match) # crashes for Appversion in example pstring = pstring + '\t' + name_match[last_index][last_index] The output from print (name_match) is: [('barfoo', 'barfoo'), ('barfoo', 'barfoo')] [('06.0001.00', '06.0001.00'), ('06.0001.00', '06.0001.00'), ('06.0001.00', '06.…
has comment: http://stackoverflow.com/comment/86554249
duplicate of: http://stackoverflow.com/q/31915018
type: Question
upvote count: 2
answer count: 0
tagged with: javascript
tagged with: python
type: UnansweredQuestion
tagged with: regex
has title: extracting javascript array variables using regex returns a list of tuples
linked to: http://stackoverflow.com/q/42238211
has comment: http://stackoverflow.com/comment/86551696
score: 0

http://stackoverflow.com/comment/86582117
type: QuestionComment
score: 0
has text: what function did you use to do the match?
comment on: http://stackoverflow.com/q/49783387
type: Comment

http://stackoverflow.com/comment/86730308
comment on: http://stackoverflow.com/a/49777091
has text: Hi David, what is happening is formdata is empty. I have checked the network tab in chrome developer tools and the request payload section is empty, I am not sure why that is happening :(
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49873225
has title: Aggregating data over matching cell in rows and calculate difference in dates
tagged with: python
accepted answer: http://stackoverflow.com/a/49873302
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49873302
score: 0
tagged with: pandas
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I have a Dataframe: d = {'User': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C', 'C'], 'Date' : ['2017-10-21', '2017-10-24', '2017-10-29', '2017-09-30', '2017-10-23', '2017-10-31', '2017-11-02', '2017-11-03', '2017-11-03']} df = pd.Dataframe(data=d) which looks like: User Date A 2017-10-21 A 2017-10-24 A 2017-10-29 B 2017-09-30 B 2017-10-23 C 2017-10-31 C 2017-11-02 C 2017-11-03 C 2017-11-03 What I want is adding another column to find the difference between dates of each user: starting from the earliest date (so difference is 0) to the next, and the next date to the date after that and so on. The Dataframe would then look like: User Date Difference A 2017-10-21 0 A 2017-10-24 3 A 2017-10-29 5 B 2017-09-30 0 B 2017-10-23 23 C 2017-10-31 0 C 2017-11-02 2 C 2017-11-03 1 C 2017-11-03 0 Note: The users and the dates are already sorted in the original Dataframe.

flask-restful
tags question: http://stackoverflow.com/q/49846559
type: Tag
tags question: http://stackoverflow.com/q/49912025
tags question: http://stackoverflow.com/q/49784883
tag name: flask-restful

http://stackoverflow.com/comment/86680941
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49831121
has text: I agree, I was basically overriding the method.
type: AnswerComment

http://stackoverflow.com/comment/86784302
type: QuestionComment
score: 0
has text: Why do you need sql?
type: Comment
comment on: http://stackoverflow.com/q/49884072

http://stackoverflow.com/comment/86676447
comment on: http://stackoverflow.com/a/49830628
type: Comment
score: 0
type: AnswerComment
has text: Thank you for your response, could you tell me where was the problem in my code..the simplified version

http://stackoverflow.com/q/49852455
has body: As the title says, how can I find the null space of a matrix i.e. the nontrivial solution to the equation ax=0. I've tried to use np.linalg.solve(a,b), which solves the equation ax=b. So setting b equal to an array of zeros with the same dimensions as matrix a, I only get the trivial solution i.e. x=0.
has title: How to find the Null Space of a matrix in Python using numpy?
favorite count: 0
linked to: http://stackoverflow.com/q/5889142
type: AnsweredQuestion
score: 1
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/86720414
accepted answer: http://stackoverflow.com/a/49852558
possible better answer: http://stackoverflow.com/a/49852529
has answer: http://stackoverflow.com/a/49852558
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49852529
tagged with: python

http://stackoverflow.com/comment/86685850
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49835348
has text: If i am trying to run my server with python manage.py runserver then i am getting the following error: from django.urls import path ImportError: cannot import name 'path'
score: 0

http://stackoverflow.com/comment/86640552
type: AnswerComment
has text: I am splitting on space - rather than on comma, but I always like to leave something for the end user to do :)
comment on: http://stackoverflow.com/a/49811645
score: 1
type: Comment

http://stackoverflow.com/comment/86701061
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49843203
has text: @Divakar It's good. Why not post as answer and get credit my dude?

http://stackoverflow.com/q/49816092
downvote count: 0
favorite count: 0
type: Question
has body: I created a database and got it working as far as searching for a specific batchnr. what i would like to do is as follows: input batchnumber:1001 It will give me the following result: (1001, 90, 10001, 2, 500, 'Veghel', 100, 300) Then the following question gets asked: "would you like to change something about this" The value you want to change is stored in "ChangeThis" and the value you want it to be changed in is stored in "ToThis" (had to translate it to english so thats why it's pretty basic) For example you will get something like this: (1001, 90, 10001, 2, 500, 'Veghel', 100, 300) change what: 500 into: 9999 Now I want to put these variables into my python-SQL code i tried this: conn = sqlite3.connect('DATABASE.db') cur = conn.cursor() ChangeThis = str(input("which value would you like to change?(value):")) ToThis = str(input("In what would you like to change this?(value):")) change = 'UPDATE batch SET ? WHERE ?' (ToThis, ChangeThis) print(change) cur.execute(change) This gives me the TypeError: 'str' object is not callable. Does anyone have an idea how to fix this? full code is posted below: import sqlite3 def create_connection(): try: conn = sqlite3.connect('DATABASE.db') return conn except Error as e: print(e) def select_all(): conn = sqlite3.connect('DATABASE.db') cur = conn.cursor() batchnr = input("batchnumber:") sqlquery = 'SELECT * FROM BATCH WHERE BATCHNR ='+ batchnr #print(sqlquery) cur.execute(sqlquery) rows = cur.fetchall() for row in rows: print(row) verander = input("Would you like to change something about this?Y/N: ") if verander == 'Y' or verander == 'y': veranderen() else: print("Shutdown") def veranderen(): conn = sqlite3.connect('DATABASE.db') cur = conn.cursor() ChangeThis = str(input("which value would you like to change?(value):")) ToThis = str(input("In what would you like to change this?(value):")) change = 'UPDATE batch SET ? WHERE ?' (ToThis, ChangeThis) print(change) cur.execute(change) create_connection() select_all()
tagged with: database
accepted answer: http://stackoverflow.com/a/49817150
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49817150
type: AnsweredQuestion
has title: Change SQL Database value via variables
score: 1
tagged with: sqlite
answer count: 1

http://stackoverflow.com/q/49812284
has title: Why does numpy return different random numbers from the same random state?
has answer: http://stackoverflow.com/a/49813138
has comment: http://stackoverflow.com/comment/86639491
score: 2
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/49813118
downvote count: 1
has comment: http://stackoverflow.com/comment/86639780
has comment: http://stackoverflow.com/comment/86640253
has comment: http://stackoverflow.com/comment/86639109
favorite count: 0
linked to: http://stackoverflow.com/q/37224116
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49813118
linked to: http://stackoverflow.com/q/5836335
answer count: 2
has comment: http://stackoverflow.com/comment/86639519
has comment: http://stackoverflow.com/comment/86639699
has body: Important Edit: If you find the time to test the snippets below, please make sure to start a completely fresh session or call np.random.seed(None) once. Background: I have been under the impression that functions such as np.random.randint() would draw the same set of numbers for identical random states (or whatever you would call the output from np.random.get_state()). Let me explain why: The following snippet uses np.random.randint() to generate 5 random integers betwenn -10 and 10, and stores some info about the process. What I've named 'state' are the 5 first numbers from the array stored in the second element in the tuple returned by np.random.get_state(). Snippet 1 # 1. Imports import pandas as pd import numpy as np # 2. describe random state by # retrieving the five first numbers # in the array in the second element # of the tuple returned by np.random.get_state() randomState = np.random.get_state() state = np.random.get_state()[1][:5] # 3. generate random numbers randints = np.random.randint(-10, 10, size = 5) # 4. organize and present findings df = pd.DataFrame.from_dict({'state':state, 'randints':randints}) print(df) Run this code once and you'll get results as in the first output section below. Just notice that the numbers themselves will differ from mine since no random seed has been set. What is important is the internal logic of the three sets of output. And if you run the same snippet more that once, you'll notice something that I think is really weird: Output 1: some random numbers and a random state: randints state 0 -10 2871458436 1 7 4226334938 2 1 179611462 3 -9 3145869243 4 5 317931933 So far, so good! We have 5 random integers and 5 numbers representing the random state. Run the same snippet again, and you'll get something like this: Output 2: new random numbers and a new random state: randints state 0 1 727254058 1 7 1473793264 2 4 2934556005 3 1 721863250 4 -6 3873014002 Now you seemingly have a new random state and 5 new random numbers. So se…
has comment: http://stackoverflow.com/comment/86639409
possible better answer: http://stackoverflow.com/a/49813138
tagged with: python
has comment: http://stackoverflow.com/comment/86640622

http://stackoverflow.com/comment/86687788
type: Comment
has text: Edited answer, added missing parenthesis
type: AnswerComment
comment on: http://stackoverflow.com/a/49836207
score: 1

http://stackoverflow.com/q/49819714
has comment: http://stackoverflow.com/comment/86655293
downvote count: 1
favorite count: 0
tagged with: xpath
has title: String concatenation with python and xpath
has body: Instead of writing 10+ IF statements, I'm trying to create one IF statement using a variable. Unfortunately, I'm not familiar with how to implement string concatenation for xpath using python. Can anyone teach me how to perform string formatting for the following code segments? I would greatly appreciate it, thanks. if page_number == 1: next_link = browser.find_element_by_xpath('//*[@title="Go to page 2"]') next_link.click() page_number = page_number + 1 time.sleep(30) elif page_number == 2: next_link = browser.find_element_by_xpath('//*[@title="Go to page 3"]') next_link.click() page_number = page_number + 1 time.sleep(30)
tagged with: string-formatting
answer count: 2
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/49820326
tagged with: string-concatenation
accepted answer: http://stackoverflow.com/a/49819833
has answer: http://stackoverflow.com/a/49820326
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49819833
type: Question
has comment: http://stackoverflow.com/comment/86655368
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49906675
upvote count: 3
downvote count: 0
has body: Loading a big dataset in memory is not a good idea. I suggest you to use something different for loading the datasets, take a look to the dataset API in TensorFlow: https://www.tensorflow.org/programmers_guide/datasets You might need to convert your data into other format, but if you have a CSV or TXT file with a example per line you can use TextLineDataset and feed the model with it: filenames = ["/var/data/file1.txt", "/var/data/file2.txt"] dataset = tf.data.TextLineDataset(filenames) def _parse_py_fun(text_line): ... your custom code here, return np arrays def _map_fun(text_line): result = tf.py_func(_parse_py_fun, [text_line], [tf.uint8]) ... other tensorlow code here return result dataset = dataset.map(_map_fun) dataset = dataset.batch(4) iterator = dataset.make_one_shot_iterator() input_data_of_your_model = iterator.get_next() output = build_model_fn(input_data_of_your_model) sess.run([output]) # the input was assigned directly when creating the model
type: Answer
answers question: http://stackoverflow.com/q/49900798
score: 3

http://stackoverflow.com/comment/86849255
comment on: http://stackoverflow.com/q/49915894
score: 0
type: Comment
type: QuestionComment
has text: @MonirulIslam Try using the `approxPolyDP`. You could also try using `connectedComponents`

http://stackoverflow.com/a/49807063
has comment: http://stackoverflow.com/comment/86660079
type: Answer
has body: This page is a dynamic, i.e., the content is dynamically generated by javascript and showed in the front. That is the reason you can't detect the div tag. But in this case you can scrape easier. With inspect tool from your browser you can detect that the data comes from a GET request to an URL. For your example, you only have to provide the players id : import requests url = 'http://lookup-service-prod.mlb.com/json/named.stats_batter_vs_pitcher_composed.bam' params = {"sport_code":"'mlb'","game_type":"'R'","player_id":"571771","pitcher_id":"641941"} resp = requests.get(url, params=params).json() print(resp) That prints: {'stats_batter_vs_pitcher_composed': {'stats_batter_vs_pitcher_total': {'queryResults': {'created': '2018-04-12T22:21:47', 'totalSize': '1', 'row': {'hr': '1', 'gidp': '0', 'pitcher_first_last_html': 'Emilio Pagán', 'player': 'Hernandez, Enrique', 'np': '4', 'sac': '0', 'pitcher': 'Pagan, Emilio', 'rbi': '1', 'player_first_last_html': 'Enrique Hernández', 'tb': '4', 'bats': 'R', 'xbh': '1', 'bb': '0', 'slg': '4.000', 'avg': '1.000', 'pitcher_id': '641941', 'ops': '5.000', 'hbp': '0', 'pitcher_html': 'Pagán, Emilio', 'g': '', 'd': '0', 'so': '0', 'throws': 'R', 'sf': '0', 'tpa': '1', 'h': '1', 'cs': '0', 'obp': '1.000', 't': '0', 'ao': '0', 'r': '1', 'go_ao': '-.--', 'sb': '0', 'player_html': 'Hernández, Enrique', 'sbpct': '.---', 'player_id': '571771', 'ibb': '0', 'ab': '1', 'go': '0'}}}, 'copyRight': ' Copyright 2018 MLB Advanced Media, L.P. Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt ', 'stats_batter_vs_pitcher': {'queryResults': {'created': '2018-04-12T22:21:47', 'totalSize': '1', 'row': {'hr': '1', 'gidp': '0', 'pitcher_first_last_html': 'Emilio Pagán', 'player': 'Hernandez, Enrique', 'np': '4', 'sac': '0', 'pitcher': 'Pagan, Emilio', 'rbi': '1', 'opponent': 'Oakland Athletics', 'player_first_last_html': 'Enrique Hernández', 'tb': '4', 'xbh': '1', 'bats': 'R', 'bb': '…
accepted answer of: http://stackoverflow.com/q/49806786
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49806786
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86660790

http://stackoverflow.com/comment/86735249
comment on: http://stackoverflow.com/a/49859718
type: Comment
score: 0
type: AnswerComment
has text: Hi. We are using Pull-Subscriptions exactly as mentioned under Load-Balancing. Nevertheless all clients are pulling the same first chunk. See observed behavior in my picture.

statsd
tags question: http://stackoverflow.com/q/49852654
tag name: statsd
type: Tag

http://stackoverflow.com/comment/86837662
comment on: http://stackoverflow.com/q/49904468
score: 0
type: QuestionComment
has text: In that case you probably want the [`fractions` module](https://docs.python.org/3.1/library/fractions.html).
type: Comment

http://stackoverflow.com/q/49766216
downvote count: 0
has comment: http://stackoverflow.com/comment/86547900
has answer: http://stackoverflow.com/a/49767711
has comment: http://stackoverflow.com/comment/86550418
upvote count: 1
tagged with: python
has body: I have a YAML file with content: --- 'Croatia': population: 4600000 capital: Zagreb 'Italy': population: 60000000 capital: Rome How do I want to add a new field: --- 'Croatia': population: 4600000 capital: Zagreb continent: Europe 'Italy': population: 60000000 capital: Rome continent: Europe How do I add the field "continent" with value Europe to every State?
score: 1
tagged with: yaml
has answer: http://stackoverflow.com/a/49766242
has comment: http://stackoverflow.com/comment/86547858
favorite count: 0
linked to: http://stackoverflow.com/q/29518833
tagged with: parsing
tagged with: pyyaml
type: Question
answer count: 2
has title: How do I add a new field to a YAML file in python?
tagged with: field
type: UnansweredQuestion

http://stackoverflow.com/q/49760916
has answer: http://stackoverflow.com/a/49761703
accepted answer: http://stackoverflow.com/a/49760973
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/21702342
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/49760973
has title: Python Pandas Dataframe create column as number of occurrence of string in another columns
downvote count: 0
possible better answer: http://stackoverflow.com/a/49761703
favorite count: 0
type: Question
upvote count: 2
tagged with: dataframe
tagged with: python
has body: I have a dataframe and I want to count how many times a string (say 'Yes') has occurred in all other columns. I want to add count into new column and call it 'Yes-Count'. I have it working using lamda and following example Creating a new column based on if-elif-else condition I am curious if this can be done in one line. This is sample data and code. import pandas as pd def finalCount(row): count = 0 if row['Col1'] == 'Yes': count = count + 1 if row['Col2'] == 'Yes': count = count + 1 if row['Col3'] == 'Yes': count = count + 1 if row['Col4'] == 'Yes': count = count + 1 return count data = { 'Col1': ['Yes', 1, 'No', 'Yes'], 'Col2': ['Yes', 2, 'No', 'Yes'], 'Col3': ['No', 3, 'Yes', 'Yes'], 'Col4': ['Yes', 4, 'No', 'Yes'], } dfData = pd.DataFrame(data, columns= ['Col1','Col2','Col3','Col4']) dfData['Yes-Count'] = dfData.apply(finalCount, axis =1) I get result as expected. Is there a way to get rid of finalCount method and do this in one line?

http://stackoverflow.com/q/49766150
type: Question
tagged with: beautifulsoup
has body: I'm trying to scrape all of the stats of off basketball-reference by player using BeautifulSoup. Let's use Michael Jordan as an example: https://www.basketball-reference.com/players/j/jordami01.html. The problem is when I grab the html page and parse through the html I can only grab one table of data and the others seem to be commented out. I'm pretty new to python and was hoping someone could walk me through why the html seems to have certain tables of data as comments. Can someone walk me through a workaround? from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import pandas as pd MJ_url = 'https://www.basketball-reference.com/players/j/jordami01.html' uClient = uReq(MJ_url) MJ_html = uClient.read() uClient.close() MJ_soup = soup(MJ_html, "html.parser") MJ_containers = MJ_soup.findAll("table",{"class":"row_summable sortable stats_table"})
has title: When scraping data from basketball-reference how come certain tables are commented out?
accepted answer: http://stackoverflow.com/a/49766769
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: web-scraping
has answer: http://stackoverflow.com/a/49766769

http://stackoverflow.com/q/49877495
has title: Spacy similarity function
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54484501
linked to: http://stackoverflow.com/q/46348209
type: UnansweredQuestion
tagged with: similarity
downvote count: 0
upvote count: 1
tagged with: python
has body: I'm trying to use Spacy Library for sentences similarity, and I want to understand how it's work!? Their documentation is not clear: By default, spaCy uses an average-of-vectors algorithm, using pre-trained vectors if available (e.g. the en_core_web_lg model). If not, the doc.tensor attribute is used, which is produced by the tagger, parser and entity recognizer. This is how the en_core_web_sm model provides similarities. Usually the .tensor-based similarities will be more structural, while the word vector similarities will be more topical. You can also customize the .similarity() method, to provide your own similarity function, which can be trained using supervised techniques. I found this question :How does the .similiarity method works? that says it uses word embeddings, but in my implementation I don't have a "en_core_web_lg model" but I have the en_core_web_sm, so in this way how is the similarity computed by "tagger, parser and entity recognizer" ?
tagged with: spacy
score: 1

http://stackoverflow.com/q/49781878
accepted answer: http://stackoverflow.com/a/49798297
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86579577
tagged with: flask
has title: Python, Flask, ffmpeg video streaming: Video does not work in Firefox
type: AnsweredQuestion
upvote count: 1
score: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86610941
type: Question
has body: I am writing a preview portion for video management system, it works like a charm in chrome with standard tag but firefox does not recognize MIME type for some reason and it bugs me a lot. Here is my stream class: class Stream: run = False FNULL = open(os.devnull, 'w') overlay = ffmpeg.input("somelogo.png") def __init__(self, camid): camUtil = CameraUtil() self.camid = camid self.streamurl = camUtil.get_stream_from_id(self.camid)['streamURL'] print(self.streamurl) self.args = ffmpeg.input(self.streamurl) # vcodec="libvpx", # acodec="libvorbis", self.args = ffmpeg.output(self.args, "-", f="matroska", vcodec="copy", acodec="copy", blocksize="1024", # strftime="1", # segment_time="60", # segment_format="matroska" preset="ultrafast", metadata="title='test'" ) self.args = ffmpeg.get_args(self.args) print(self.args) self.pipe = subprocess.Popen(['ffmpeg'] + self.args, stdout=subprocess.PIPE,) #stderr=self.FNULL) def dep_stream(self): def gen(): try: f = self.pipe.stdout byte = f.read(1024) while byte: yield byte byte = f.read(1024) finally: self.pipe.kill() return Response(gen(), status=200, mimetype='video/webm', headers={'Access-Control-Allow-Origin': '*', "Content-Type": "video/webm", }) My html playback portion: &lt;video id="live_page_player" id="video" preload="auto" autoplay width="1280" height="720"&gt; &lt;source src="/stream/{{ camid }}" type='video/webm;codecs="vp8, vorbis"'/&gt; YOUR BROWSER DOES NOT SUPPORT HTML5, WHAT YEAR ARE YOU FROM?! &lt;/video&gt; Firefox says "No video with supported format and MIME type found" and in console it says error: Error Code: NS_ERROR_DOM_MEDIA_METADATA_ERR (0x806e0006) Did I do something dumb?! Or am I missing something, because it works google chrome like a charm I need fresh eyes. Help plez
tagged with: ffmpeg
has answer: http://stackoverflow.com/a/49798297

http://stackoverflow.com/q/49806945
answer count: 1
has title: Passing variables to parallelized function
accepted answer: http://stackoverflow.com/a/49807532
type: Question
has answer: http://stackoverflow.com/a/49807532
has comment: http://stackoverflow.com/comment/86628843
has comment: http://stackoverflow.com/comment/86628816
has body: I'm parallelizing the generation of a matrix where each element in the matrix is computed by a function fun. I can get it to work if the only thing I pass into this function are the indices i and j. However, I want to pass another variable into this function say x, how do I do this? I'm using Python 2.7 import numpy as np import multiprocess as mp import itertools p = mp.Pool() def fun((i,j)): print i,j prod = i * j # what if I want to have a variable x in this function # prod = i * j * x return prod combs = ((i,j) for i,j in itertools.product(xrange(5), repeat=2) if i &lt;= 5) result = p.map(fun, combs) p.close() p.join() newresult = np.array(result).reshape(5,5) print newresult
has comment: http://stackoverflow.com/comment/86628689
has comment: http://stackoverflow.com/comment/86628730
tagged with: python
tagged with: multiprocess
tagged with: parallel-processing
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/86629105
tagged with: matrix

http://stackoverflow.com/comment/86840189
score: 0
has text: As @Mihai Alexandru-Ionut rightly pointed out, this solution doesn't work with [[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9]],[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9],[[1,2,3],[4,5,6]],[[2,3,4],[3,4,5]],[[4,6,7],[5,7,9]]]]
type: Comment
comment on: http://stackoverflow.com/a/49901080
type: AnswerComment

http://stackoverflow.com/a/49763275
has comment: http://stackoverflow.com/comment/131795667
accepted answer of: http://stackoverflow.com/q/49763237
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49763237
type: Answer
has body: Use np.dstack to stack arrays by the third axis: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; R = np.arange(4).reshape(2,2) &gt;&gt;&gt; G = np.arange(4).reshape(2,2) &gt;&gt;&gt; B = np.arange(4).reshape(2,2) &gt;&gt;&gt; np.dstack([R,G,B]) array([[[0, 0, 0], [1, 1, 1]], [[2, 2, 2], [3, 3, 3]]]) &gt;&gt;&gt; np.dstack([R,G,B]).shape (2, 2, 3)
type: AcceptedAnswer

http://stackoverflow.com/a/49876768
has body: Note that the proper and official way to interact with Google Cloud Storage is to make use of the Google Cloud Client Library for Python and not running the gsutil command through subprocess.Popen. If you are not setting up merely some tests I would suggest you to follow from the beginning this way if there is not any technological constrain that makes this way impracticable. You can check at the following links the relative Overview and Documentation. A small example taken from the Documentation can be the following: from google.cloud import storage client = storage.Client() bucket = client.get_bucket('&lt;your-bucket-name&gt;') blob = bucket.blob('my-test-file.txt') blob.upload_from_string('this is test content!') You can find a further example here using google-cloud-python with the Datastore and Cloud Storage to manage expenses.
accepted answer of: http://stackoverflow.com/q/49866283
has comment: http://stackoverflow.com/comment/127267037
has comment: http://stackoverflow.com/comment/108618347
has comment: http://stackoverflow.com/comment/103828450
type: AcceptedAnswer
upvote count: 16
type: Answer
score: 13
answers question: http://stackoverflow.com/q/49866283
has comment: http://stackoverflow.com/comment/102150010
has comment: http://stackoverflow.com/comment/126568082
downvote count: 3
has comment: http://stackoverflow.com/comment/130899191

http://stackoverflow.com/q/49794144
score: 1
has comment: http://stackoverflow.com/comment/86602671
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: performance
has comment: http://stackoverflow.com/comment/86605764
tagged with: python
has comment: http://stackoverflow.com/comment/86603303
has comment: http://stackoverflow.com/comment/86605728
has title: How to improve speed of list comprehension with array size 9e3?
tagged with: list-comprehension
has body: I am multiplying an array Amp by another B**w where W is another array, and then summing the resultant array for each w. Amp and B have size (4867206,1) and W has size (40x10^3,1). This is currently taking 2min 49 seconds if W is size (1000,1). How can I improve this speed when using the complete W of size 40x10^3? Hw2=[np.einsum('i,i-&gt;', Amp, (np.array(B)**w)) for w in W]
accepted answer: http://stackoverflow.com/a/49795144
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86602713
tagged with: list
has answer: http://stackoverflow.com/a/49795144

http://stackoverflow.com/comment/86661078
type: Comment
has text: doesn't `jupyter` come as part of anaconda? The OP said he installed anaconda? why use `pip` :) ?
comment on: http://stackoverflow.com/a/49822731
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86866269
score: 0
comment on: http://stackoverflow.com/q/49907111
type: Comment
type: QuestionComment
has text: Thank you for the comments! Ok, I will start learning how to use properties properly then. Just starting to learn Python and I always feel when learning a new language that some basics change to more advance constructs, so property was a nice find.

http://stackoverflow.com/q/49914594
has comment: http://stackoverflow.com/comment/86844897
has title: I do not understand why i get this error: [...] got multiple values for argument [...]
has answer: http://stackoverflow.com/a/49914879
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86844824
has comment: http://stackoverflow.com/comment/86845083
has comment: http://stackoverflow.com/comment/86845155
accepted answer: http://stackoverflow.com/a/49914879
tagged with: genetic-algorithm
score: 0
answer count: 1
has body: I defined the following function: def lattice_pipe(real_coords, guess_cmap): guess_coords = laplacian_coords(guess_cmap) return fitness(real_coords, kabsch(real_coords,guess_coords)) And the i called it in this way: fit = list(map(functools.partial(lattice_pipe, real_coords = coords_real, guess_cmap = cmap_guess), population)) But I get the following error: fit = list(map(functools.partial(lattice_pipe, real_coords = coords_real, guess_cmap = cmap_guess), population)) TypeError: lattice_pipe() got multiple values for argument 'real_coords' I cannot understand why I am getting this because I think I am giving it only the two arguments it requires which are real_coords and guess_cmap... Thank you for your help!
type: Question
has comment: http://stackoverflow.com/comment/86845015
has comment: http://stackoverflow.com/comment/86845139

http://stackoverflow.com/comment/86730005
score: 0
type: Comment
type: AnswerComment
has text: I tried using this : f = NamedTemporaryFile(mode='wb+', dir=static_tmp_path,delete=False) and I printed f.name and it returned /app/static/tmp/tmptcip7smc. But no such file is really created in that dir.
comment on: http://stackoverflow.com/a/49841562

http://stackoverflow.com/q/49889200
has answer: http://stackoverflow.com/a/49889234
has comment: http://stackoverflow.com/comment/86794537
has body: Code is below, I am simply trying to subtract 2 dates, and figure out if the date difference meets a certain threshold. Can't seem to figure out how to get them in the right format for this. def activity_breakup(): now = datetime.date.today().strftime('%Y-%m-%d %H:%M:%S') print("now is equal to {}".format(now)) for activity in convert_csv_to_list()[1:]: date = datetime.datetime.strptime(activity[2], '%m/%d/%Y') print("date is equal to {}".format(date)) if now - date == 0: activities_in_next_7_days.append(activity) elif now - date &lt;= 7: activities_today.append(activity) else: continue Output of the prints are: now is equal to 2018-04-17 00:00:00 date is equal to 2018-04-22 00:00:00
tagged with: datetime
tagged with: python
tagged with: date
answer count: 3
accepted answer: http://stackoverflow.com/a/49889241
has answer: http://stackoverflow.com/a/49889245
type: Question
has title: Can't seem to subtract dates in Python: TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime'
possible better answer: http://stackoverflow.com/a/49889234
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49889241

http://stackoverflow.com/a/49803099
upvote count: 2
has comment: http://stackoverflow.com/comment/86628190
has comment: http://stackoverflow.com/comment/86621077
has body: Your projection on the call barbs gives the transform argument as LambertConformal(), but it looks like you're passing in latitude and longitude values for position. Change transform to PlateCarree(), as you use in the other plot methods.
accepted answer of: http://stackoverflow.com/q/49786173
has comment: http://stackoverflow.com/comment/86628832
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49786173
has comment: http://stackoverflow.com/comment/86627296
score: 2
has comment: http://stackoverflow.com/comment/86629942
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86632448
has comment: http://stackoverflow.com/comment/116394665

http://stackoverflow.com/q/49830413
has body: I'm trying to install Open Cv on the raspberry pi. I'm following this tutorial https://www.pyimagesearch.com/2017/09/04/raspbian-stretch-install-opencv-3-python-on-your-raspberry-pi/ I ended up getting an error in the middle, I successfully installed virtualenv and virtualenvwrapper I can see that but when I type the command of profile I get an error saying usr/bin/python: No module named virtualenvwrapper virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is set properly. pi@raspberrypi:~ $ sudo pip install virtualenv virtualenvwrapper Requirement already satisfied: virtualenv in /usr/local/lib/python3.5/dist-packages Requirement already satisfied: virtualenvwrapper in /usr/local/lib/python3.5/dist-packages Requirement already satisfied: stevedore in /usr/local/lib/python3.5/dist-packages (from virtualenvwrapper) Requirement already satisfied: virtualenv-clone in /usr/local/lib/python3.5/dist-packages (from virtualenvwrapper) Requirement already satisfied: pbr!=2.1.0,&gt;=2.0.0 in /usr/local/lib/python3.5/dist-packages (from stevedore-&gt;virtualenvwrapper) Requirement already satisfied: six&gt;=1.10.0 in /usr/lib/python3/dist-packages (from stevedore-&gt;virtualenvwrapper) pi@raspberrypi:~ $ VIRTUALENVWRAPPER_PYTHON bash: VIRTUALENVWRAPPER_PYTHON: command not found pi@raspberrypi:~ $ echo $VIRTUALENVWRAPPER_PYTHON pi@raspberrypi:~ $ echo $VIRTUALENVWRAPPER_PYTHON pi@raspberrypi:~ $ echo $VIRTUALENV_PYTHON pi@raspberrypi:~ $ echo $VIRTUALENV_PYTHON3 pi@raspberrypi:~ $ sudo pip install virtualenv virtualenvwrapper Requirement already satisfied: virtualenv in /usr/local/lib/python3.5/dist-packages Requirement already satisfied: virtualenvwrapper in /usr/local/lib/python3.5/dist-packages Requirement already satisfied: stevedore in /usr/local/lib/python3.5/dist-packages (…
tagged with: raspberry-pi
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50079649
upvote count: 2
score: 2
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has title: Why am I getting errors while downloading virtualenv on Raspberry Pi 3?
tagged with: python-3.x

http://stackoverflow.com/q/49805900
tagged with: pandas
has body: I have a datetime column and I am trying to find entries with a specific weekday name and month based on user input. The user input is a String and can be Sunday, Monday,...Saturday and Month, January, February,...June. Unnamed: 0 Start Time End Time Trip Duration Start Station End Station User Type 0 1621326 2017-06-21 08:36:34 2017-06-21 08:44:43 489.066 14th &amp; Belmont St NW 15th &amp; K St NW Subscriber 1 482740 2017-03-11 10:40:00 2017-03-11 10:46:00 402.549 Yuma St &amp; Tenley Circle NW Connecticut Ave &amp; Yuma St NW Subscriber 2 1330037 2017-05-30 01:02:59 2017-05-30 01:13:37 637.251 17th St &amp; Massachusetts Ave NW 5th &amp; K St NW Subscriber To get the month name based on previous user input(user_month): df[df['Start Time'].dt.month == dt.datetime.strptime(user_month, '%B').month] To get the weekday name based on previous user input(user_day): df[df['Start Time'].dt.weekday_name == user_day] Each one handles a user case were selection is either month name or weekday name, I am struggling with a solution to cover a case were both month name(string) and week day name(string) are derived based on both choices.
has comment: http://stackoverflow.com/comment/86626595
accepted answer: http://stackoverflow.com/a/49806300
has answer: http://stackoverflow.com/a/49806300
has comment: http://stackoverflow.com/comment/86626731
type: Question
possible better answer: http://stackoverflow.com/a/49806290
has title: Pandas: how to filter on a datetime column using two conditions
has answer: http://stackoverflow.com/a/49806290
has comment: http://stackoverflow.com/comment/86626693
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/comment/86683083
type: Comment
score: 1
type: QuestionComment
has text: I haven't found a legitimate way of dealing with this issue, however I have found a way to get around for my needs. I'm going to cast all my ints, and since for my application I only need N, S, W, and E I'm doing a set of 'if' statements and then declaring the chars that way. Not the most ideal, but it certainly works!
comment on: http://stackoverflow.com/q/49832898

http://stackoverflow.com/comment/86722579
type: QuestionComment
has text: Perhaps you can provide some information about what actually happens in your code verses what you expect to happen. "It doesn't work" isn't enough
comment on: http://stackoverflow.com/q/49845752
score: 0
type: Comment

stream
tags question: http://stackoverflow.com/q/49759309
tags question: http://stackoverflow.com/q/49859876
tags question: http://stackoverflow.com/q/49825421
type: Tag
tag name: stream
tags question: http://stackoverflow.com/q/49865741

http://stackoverflow.com/q/49779340
accepted answer: http://stackoverflow.com/a/49779548
has title: Mutliprocessing in Python in a for loop and passing multiple Arguments
tagged with: python-multiprocessing
type: AnsweredQuestion
tagged with: multithreading
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I'm doing a lot of calculations with a python script. As it is CPU-bound my usual approach with the threading module didn't yield any performance improvements. I was now trying to use Multiprocessing instead of Multithreading to better use my CPU and speed up the lengthy calculations. I found some example codes here on stackoverflow, but I don't get the script to accept more than one argument. Could somebody help me out with this? I've never used these modules before an I'm pretty sure I'm using Pool.map wrong. - Any help is appreciated. Other ways to accomplish Multiprocessing are also welcome. from multiprocessing import Pool def calculation(foo, bar, foobar, baz): # Do a lot of calculations based on the variables # Later the result is written to a file. result = foo * bar * foobar * baz print(result) if __name__ == '__main__': for foo in range(3): for bar in range(5): for baz in range(4): for foobar in range(10): Pool.map(calculation, foo, bar, foobar, baz) Pool.close() Pool.join()
upvote count: 5
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/49779548

http://stackoverflow.com/comment/86796321
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49889323
has text: `parser.parse_args()` parses `sys.argv[1:]` and uses `sys.argv[0]` as the `prog` attribute in `usage`.
type: Comment

http://stackoverflow.com/a/49801850
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49801773
score: 3
has comment: http://stackoverflow.com/comment/86637762
type: Answer
has body: your solution is okay, but if you want to have a counting side effect, use itertools.count object: import itertools def f(x): print(x) c = itertools.count() f(next(c)) f(next(c)) or the variant, performing the next call in the functions themselves (itertools.counter is mutable so you can modify it inside the function): import itertools def f(c): x = next(c) print(x) c = itertools.count() f(c) f(c) you can initialize it to a non-zero value: c = itertools.count(3)

http://stackoverflow.com/comment/86657849
type: Comment
type: QuestionComment
score: 0
has text: If you *must* use a regex, why do you need the regex to cover the whole string and not just `re.search(">(.+) in \d", Text).group(1)`
comment on: http://stackoverflow.com/q/49820904

http://stackoverflow.com/comment/86706104
comment on: http://stackoverflow.com/a/49844754
type: AnswerComment
has text: But this way I will need to send request explicit on image or am I wrong ?. I have already secured endpoint with token but I want to create multiple urls because i fetch like 5O items and each item has image.
score: 0
type: Comment

http://stackoverflow.com/q/49876793
type: Question
accepted answer: http://stackoverflow.com/a/49877277
has comment: http://stackoverflow.com/comment/86769245
has answer: http://stackoverflow.com/a/64629429
tagged with: python
possible better answer: http://stackoverflow.com/a/62230885
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49877277
downvote count: 2
answer count: 3
upvote count: 1
has body: Please i have been finding it a little difficult to draw a grid like this.. i need some help to have a specific functon that can draw me any given grid of numbers given def grid(f, l): print("{:10}".format("---+---" * f)) print("|{:12}|".format(" " * l)) print("|{:12}|".format(" " * l)) print("|{:12}|".format(" " * l)) print("{:10}".format("---+---" * f))
score: -1
has answer: http://stackoverflow.com/a/62230885
has title: Python Draw grid Function
favorite count: 0

http://stackoverflow.com/a/66727603
answers question: http://stackoverflow.com/q/49848517
score: 0
has body: I tried all of the above with no success. I switched from Python 3.8 to Python 3 and that worked.
type: Answer

http://stackoverflow.com/comment/86924376
has text: It works with steam ... You Rock!
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49855940

http://stackoverflow.com/a/49909766
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49909507
upvote count: 1
has body: From The python documentation for Set: A set is an unordered collection with no duplicate elements. When you save each line into a set the order in which the items are retrieved is not guaranteed to be the same as when they went in. A better choice might be to use a List and in fact, the splitlines() function already returns a list. You should be able to fix your code by simply removing set(...) from line 2. with open("C:/Temp/1_attlog.dat", "r") as f1, open("C:/Temp/attlog.dat","r") as f2, open("C:/Temp/attlog_new.dat", "w") as n: f_a = f1.read().splitlines() # No more set f_b = set(f2.read().splitlines()) for line in f_a: count_line += 1 if line not in f_b: print(line) count_new_lines += 1 n.writelines(line)
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49909507
type: AcceptedAnswer

http://stackoverflow.com/q/49914355
type: Question
tagged with: python-3.x
answer count: 2
has body: I have a nested list of numbers. Like this one: [[1,2,3],[3,2,1],[3,1,2],[2,3,1]] Now, I want to count the number(s) that is bigger than it's previous element and it's front element, it must also has to have an element on both of it's sides. The output should be like this(inside a list): [0,0,0,1] The first element of the output list is zero because in the first nested list, it's first element has no other previous element but only 2 in it's front. For the second element(still on the first nested list) it has 1 as it's previous element and 3 as it's front one but the output is zero because it's needs to be greater than both the element in it's front and it's previous one. The third element is is also not valid because it doesn't have a front element, only it's previous one. The same is for the other nested lists except for the last one. In the last nested list 2 and 1 is already not valid, but 3 is, so now we need to check whether if this is higher than it's two elements. Since three is higher, we count +1 for the last nested list. Another example: [[1,2,1,3,1],[2,2,2],[2,3,4,3,4,2,3,1]] The output should be: [2,0,3] The first element of the output list is 2 because in the first nested list(the first and last element is already invalid), 2 has both elements and it is also higher than the both. Then, we move on to 1, it also has both elements but it is smaller than the both so it's invalid. 3 is valid because it has both elements and it is also higher. So we count +2 since there are 2 numbers that valid. The second nested list is invalid because the number that has both elements cannot be equal to any of them, it needs to be higher, and the first and last element is already invalid.In the last nested list, the first and last element of it is already invalid, so we start from it's second one, 3, 3 has both elements but it is only higher than it's previous one but is smaller than it's front one. Next, 4 has both elements and it is also higher so it is counted. Next, 3 …
has comment: http://stackoverflow.com/comment/86844494
has comment: http://stackoverflow.com/comment/86844334
has comment: http://stackoverflow.com/comment/86844659
possible better answer: http://stackoverflow.com/a/49914636
tagged with: python
has comment: http://stackoverflow.com/comment/86844550
score: 2
type: AnsweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/6822725
has comment: http://stackoverflow.com/comment/86844380
has answer: http://stackoverflow.com/a/49914565
accepted answer: http://stackoverflow.com/a/49914565
has title: How to count the number of local maxima in a nested list?
downvote count: 1
has answer: http://stackoverflow.com/a/49914636
favorite count: 0

http://stackoverflow.com/a/49911712
has comment: http://stackoverflow.com/comment/86839258
answers question: http://stackoverflow.com/q/49911587
type: Answer
downvote count: 1
has body: That is because there are two different scopes. One is Class and one is function. When you define a function in a class, that function is defined in Class scope. You can build a minimal example: class A: a = 1 b = a + 1 pass You can see that when defining b, we can directly access variable a as they are in the same scope A Class. But when you use a Class scope variable in a function, that is another scope function. So in this case you need to manually specify scope. Actually, this behave varies from language to language.
has comment: http://stackoverflow.com/comment/86839372
score: 0
upvote count: 1

http://stackoverflow.com/a/49899530
type: Answer
answers question: http://stackoverflow.com/q/49898985
has comment: http://stackoverflow.com/comment/86814459
has body: Basically, your task seems to be: get url status code collect responses for all of the calculate percentages For first step you use: def get_code(url): return requests.head(url).status_code For second step you apply this fucntion to dataframe column, see https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html resp_df = df[column].apply(get_code, axis=1) For third step you can use opertions over column to calculate percentages: resp_df[resp_df == 404].sum() / len (resp_df) (note code not run)
score: 0

http://stackoverflow.com/comment/86560742
type: AnswerComment
comment on: http://stackoverflow.com/a/49772948
score: 0
type: Comment
has text: I had tried this, receiving the following error: 'TypeError: the JSON object must be str, bytes or bytearray, not 'Response''. On the other hand if I use the .text version: json.loads(response.text), I get a different error: json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 113)

http://stackoverflow.com/comment/86777991
comment on: http://stackoverflow.com/q/49880980
has text: https://www.gnu.org/prep/standards/html_node/Names.html#Names
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49916472
has answer: http://stackoverflow.com/a/49917099
accepted answer: http://stackoverflow.com/a/49917099
has comment: http://stackoverflow.com/comment/86849011
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86848412
has body: I would like to know the correct naming convention for the following variables in Python which I couldn't find one from Google Style Guide and PEP8 (Let's say I have the following Python code) output_file = open(output_file_path, 'w') What would be the best variable name for the out file name? I believe the possible options for the variable name would be something like output_file outputfile outfile out_file outfile And the path variable can be something like output_file_path output_filepath output_path out_path ...
tagged with: naming-conventions
has comment: http://stackoverflow.com/comment/86848375
score: 7
tagged with: python
has title: Python: variable naming convention - file, path, filepath, file_path
type: Question
upvote count: 9
tagged with: coding-style
has answer: http://stackoverflow.com/a/72509726
possible better answer: http://stackoverflow.com/a/72509726
answer count: 2
downvote count: 2

http://stackoverflow.com/comment/86708622
has text: In order to be immediately helpful to readers (and avoid [Linkrot](https://en.wikipedia.org/wiki/Link_rot)), we prefer answer that provide at least a solid summary of the solution directly, with links used to offer additional information. [More info on link only answers](https://meta.stackoverflow.com/tags/link-only-answers/info).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49846745
type: Comment

http://stackoverflow.com/comment/86742332
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49863492
has text: include the output of `ulimit -a`
score: 1

http://stackoverflow.com/comment/86603466
score: 0
type: QuestionComment
has text: I don't understand why you would need to remove the unicode encode, Can you just use json.dump(dictionary_obj, file_obj)
type: Comment
comment on: http://stackoverflow.com/q/49794587

http://stackoverflow.com/q/49862153
has title: Initializing a matrix with alternating 0s and 1s in TensorFlow
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49862579
tagged with: numpy
type: AnsweredQuestion
score: 0
has body: I am trying to create an n-by-m matrix of 0s and 1s with a very simple structure: [[1 0 0 0 0 0 0 ...], [1 1 0 0 0 0 0 ...], [1 1 1 0 0 0 0 ...], [1 1 1 1 0 0 0 ...], [0 1 1 1 1 0 0 ...], [0 1 1 1 1 1 0 ...], ... [... 0 0 0 1 1 1 1], [... 0 0 0 0 1 1 1], [... 0 0 0 0 0 1 1], [... 0 0 0 0 0 0 1]] However, I don't want to start writing loops as this is probably achievable using something built in: A = tf.constant(???,shape(n,m)) Note that after the first 3 rows there is simply a repetition of four 1s, followed by m-3 0s, until the last 3 rows. So I am thinking something along the lines of a repeat of repeat, but I have no idea what syntax to use.
accepted answer: http://stackoverflow.com/a/49862579
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/86616119
has text: @mrzasa yes you're totally right I edited my answer
type: Comment
comment on: http://stackoverflow.com/a/49800185
type: AnswerComment
score: 1

pyopenssl
tag name: pyopenssl
tags question: http://stackoverflow.com/q/49787069
type: Tag

http://stackoverflow.com/comment/86796353
has text: short answer: use arbitrary precision math
type: QuestionComment
comment on: http://stackoverflow.com/q/49888741
score: 0
type: Comment

http://stackoverflow.com/a/49803200
answers question: http://stackoverflow.com/q/49802955
score: 1
type: Answer
has body: i assume when you compare with na it always be 1 df['Status'] = (df.A &lt; df.RM.fillna(df.A.max()+1).shift(1)).astype(int) A RM Status 0 384 NaN 0 1 376 380.0 1 2 399 387.5 0 3 333 366.0 1 4 393 363.0 0 5 323 358.0 1 6 510 416.5 0 7 426 468.0 0 8 352 389.0 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/86561546
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49762136
has text: Probably [xarray](https://xarray.pydata.org/en/stable/) is more suitable?

http://stackoverflow.com/a/49801229
answers question: http://stackoverflow.com/q/49760712
has body: Well, thanks to ImportanceOfBeingErnst for pointing out that I was vastly over-complicating things... It turns out that I really only need the ax.plot(x,y) function rather than the ax.plot_date(mdatetime, y) function. Plot can actually plot varied lengths of data as long as each individual trace has the same number of x and y values. Since the data is all given in seconds I can easily plot using 0 as my "reference time". For anyone else struggling with plotting duration rather than exact times, you can simply manipulate the "time" (x) data by using python's map() function, or better yet a list comprehension to "time shift" the data or convert to a single unit of time (e.g. simply turn minutes into seconds by dividing by 60). "Time Shifting" might look like: # build some sample 25 Hz time data time = range(0,1000,1) time = [x*.04 for x in time] # "time shift it by 5 seconds, since this data is recorded 5 seconds after the other signal time = [x+5 for x in time] Here is my plotting code for any other matplotlib beginners like me :) (this will not run, since I have not converted my variables to generic data... but nevertheless it is a simple example of using matplotlib.) fig,ax = plt.subplots() ax.grid() ax.set_title(plotTitle) ax.set_xlabel("time (s)") ax.set_ylabel("value") # begin looping over the different sets of data. tup = 0 while (tup &lt; len(alldata)): outTime = alldata[tup][1].get("time") # each signal is time shifted 5 seconds later. # in addition each signal has different sampling frequency, # so len(outTime) is different for almost every signal. outTime = [x +(5*tup) for x in outTime] for key in alldata[tup][1]: if(key not in channelSelection): ## if we dont want to plot that data then skip it. continue else: data = alldata[tup][1].get(key) ## using list comprehension to scale y values. data = [100*x for x in data] ax.plot(outTime,data,linestyle='solid', linewidth='1', marker='') tup+=1 plt.show()
type: Answer
score: 0

http://stackoverflow.com/comment/86647123
type: AnswerComment
comment on: http://stackoverflow.com/a/49815210
score: 0
type: Comment
has text: Good to know I'm not asking a dumb question with an obvious answer then. :) The "elegant" part was more to do with how this connection is represented in the json file I wanted to export. I wanted to use JSON just because it's standard, ascii based (and therefore more secure than pickle) and doesn't require any external modules.

http://stackoverflow.com/comment/86646451
score: 3
has text: @Aritesh: You're generating a *uniformly distributed* integer between 1 and 11 (inclusive). The sum of two dice is *not* uniformly distributed, so you can't use `randint(1, 12)` to model it.
type: Comment
comment on: http://stackoverflow.com/a/49812118
type: AnswerComment

http://stackoverflow.com/comment/86673640
comment on: http://stackoverflow.com/q/49828991
type: QuestionComment
type: Comment
has text: @RannLifshitz Thank you, I'll try to do that.
score: 0

http://stackoverflow.com/q/49910547
has title: Replace elements of a list by elements of other list
type: Question
has answer: http://stackoverflow.com/a/49910910
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: python-2.7
score: 0
tagged with: list
has body: Consider the following Python list of lists: my_list = [[0], [1], [2], [3], [4], [5], [6, 2], [7, 6, 4, 3], [8, 6, 3], [9], [10, 4, 3], [11], [12, 9], [13, 11, 12]] Every element of my_list is a list starting with its index in my_list and the other values are less than the first one, and so also appears as 1st element of some previous list. For example, my_list[8] is [8, 6, 3] (and everybody knows that 6,3 &lt; 8). I'd like to do the following replacement when is possible: if s in my_list contains an element s_i such that some previous element r in my_list is as [s_i, a, b, c] (or longer), replace s_i in s by s_i, a, b, c (or more). For example, instead of [13, 11, 12] (could be done for other elements too) in my_list I'd like to get [13, 11, 12, 9] since [12, 9] is in my_list also. But, notice that this procedure should be done recursively, if necessary. For example, suppose that [9, 4] is in my_list, then the result should be [13, 11, 12, 9, 4]. Or, since [6, 2] is in my_list, such replacement should be done also for [7, 6, 4, 3] and [8, 6, 3]. Sorry, if is not clear what I need. I think that defining some function and call it in while could be a profit.

http://stackoverflow.com/comment/86819362
type: QuestionComment
comment on: http://stackoverflow.com/q/49901047
type: Comment
has text: Python is a great glue language, but you need something faster for pixel loops. People usually use C/C++ for performance, but of course that's rather painful to develop in if you're used to Python. I've seen javascript used for this kind of thing: it's surprisingly fast, and if you're careful, not as awful as everyone says. For example, here's a JPEG decoder in pure javascript https://github.com/eugeneware/jpeg-js/blob/master/lib/decoder.js
score: 0

http://stackoverflow.com/comment/86881716
comment on: http://stackoverflow.com/q/49890135
type: QuestionComment
has text: @Koustav (1) I want to stick an "Input" layer at the beginning of the decoder network. IE, right before the second Conv2D(32, ...). This way I can treat this as a independent network and send inputs (autoencoder encodings) down to generate images (2) You're right about how each new layer looks like it would have half as many channels as the previous. For now, yes, I would like the new layers to have 4 channels. My question wasn't really about the # of channels, it's really about using a new layer as an input to a previously defined layer. Thank you!
type: Comment
score: 0

http://stackoverflow.com/comment/86708047
has text: Yes, now it works. I was sure that I tried something like that. Now it works. Thanks a lot for your clarifications.
type: AnswerComment
comment on: http://stackoverflow.com/a/49836453
type: Comment
score: 0

http://stackoverflow.com/q/49902653
has comment: http://stackoverflow.com/comment/86859818
tagged with: hyperledger
answer count: 0
downvote count: 0
has title: Communicate with Hyperledger Fabric orderer
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: hyperledger-fabric
has comment: http://stackoverflow.com/comment/86858493
type: UnansweredQuestion
tagged with: python
has body: I set up Hyperledger Fabric net using devmode (https://github.com/hyperledger/fabric-samples/tree/release-1.1/chaincode-docker-devmode) and started chaincode. I need a way to communicate with the network (create/join channels, invoke chaincode). I tried to use python-SDK (https://github.com/hyperledger/fabric-sdk-py/blob/master/docs/tutorial.md). A network.json configuration file is needed to initialize a client instance, but the file is not provided in fabric-samples, so I attempted to create my own. It doesn't work. The code: from hfc.fabric import Client cli = Client(net_profile="network.json") print(cli.organizations) # orgs in the network org1_admin = cli.get_user('org1.example.com', 'Admin') response = cli.channel_create( 'orderer', 'myc', org1_admin, 'myc.tx') The orderer outputs: http2Server.HandleStreams received bogus greeting from client I tried to use different certificates and name for orederer, but it didn't help. The network.json: { "name": "sample-network", "description": "Sample network contains 4 peers (2 orgs), 1 orderer and 2 cas for Python SDK testing", "version": "0.1", "client": { "organization": "Org1", "credentialStore": { "path": "/tmp/hfc-kvs", "cryptoStore": { "path": "/tmp/hfc-cvs" }, "wallet": "wallet-name" } }, "organizations": { "orderer.example.com": { "mspid": "OrdererMSP", "orderers": [ "orderer" ], "certificateAuthorities": [ ] }, "org1.example.com": { "mspid": "Org1MSP", "peers": [ "peer0.org1.example.com" ], "certificateAuthorities": [ "ca-org1" ], "users": { "Admin": { "cert": "msp/admincerts/admincert.pem", "private_key": "msp/keystore/key.pem" } } } }, "orderers": { "orderer": { "url": "localhost:7050", "grpcOptions": { "ssl-target-name-override": "orderer", "grpc-max-send-message-length": 15 }, "tlsCACerts": { "path": "msp/cacerts/cacert.pem" } } }, "peers": { "peer0.org1.example.com": { "url": "localhost:7051", "eventUrl": "localhost:7053", "grpcOptions": { "ssl-target-name-override": "peer0.org1.example.com", "grpc.http2.k…

http://stackoverflow.com/q/49791853
downvote count: 0
has comment: http://stackoverflow.com/comment/86598391
upvote count: 1
score: 1
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has title: logits and labels must have the same first dimension CNN
has comment: http://stackoverflow.com/comment/86598666
type: UnansweredQuestion
has body: I'm training a simple CNN model, here's the structure image's size is 64X64 1st layer: convolution 5X5X8 average pooling 5X5 strides 2 2nd layer: convolution 5X5X8 average pooling 5X5 strides 2 3rd layer: convolution 1X1X32 average pooling global pooling 4th layer: fully connected layer 32inputs 2outputs when I use sparse_softmax_cross_entropy to calculate the loss, it raise an Error like this: I thought the shape of Tensor output by 4th layer should be (?, 2) and it is, but I dont understand why the shape of logits is [1280, 2] def stg_model_fn(features, labels, mode): # Input Layer x = tf.reshape(features, [-1, 64, 64, 1]) # print(x) x = layer_module.conv_group( inputs = x, activation = "tanh", filters = 8, kernel_size = [5, 5], pool_size = 5, strides = 2, abs_layer = True, pool_padding = "same") print(x) x = layer_module.conv_group( inputs = x, filters = 16, activation = "tanh", kernel_size = [5, 5], pool_size = 5, strides = 2, abs_layer = False, pool_padding = "same") print(x) x = layer_module.conv_group( inputs = x, filters = 32, activation = "relu", kernel_size = [1, 1], pool_size = 16, strides = 1, abs_layer = False, pool_padding = "valid") print(x) x = tf.reshape(x, [-1, 32]) x = tf.layers.dense(inputs = x, units = 2) predictions = { # Generate predictions (for PREDICT and EVAL mode) "classes": tf.argmax(input=x, axis=1), # Add `softmax_tensor` to the graph. It is used for PREDICT and by the # `logging_hook`. "probabilities": tf.nn.softmax(x, name="softmax_tensor") } if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) # Calculate Loss (for both TRAIN and EVAL modes) loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels = labels, logits = x) if mode == tf.estimator.ModeKeys.TRAIN: optimizer = tf.train.GradientDescentOptimizer(learning_rate=FLAGS.learning_rate) train_op = optimizer.minimize( loss=loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec(mode=mode, loss=los…
has answer: http://stackoverflow.com/a/49792980
tagged with: python
has comment: http://stackoverflow.com/comment/86599897
has comment: http://stackoverflow.com/comment/86598582

http://stackoverflow.com/comment/86633099
type: Comment
comment on: http://stackoverflow.com/q/49809138
score: 0
type: QuestionComment
has text: There are no folders in an S3 bucket, just a big flat list of objects. You can put slashes in the names of those objects, but that doesn't create folders. S3 _does_ have `prefix` and `delimiter` arguments for convenience, that let you sort of fake having folders, but that only goes so far—you can't "walk the tree" hierarchically, because there is no tree, just a flat list.

http://stackoverflow.com/comment/86830805
type: Comment
score: 0
type: AnswerComment
has text: got it. Thanks again! Everything is a learning experience. Small steps
comment on: http://stackoverflow.com/a/49907081

http://stackoverflow.com/comment/86838130
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49816225
has text: It's working now. I simply builded a raw_input_receiver_fn instead of a parsing one. I'm just having a problem with the shapes but that is unrelated to the problem now. Thank you so much for your help :bd
score: 0

http://stackoverflow.com/a/49776368
has body: I highly recommend you to use the numpy package for doing such statistical analysis. You then simply start out by using numpy.histogram to bin your data, and proceed from there to extract other statistics. Of course, for more advanced use-cases, it might be desirable to use something like scipy or pandas, but numpy is likely to serve your needs for most things and is these days a rather standard module.
type: Answer
answers question: http://stackoverflow.com/q/49776192
score: 0

http://stackoverflow.com/a/49780950
upvote count: 1
has comment: http://stackoverflow.com/comment/86616301
has comment: http://stackoverflow.com/comment/86618023
has comment: http://stackoverflow.com/comment/86636683
answers question: http://stackoverflow.com/q/49778278
has comment: http://stackoverflow.com/comment/86595190
type: Answer
has comment: http://stackoverflow.com/comment/86596424
has comment: http://stackoverflow.com/comment/86612352
score: 1
has body: Selecting the records can be done by: target_records = [rec for rec in table if start &lt;= rec.dist &lt;= end] Once you have the records, it's fairly easy to copy them into a new dbf: new_table = old_table.new('some_file.dbf') with new_table: for record in target_records: new_table.append(record)
downvote count: 0

http://stackoverflow.com/a/49850786
type: Answer
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49833921
has comment: http://stackoverflow.com/comment/86791509
score: 5
has body: If you using SQLAlchemy the best way is the events. So you can do something like this: class Post(db.Model): id = db.Column('id', db.Integer, primary_key=True) title = db.Column(db.String) text = db.Column(db.String) @db.event.listens_for(Post, "after_insert") def send_notification(mapper, connection, target): push_firebase_notification() Read more details about events of SQLAlchemy here http://docs.sqlalchemy.org/en/latest/orm/events.html#orm-events A different way is to use your signals in your models as Beq mentioned. from blinker import Namespace awesome_signals = Namespace() model_saved = awesome_signals.signal('model-saved') class Post(object): ... def save(self): model_saved.send(self)
answers question: http://stackoverflow.com/q/49833921
upvote count: 5

http://stackoverflow.com/comment/86686756
comment on: http://stackoverflow.com/q/49835798
has text: It doesn't work that way at all. The entire template, including the included template, is rendered by the `home` view. `contact_view` has nothing to do with anything here and is not called.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49868402
has title: How to format python interpreter text?
type: Question
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49868454
has comment: http://stackoverflow.com/comment/86752363
has comment: http://stackoverflow.com/comment/86752322
score: 1
has body: I am trying to edit the text that pops up when I launch the python3 interpret. This should be a very simple task and I am trying to use the PYTHONSTARTUP environment variable set to a file .pythonrc.py but I am not 100% sure what I am doing. For some reason I cannot find a simple script that shows how this is done. I do not have my own generated code because I didn't even write the code for my terminal customization. I just googled how to edit, found some examples and then tweeked it from there. I just want to know how to change this. Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 03:03:55) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information.

http://stackoverflow.com/a/49785060
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49784195
has body: This should give you the basic idea, which is compute the minimum and maximum x and y values of each box and store them in BOXES. This makes it very easy to determine if the given x and y coordinates passed to the mouse() callback function are within any of them. With the multiple boxes in your real code, make sure to apply the new minmax() function to the corners of each one of them. import turtle """ This will be based off 1 box instead of all 9""" pen = turtle.Turtle() corners = [] BOXES = {} for line in range(0, 4): pen.forward(50) pen.left(90) corners.append(pen.pos()) def minmax(points): """ Find extreme x and y values in a list of 2-D coordinates. """ minx, miny, maxx, maxy = points[0][0], points[0][1], points[0][0], points[0][1] for x, y in points[1:]: if x &lt; minx: minx = x if y &lt; minx: miny = y if x &gt; maxx: maxx = x if y &gt; maxy: maxy = y return minx, miny, maxx, maxy BOXES['MIDDLEBOX'] = minmax(corners) for i in BOXES: print(i, BOXES[i]) """ POINTS FROM LEFT TO RIGHT (1) - TOP LEFT CORNER (2) - BOTTOM LEFT CORNER (3) - BOTTOM RIGHT CORNER (4) - TOP RIGHT CORNER """ def mouse(x, y): """ Return key of box if x, y are within global BOXES or None if it's not. """ for key in BOXES: minx, miny, maxx, maxy = BOXES[key] if (minx &lt;= x &lt;= maxx) and (miny &lt;= y &lt;= maxy): print(key) return key print('None') return None # Not found. turtle.onscreenclick(mouse) turtle.mainloop()

http://stackoverflow.com/q/49909381
upvote count: 1
tagged with: python
tagged with: python-requests
tagged with: password-protection
accepted answer: http://stackoverflow.com/a/55144861
type: AnsweredQuestion
tagged with: security
answer count: 2
has comment: http://stackoverflow.com/comment/86834760
has answer: http://stackoverflow.com/a/55144861
score: 1
has answer: http://stackoverflow.com/a/49909463
tagged with: windows-authentication
favorite count: 0
has title: Using username and password safely in Python code
type: Question
has body: I'm using the Python requests library to make a call to an API that requires Windows Authentication. In C# I have always used the Directory Services, which has allowed me to avoid putting passwords in any of my code or configurations. From what I have found online, it seems that my only option in Python is to have a password somewhere. I have a service account that I will use, but I need to store the password securely. What is the best way to securely store and retrieve a service account password in Python without hard coding plain text? The code that I am currently using is below. I have the username and password stored in plain text in my configuration: auth = HttpNtlmAuth( config.ServiceAccount["Username"], config.ServiceAccount["Password"] ) content = requests.post(call_string, json=parameters, auth=auth) Edit: I should mention that this will not be a user-facing application. It will run as a batch job. So there will not be any way for a user to enter the username/password while running the application.
has comment: http://stackoverflow.com/comment/86834867
possible better answer: http://stackoverflow.com/a/49909463
downvote count: 0
linked to: http://stackoverflow.com/q/7014953

http://stackoverflow.com/comment/86776339
type: QuestionComment
comment on: http://stackoverflow.com/q/49865386
has text: I will check theese hints, thank you. But I discovered I am still using too much data. A image numpy array is too big, I must have a selection of it's data first
score: 0
type: Comment

http://stackoverflow.com/a/69408314
has body: for your information, a trick works. You can change the uri after generating the request : request = service.projects().databases().documents().runQuery( parent='projects/myprojectid/databases/(default)/documents/*/**', body=query) request.uri = request.uri.replace('/*/**', '') response = request.execute()
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49899100

http://stackoverflow.com/comment/126815707
type: QuestionComment
has text: What is that 'account-list' view doing in post? I have run into this issue and it is when the view resolves while a separate task is being handled asynchronously. When the post method of the view returns the response, it closes the db connection. I always close the connection before kicking off asynchronous tasks that require it.
score: 0
comment on: http://stackoverflow.com/q/49820088
type: Comment

http://stackoverflow.com/a/49820383
type: AcceptedAnswer
downvote count: 0
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/49820185
type: Answer
accepted answer of: http://stackoverflow.com/q/49820185
has body: Easiest way to capture something that does not entail some other things is with [^ ....] - the ^ disallowes anything inside the [] - as a special feature you do not need to escape brackets inside it - so by declaring your regex as r'(\([^()]+\))' you essentially capture a literal ( followed bei 1+ anythings but neither ( nor ) followed by a literal ). See https://regexr.com/3nsfg From Regex Syntax: Characters that are not within a range can be matched by complementing the set. If the first character of the set is ^, all the characters that are not in the set will be matched. For example, [^5] will match any character except '5', and [^^] will match any character except '^'. ^ has no special meaning if it’s not the first character in the set. To match a literal ']' inside a set, precede it with a backslash, or place it at the beginning of the set. For example, both [()[\]{}] and []()[{}] will both match a parenthesis. Code: t = "x(x+3(x+3))" import re m = re.findall(r"(\([^()]+\))", t) print(m[0]) Output: (x+3)

http://stackoverflow.com/a/49770912
accepted answer of: http://stackoverflow.com/q/49770819
score: 2
has body: Those are definitely not functionally equivalent. The first piece of code puts the result of the last called method into result, so whatever remove returns. remove always returns None since it returns nothing. The second piece of code puts the list into result, then removes from the list (which is already stored in result) the item. You are discarding the return of remove, as you should. The equivalent and wrong thing to do would be: : result = list(df.columns) result = result.remove(X)
type: Answer
answers question: http://stackoverflow.com/q/49770819
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86660837
type: Comment
type: QuestionComment
has text: maybe `indexed_df.rolling('250L')`
score: 0
comment on: http://stackoverflow.com/q/49822424

http://stackoverflow.com/comment/86731645
type: AnswerComment
has text: I did. I've also voted for you but it is not publicly displayed because this is new user and I dont have enough reputations. Anyway, you are totaly deserve it. Thank you!
comment on: http://stackoverflow.com/a/49852111
type: Comment
score: 0

http://stackoverflow.com/q/49896802
favorite count: 0
accepted answer: http://stackoverflow.com/a/49897155
type: Question
upvote count: 2
has title: SSH using paramiko and exec_command
has answer: http://stackoverflow.com/a/49897155
tagged with: python
answer count: 1
downvote count: 1
tagged with: paramiko
linked to: http://stackoverflow.com/q/8138241
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86811594
tagged with: ssh
score: 1
has body: Trying to SSH from windows server to a Linux remote connection using SSH and paramiko and just 'pwd' this server with the following code (I've changed the user/password and server IP from real code): import paramiko from paramiko import SSHClient, AutoAddPolicy LOCAL_IP=IP client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(LOCAL_IP,username=username, password=password) client.exec_command('pwd') I'm getting the following result: (&lt;paramiko.ChannelFile from &lt;paramiko.Channel 0 (open) window=24576 -&gt; &lt;paramiko.Transport at 0x6716710L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))&gt;&gt;&gt;, &lt;paramiko.ChannelFile from &lt;paramiko.Channel 0 (open) window=24576 -&gt; &lt;paramiko.Transport at 0x6716710L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))&gt;&gt;&gt;, &lt;paramiko.ChannelFile from &lt;paramiko.Channel 0 (open) window=24576 -&gt; &lt;paramiko.Transport at 0x6716710L (cipher aes128-ctr, 128 bits) (active; 1 open channel(s))&gt;&gt;&gt;) The SSH connection IS open, I can tell by netstat at the linux server that I'm trying to SSH to....
duplicate of: http://stackoverflow.com/q/8138241

http://stackoverflow.com/comment/86747770
has text: well each node is a different `mycontent` tag here, so cant we loop over these directly?
type: Comment
comment on: http://stackoverflow.com/a/49866022
score: 0
type: AnswerComment

http://stackoverflow.com/q/49853326
has answer: http://stackoverflow.com/a/49916326
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
answer count: 1
favorite count: 0
has title: Replace xarray coordinates with another coordinate
type: Question
has body: I try to replace two coordinates with the same length in a xarray.Dataset by using one coordinate for both of them. I do not care about the old coordinates or its values; I simply want to replace them. Is there any convenient method for this? import xarray as xr ds = xr.Dataset({ "a": ("a_coord", [0, 1, 2]), "b": ("b_coord", [50, 10, 20]), "a_coord": [4, 8, 9], "b_coord": [3, 1, 4], "new_coord": [0, 1, 2], }) # Get rid of a_coord and b_coord and replace both with new_coord, so a and b # have new_coord as coordinate. # But how? I tried rename, but it returns a conflict error (since new_coord already exists). ds.rename({ "a_coord": "new_coord", "b_coord": "new_coord", }) Do I have to assign the new coordinate explicitly to each data variable that was depended on one of the old coordinates? Since I have many data variables (not just a and b) and other coordinates, this could become messy.
tagged with: python
tagged with: coordinate
accepted answer: http://stackoverflow.com/a/49916326
tagged with: python-xarray

http://stackoverflow.com/q/49806805
tagged with: css
tagged with: import
has comment: http://stackoverflow.com/comment/86630889
score: -1
type: Question
upvote count: 0
answer count: 1
tagged with: url
has comment: http://stackoverflow.com/comment/86628697
has title: Scrape url of css file imports in css file and then remove them, in Python
downvote count: 1
favorite count: 0
has body: I need to grab all css imports(urls) within a css file. the example is: @import url("/pub-assets/css/index/tac-holidaysale.css"); @import url("/pub-assets/css/index/tc1200-fonts.css"); @import url("/pub-assets/css/index/ad-banner.css"); so I need to get a list that includes: /pub-assets/css/index/tac-holidaysale.css /pub-assets/css/index/tc1200-fonts.css /pub-assets/css/index/ad-banner.css I need this for minifying the Css. After I grabbed all the urls, I need to remove all these imports. How can I do this in Python only?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49806904
has answer: http://stackoverflow.com/a/49806904
tagged with: minify
tagged with: python

http://stackoverflow.com/a/49873690
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/49873536
downvote count: 0
has comment: http://stackoverflow.com/comment/86766764
has comment: http://stackoverflow.com/comment/86766684
has comment: http://stackoverflow.com/comment/86766821
has comment: http://stackoverflow.com/comment/86764414
has body: First of all you need to add one-to-many relation to your models. For this you need to add ForeignKkey field to Taxproduct model: class Taxproduct(models.Model) tax_name = models.CharField(max_length=250) percentage=models.CharField(max_length=250) product = models.ForeignKey(Product, on_delete=models.CASCADE) This will add to Product model attribute taxproduct_set which will return list of related taxes. To add it to serializer with different name (tax_details in your case) use field's source argument: class ProductSerializer(serializers.HyperlinkedModelSerializer): tax_details = TaxproductSerializer(many=True,read_only=True, source='taxproduct_set') class Meta: model = Product fields = ('id','pro_name','description','sales','cost','tax_details')
has comment: http://stackoverflow.com/comment/86764517
has comment: http://stackoverflow.com/comment/86766681
type: Answer
has comment: http://stackoverflow.com/comment/86766407

http://stackoverflow.com/a/78657218
answers question: http://stackoverflow.com/q/49892526
score: 0
has body: There are several projects out there that can help you go from OpenAPI -&gt; SDK. OpenAPI generator (https://github.com/OpenAPITools/openapi-generator) is the most popular but there are 4.2k+ issues. Another option is Fern (https://buildwithfern.com/). Full disclosure: I am a contributor to the Fern.
type: Answer

http://stackoverflow.com/a/49866734
upvote count: 1
has body: This is one way. frontier = [{ 'state': (2, 5, 4, 3, 0, 1), 'path': [ 'PULL' ] }, { 'state': (2, 4, 5, 0, 3, 1), 'path': [ 'SWAP','PULL' ] }, { 'state': (2, 5, 4, 0, 1, 3), 'path': [ 'SWAP' ] }, { 'state': (2, 0, 5, 4, 3, 1), 'path': [ 'PUSH', 'PUSH' ] }] d = {'PUSH': 5, 'PULL': 6, 'SWAP': 8, 'FLIP': 2} res = [sum(map(d.get, item['path'])) for item in frontier] print(res) [6, 14, 8, 10] Explanation Create a dictionary mapping actions to values. Use sum with map to lazily calculate the the sum of all actions in a dictionary. Use a list comprehension to loop through each dictionary in the list.
has comment: http://stackoverflow.com/comment/86749332
score: 1
has comment: http://stackoverflow.com/comment/86749112
accepted answer of: http://stackoverflow.com/q/49866677
answers question: http://stackoverflow.com/q/49866677
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86767422
has text: I tried quite lots of ways yesterday, but for some reasons any of I tried did not work..
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49849827
type: AnswerComment

http://stackoverflow.com/a/49897177
type: Answer
answers question: http://stackoverflow.com/q/49897115
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49897115
has comment: http://stackoverflow.com/comment/86813393
type: AcceptedAnswer
downvote count: 0
has body: Use groupby with size and unstack or crosstab alternative for reshape. For change order of days need ordered Categorical or reindex by columns: cats = ['Monday','Tuesday','Wednesday','Thursday','Friday'] df['Weekday'] = pd.Categorical(df['Weekday'], categories=cats, ordered=True) df = df.groupby(['Time', 'Weekday']).size().unstack(fill_value=0) df = df.groupby(['Time', 'Weekday']).size().unstack(fill_value=0).reindex(columns=cats) Alternatives: df = pd.crosstab(df['Time'], pd.Categorical(df['Weekday'], categories=cats, ordered=True)) df = pd.crosstab(df['Time'], df['Weekday']).reindex(columns=cats) print (df) col_0 Monday Tuesday Wednesday Thursday Friday Time 21:10:00 0 1 0 0 0 21:15:00 0 1 0 0 0 21:20:00 0 2 0 0 0 21:25:00 0 0 2 0 0 21:30:00 0 0 0 0 1 21:35:00 0 0 1 1 0 21:40:00 1 0 2 0 0 Last use seaborn.heatmap: import seaborn as sns sns.heatmap(df, annot=True, fmt="g", cmap='viridis')

http://stackoverflow.com/a/50574354
type: Answer
answers question: http://stackoverflow.com/q/49801638
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49801638
downvote count: 1
score: 15
upvote count: 16
has comment: http://stackoverflow.com/comment/135238667
has comment: http://stackoverflow.com/comment/135252067
has body: Background Yes, positive rewards are better than negative rewards No, positive rewards are not good on an absolute scale No, negative rewards are not bad on an absolute scale If you increase or decrease all rewards (good and bad) equally, nothing changes really. The optimizer tries to minimize the loss (maximize the reward), that means it's interested only in the delta between values (the gradient), not their absolute value or their sign. Reinforcement Learning Let's say your graph looks something like this: ... logits = tf.nn.softmax(...) labels = tf.one_hot(q_actions, n_actions) loss = tf.losses.softmax_cross_entropy(labels, logits, weights=q_rewards) The losses for the individual "classes" get scaled by weights which in this case are q_rewards: loss[i] = -q_rewards[i] * tf.log( tf.nn.softmax( logits[i] ) ) The loss is a linear function of the reward, the gradient stays monotonic under linear transformation. Reward Normalization doesn't mess with the sign of the gradient makes the gradient steeper for rewards far from the mean makes the gradient shallower for rewards near the mean When the agent performs rather badly, it receives much more bad rewards than good rewards. Normalization makes the gradient steeper for (puts more weight on) the good rewards and shallower for (puts less weight on) the bad rewards. When the agent performs rather good, it's the other way 'round. Your questions If positive returns are enforced, and negative returns are discouraged (in the optimize step) ... It's not the sign (absolute value) but the delta (relative values). ... then no matter the length of the episode, roughly the first half of the actions will be encouraged, and the latter half will be discouraged. If there are either much more high or much more low reward values, then you have a smaller half with a steeper gradient (more weight) and a larger half with a shallower gradient (less weight). If it IS true, then I don't understand why the model trains, since even a good-perfor…

http://stackoverflow.com/q/49771421
possible better answer: http://stackoverflow.com/a/49771534
answer count: 2
has answer: http://stackoverflow.com/a/49771481
tagged with: indentation
tagged with: pep8
duplicate of: http://stackoverflow.com/q/53162
tagged with: python
has title: Unexpected indent error while i break my url to short length as per PEP8 guideline
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/10739843
has body: I tried to make url of short length but its giving unexpected indent.i provided the piece of code on which its giving error trackback: Traceback (most recent call last): File "C:\Users\HOME\Desktop\movie trailer\entertainment.py", line 1, in import media File "C:\Users\HOME\Desktop\movie trailer\media.py", line 85 "/w185"+str(detail_new[4])" ^ IndentationError: unexpected indent self.poster_image_url = "http://image.tmdb.org/t/p" "/w185"+str(detail_new[4])" self.trailer_youtube_url = "https://www.youtube.com/watch?" "v="+str(self.get_trailer_link(movie_name))"
has answer: http://stackoverflow.com/a/49771534
accepted answer: http://stackoverflow.com/a/49771481
duplicate of: http://stackoverflow.com/q/10739843
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/49892206
type: Question
possible better answer: http://stackoverflow.com/a/49892322
has title: I want to replace words from a file by the line no using python i have a list of line no?
answer count: 2
has answer: http://stackoverflow.com/a/49892322
tagged with: file
accepted answer: http://stackoverflow.com/a/49892258
has answer: http://stackoverflow.com/a/49892258
type: AnsweredQuestion
score: 0
tagged with: list
has body: if I have a file like: Flower Magnet 5001 100 0 and I have a list containing line number, which I have to change. list =[2,3] How can I do this using python and the output I expect is: Flower Most Most 100 0 Code that I've tried: f = open("your_file.txt","r") line = f.readlines()[2] print(line) if line=="5001": print "yes" else: print "no" but it is not able to match. i want to overwrite the file which i am reading
tagged with: python

http://stackoverflow.com/a/49822941
upvote count: 2
downvote count: 2
answers question: http://stackoverflow.com/q/49822712
has body: The "random" module should come pre-included in both python2 and python3, especially if you're working on the more recent versions of each of these. Try just using: import random in your project/file and you should be able to import the module and use it just fine.
type: Answer
score: 0

http://stackoverflow.com/a/49775125
answers question: http://stackoverflow.com/q/49774035
has comment: http://stackoverflow.com/comment/99401823
has comment: http://stackoverflow.com/comment/86926748
has body: python train_model.py \ --training_data=rnn_tutorial_data/training.tfrecord-?????-of-????? \ --eval_data=rnn_tutorial_data/eval.tfrecord-?????-of-????? \ --classes_file=rnn_tutorial_data/training.tfrecord.classes AFAIK using the above command works as well, it will simply read all the files in the folder where you have download the data files one by one. create_tfrecord_for_prediction is certainly not my own creation, this code was mostly picked from another file from tensorflow guys create_dataset.py Below I have pasted the almost all of the new code i added including the my modifications to the main() function def create_tfrecord_for_prediction(batch_size, stoke_data, tfrecord_file): def parse_line(stoke_data): """Parse provided stroke data and ink (as np array) and classname.""" inkarray = json.loads(stoke_data) stroke_lengths = [len(stroke[0]) for stroke in inkarray] total_points = sum(stroke_lengths) np_ink = np.zeros((total_points, 3), dtype=np.float32) current_t = 0 for stroke in inkarray: if len(stroke[0]) != len(stroke[1]): print("Inconsistent number of x and y coordinates.") return None for i in [0, 1]: np_ink[current_t:(current_t + len(stroke[0])), i] = stroke[i] current_t += len(stroke[0]) np_ink[current_t - 1, 2] = 1 # stroke_end # Preprocessing. # 1. Size normalization. lower = np.min(np_ink[:, 0:2], axis=0) upper = np.max(np_ink[:, 0:2], axis=0) scale = upper - lower scale[scale == 0] = 1 np_ink[:, 0:2] = (np_ink[:, 0:2] - lower) / scale # 2. Compute deltas. #np_ink = np_ink[1:, 0:2] - np_ink[0:-1, 0:2] #np_ink = np_ink[1:, :] np_ink[1:, 0:2] -= np_ink[0:-1, 0:2] np_ink = np_ink[1:, :] features = {} features["ink"] = tf.train.Feature(float_list=tf.train.FloatList(value=np_ink.flatten())) features["shape"] = tf.train.Feature(int64_list=tf.train.Int64List(value=np_ink.shape)) f = tf.train.Features(feature=features) ex = tf.train.Example(features=f) return ex if stoke_data is None: print("Error: Stroke data cannot be none") return example = parse_line(st…
type: Answer
has comment: http://stackoverflow.com/comment/86926915
accepted answer of: http://stackoverflow.com/q/49774035
has comment: http://stackoverflow.com/comment/87140057
has comment: http://stackoverflow.com/comment/99401814
has comment: http://stackoverflow.com/comment/86928208
has comment: http://stackoverflow.com/comment/87149032
has comment: http://stackoverflow.com/comment/87155534
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86926555
has comment: http://stackoverflow.com/comment/87324309

http://stackoverflow.com/comment/86742961
score: 1
comment on: http://stackoverflow.com/q/49863243
type: QuestionComment
has text: I'm sorry if I misunderstand your problem, don't you want simply to do: `df['b'] = df.apply(lambda x: search_log(x['b'],x['a'],search_string),axis=1)`?
type: Comment

http://stackoverflow.com/comment/86541542
score: 0
has text: entire list of list in my case provided above its ''
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49762947

http://stackoverflow.com/comment/86689211
type: Comment
comment on: http://stackoverflow.com/a/49836968
score: 0
type: AnswerComment
has text: When you call bindings.SetProperty in Python, it works. But the part I'm struggling with is trying to define the Python variable from the JavaScript (cefpython) side, which doesn't seem to update again once the script has initially run, or at least it's not happening when I call any of the functions I've tried so far. (And a lot of times, it just produces various errors. But you can still see the first instance outputted in the popup.)

http://stackoverflow.com/q/49864475
has comment: http://stackoverflow.com/comment/86753013
favorite count: 0
has body: I have an Azure blob storage account which is fire walled to selected networks only. I would like to access this storage account from a function app running on a dynamic plan whose outbound IP addresses are known to me. Problem is that I add these outbound ips to the Allowed IP addresses in Firewall and Virtual Network settings of the blob storage but I still continue to get an error which says: This request is not authorized to perform this operation. Can someone please point out where I am going wrong? N.B. I am using PythonSDK for accessing the blob storage with the account name and the account key!
has comment: http://stackoverflow.com/comment/86893370
has answer: http://stackoverflow.com/a/56140173
tagged with: azure
tagged with: azure-functions
tagged with: azure-blob-storage
has comment: http://stackoverflow.com/comment/86748377
has comment: http://stackoverflow.com/comment/86829535
tagged with: python
type: Question
upvote count: 4
has title: Access to Azure Blob Storage with Firewall from Azure Function App
type: UnansweredQuestion
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/49550931
score: 4

http://stackoverflow.com/a/49866618
has body: Your test are using User in a wrong way. you need to keep the object return by the User class: user = User(1, 2) print(user.x) print(user.y) print(user.client.x)
type: Answer
answers question: http://stackoverflow.com/q/49866519
score: 0

http://stackoverflow.com/comment/86576216
type: Comment
comment on: http://stackoverflow.com/a/49767553
type: AnswerComment
has text: Thanks a lot R.yan
score: 0

http://stackoverflow.com/comment/86642412
type: AnswerComment
comment on: http://stackoverflow.com/a/49788539
has text: Just opened the page source and searched for the string using ctrl F
score: 0
type: Comment

http://stackoverflow.com/a/49867197
answers question: http://stackoverflow.com/q/49867180
has comment: http://stackoverflow.com/comment/86750132
downvote count: 0
has comment: http://stackoverflow.com/comment/86750741
has comment: http://stackoverflow.com/comment/86749966
score: 2
has body: You can use an OrderedDict from the collections module to store your sorted value from collections import OrderedDict a_dict = {'aa1':'n','ba2' : 'a','aa2':'a'} sorted_by_key_then_value = sorted(a_dict.items(), key=lambda t: (t[1], t[0]))) sort_dict = OrderedDict(sorted_by_key_then_value) EDIT: I mix up key and value in (t[0], t[1]). In the key function t[0] give the key, and t[1] give the value. The sorted function will use the tuple(value, key) and order them by alphanumerical order.
type: Answer
upvote count: 2

http://stackoverflow.com/comment/86743188
comment on: http://stackoverflow.com/q/49822986
has text: @sambler No I don't have another variable named texture. Already checked that out. However, I recreated the script new and it worked. I don't know what the problem was.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49798796
tagged with: pandas
has answer: http://stackoverflow.com/a/49798920
has answer: http://stackoverflow.com/a/49798876
possible better answer: http://stackoverflow.com/a/49798876
accepted answer: http://stackoverflow.com/a/49798962
tagged with: dataframe
favorite count: 0
type: Question
upvote count: 0
score: -3
has answer: http://stackoverflow.com/a/49798962
tagged with: python
has body: I am trying to get total values of these table building_weight_and_height = {'Floor': ['Roof','10th','9th','8th','7th','6th','5th','4th','3rd','2nd'], 'DL(kN)': [1200,1200,1200,1200,1200,1200,1200,1200,1200,1200], 'StoreyHeight': [3,3,3,3,3,3,3,3,3,4]} Expected output: Output image
type: AnsweredQuestion
has title: Total values dataframe python
answer count: 3
downvote count: 3

http://stackoverflow.com/comment/86711594
type: Comment
type: AnswerComment
has text: This may be correct on Windows, but the OP Is clearly not on Windows, since they are setting the PATH in a .bashrc file and the path specified looks like it is from some *nix variant.
comment on: http://stackoverflow.com/a/49845975
score: 1

http://stackoverflow.com/comment/86791596
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49867284
has text: Yes you don't need to add X_train Y_train, it was just an example X was the entry and Y was the result

http://stackoverflow.com/q/49767414
has comment: http://stackoverflow.com/comment/86557540
linked to: http://stackoverflow.com/q/4257410
has comment: http://stackoverflow.com/comment/86557754
has comment: http://stackoverflow.com/comment/86555000
answer count: 1
has comment: http://stackoverflow.com/comment/86558996
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86556977
has comment: http://stackoverflow.com/comment/86554344
has comment: http://stackoverflow.com/comment/86557296
type: UnansweredQuestion
tagged with: sockets
has answer: http://stackoverflow.com/a/75025930
tagged with: python
has comment: http://stackoverflow.com/comment/86550992
has body: I found, that buffer size can be set this way sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1) # Buffer size 8192 I set only 1 byte for the test. Let's send some big amount of data: cat file.txt | nc -l 1489 But, I'm still able to get more than 1 byte here.. while 1: read_ready = select.select([sock], [], [], timeout_in_seconds) if read_ready[0]: # we have what to read data = sock.recv(1000) It looks like buffer size is enough to keep all data from file, and it is obviously not 1 byte, what we set above.
has title: Buffer size in socket, python3
score: 0

http://stackoverflow.com/comment/86778048
type: QuestionComment
score: 0
has text: Yes Colin, it is returning me the web url that basically has the pdf document for every item in the cusip list.
comment on: http://stackoverflow.com/q/49880846
type: Comment

http://stackoverflow.com/comment/86659198
type: QuestionComment
has text: Can you show some of the code you have tried? :)
comment on: http://stackoverflow.com/q/49821907
type: Comment
score: 1

sequences
tags question: http://stackoverflow.com/q/49896242
tag name: sequences
type: Tag
tags question: http://stackoverflow.com/q/49833528
tags question: http://stackoverflow.com/q/49770284

http://stackoverflow.com/comment/86806201
type: Comment
comment on: http://stackoverflow.com/a/49876121
score: 0
type: AnswerComment
has text: @Sahitya Oh wait, are you using [`tf.keras.Model`](https://www.tensorflow.org/api_docs/python/tf/keras/Model) or [`keras.model.Model`](https://keras.io/models/model/). If it is the second one, you can access the graph through the [backend](https://keras.io/backend/) like `K.get_session().graph` (see [issue #3223](https://github.com/keras-team/keras/issues/3223)).

word2vec
tags question: http://stackoverflow.com/q/49847602
tags question: http://stackoverflow.com/q/49761175
type: Tag
tags question: http://stackoverflow.com/q/49798313
tag name: word2vec

http://stackoverflow.com/q/49846343
type: UnansweredQuestion
tagged with: group-by
tagged with: python
has title: Python Groupby Iteration Error
score: 0
tagged with: pandas
has body: Getting the following error after running the following code: for names, group in df_group: print(str(names)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'int' object is not iterable Any ideas? df_group's output is (for example) the following symbol exchange price AAPL NASDAQ 154.630 800 154.640 641 154.650 100 154.660 300 154.670 400 154.675 100 154.680 300 154.690 1390 154.695 100 154.700 360 154.705 100 154.710 671 154.720 190 154.725 100 154.730 400 ... XOM ARCA 80.67 1300 80.68 2721 80.69 1901 80.7 700 80.71 800 80.72 200 80.73 700 80.74 500 80.75 600 80.76 300 80.77 900 80.78 100 80.79 1000 80.8 1000 symbol exch price sizesizesizesizesizesizesizesizesizesizesizesi... And I've grouped using the following code: df_group = df.groupby(['symbol','exchange','price'])["size"].sum() Thanks!!
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/49846451

http://stackoverflow.com/comment/86739996
type: Comment
has text: @pault, Desired output is the dataset sans null values. Fancyimpute does mean/median imputation, Knn imputation, etc for the numerical columns but I couldn't find any libraries for imputing null values in categorical data.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49862211

http://stackoverflow.com/a/49763202
has comment: http://stackoverflow.com/comment/86542010
upvote count: 1
has body: Here is what you are looking for. you actually want to remove all the empty entries from lists : unique =[] tempList = [] a=[['102 min', '', 'Comedy', 'User Rating: 6.6/10 (4,072 user ratings)', '69', 'Metascore', '', 'Rank:', '10', 'Showtimes:', 'Studio Movie Grill - Downey', '11:00 am', '', '1:35 pm', '', '4:10', '', '4:55', '', '7:40', '', '9:55', '', '10:35'], ['110 min', '', 'Comedy', '', 'Drama', '', 'Romance', 'User Rating: 8.1/10 (11,478 user ratings)', '73', 'Metascore', '', 'Rank:', '18', 'Showtimes:', 'Studio Movie Grill - Downey', '11:30 am', '', '2:10 pm', '', '4:45', '', '7:25', '', '10:00'], ['111 min', '', 'Action', '', 'Adventure', '', 'SciFi', 'User Rating: 6/10 (23,905 user ratings)', '44', 'Metascore', '', 'Rank:', '7', 'Showtimes:', 'Studio Movie Grill - Downey', '11:05 am', '', '1:50 pm', '', '4:35', '', '7:20', '', '10:05'], ['118 min', '', 'Action', '', 'Adventure', '', 'Drama', '', 'Fantasy', '', 'Thriller', 'User Rating: 6.8/10 (45,126 user ratings)', '48', 'Metascore', '', 'Rank:', '8', 'Showtimes:', 'Studio Movie Grill - Downey', '11:10 am', '', '1:55 pm', '', '4:40', '', '7:35', '', '10:20'], ['120 min', '', 'Thriller', 'User Rating: 4.9/10 (1,002 user ratings)', '32', 'Metascore', '', 'Rank:', '16', 'Showtimes:', 'Studio Movie Grill - Downey', '11:20 am', '', '2:05 pm', '', '4:50', '', '7:45', '', '10:40'], ['134 min', '', 'Action', '', 'Adventure', '', 'SciFi', 'User Rating: 7.8/10 (223,161 user ratings)', '88', 'Metascore', '', 'Rank:', '4', 'Showtimes:', 'Studio Movie Grill - Downey', '12:00 pm', '', '4:05', '', '7:15', '', '10:15'], ['140 min', '', 'Action', '', 'Adventure', '', 'SciFi', 'User Rating: 7.9/10 (76,138 user ratings)', '64', 'Metascore', '', 'Rank:', '1', 'Showtimes:', 'Studio Movie Grill - Downey', '11:45 am', '', '4:00 pm', '', '7:10', '', '10:10'], ['86 min', '', 'Animation', '', 'Adventure', '', 'Comedy', '', 'Family', '', 'Fantasy', '', 'Mystery', '', 'Romance', 'User Rating: 4.7/10 (1,275 user ratings)', '36', 'Me…
has comment: http://stackoverflow.com/comment/86542287
answers question: http://stackoverflow.com/q/49762947
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/86542521
has comment: http://stackoverflow.com/comment/86542396
has comment: http://stackoverflow.com/comment/86542042
accepted answer of: http://stackoverflow.com/q/49762947
downvote count: 2
has comment: http://stackoverflow.com/comment/86542051
type: AcceptedAnswer

sentiment-analysis
tags question: http://stackoverflow.com/q/49863520
tags question: http://stackoverflow.com/q/49765834
tags question: http://stackoverflow.com/q/49880762
type: Tag
tag name: sentiment-analysis
tags question: http://stackoverflow.com/q/49871737

http://stackoverflow.com/q/49890346
has comment: http://stackoverflow.com/comment/86796625
has comment: http://stackoverflow.com/comment/86796751
type: Question
has comment: http://stackoverflow.com/comment/86796522
has answer: http://stackoverflow.com/a/49911350
tagged with: mongodb
type: UnansweredQuestion
has title: Pymongo Nested Search
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/86838402
has comment: http://stackoverflow.com/comment/86802257
has comment: http://stackoverflow.com/comment/86832189
has body: I have some nested data in mongo that I am trying (unsuccessfully) to query. An example of the document I am trying to find is shown below: { 'T009_Measurments': { 'ConditionKey': 'WPS-ActivePower 0-920,', 'HalfLifeDays': 100, 'ID': 120, 'LocationName': 'T001', 'MeasurementKey': 'Some DATA/LOC/LOC LOC/FFT_16000', 'Overload': 0, 'RPM': 1496.6044, 'RedAlarm': 0, 'TimeClosed-Min': 1440, 'Trigger_Time': datetime.datetime(2099, 6, 11, 20, 20, 40), 'WPS-ActivePower-Average': 727.0, 'WPS-ActivePower-Deviation': 0.0, 'YellowAlarm': 0 } } What I really want to do is search by HalfLifeDays. I have tried several things including: db.collection.find({'T009_Measurments.HalfLifeDays' : 100}) db.collection.find({'T009_Measurments'}: {'HalfLifeDays' : 100}) But so far I cannot get anything. What am I doing wrong?
answer count: 1
tagged with: pymongo
has comment: http://stackoverflow.com/comment/86796581

http://stackoverflow.com/comment/86796208
score: 0
has text: Could you post the URL that you are attempting to scrape from?
type: QuestionComment
comment on: http://stackoverflow.com/q/49890130
type: Comment

http://stackoverflow.com/a/49937599
score: 0
has body: The pycrfsuite docs don't mention what their Unicode support is for feature values and keys. I can't tell from the examples either, as it isn't clear to me if they are Python 2 or 3. Also, I don't know enough about Cython to give you a definite answer by reading the source. In any case, I suggest you try two things: Just encode the keys yourself before you pass them to the library. If the values are strings too, encode them as well. Maybe the library is happy to accept bytes objects. If that doesn't work (because it really wants to have ASCII), use some ASCII encoding, eg. use urlencode or call Python's ascii() built-in function on the string. The latter will encode 'can’t' to "'can\\u2019t'", with backslash escapes and quotes. It doesn't really matter, since the classifier doesn't care about how the feature keys look, as long as the same input produces the same feature key. I hope this helps!
type: Answer
answers question: http://stackoverflow.com/q/49891013

http://stackoverflow.com/a/49765651
answers question: http://stackoverflow.com/q/49765286
type: Answer
has body: Automatic detection of being appended to a list is not possible. Here are two ways that are close enough. You only need to go with one: An ORM-like save(self) function. Instead of appending child to root, assign root to child with Pythonic @property and setter. class Root: def __init__(self): self.children = [] #1 def save(self): for child in self.children: child.root = self class Child: def __init__(self): self.__root = None #2 @property def root(self): return self.__root #2 @root.setter def root(self, root): self.__root = root if self not in root.children: root.children.append(self) Usage for #1: root_obj = Root() child_obj = Child() root_obj.children.append(child_obj) root_obj.save() print(child_obj.root) # &lt;__main__.Root object at 0x05932890&gt; Usage for #2: root_obj = Root() child_obj = Child() child_obj.root = root_obj print(root_obj.children) # [&lt;__main__.Child object at 0x060578F0&gt;] Bonus If you combine both, you can easily handle: reassignments, e.g. child_obj.root = root_obj_2 ...including edge cases, e.g. child_obj.root = None removal, e.g. root_obj.children.remove(child_obj) and then root_obj.save() class Root: def __init__(self): self.children = [] self.__previous_children = [] def save(self): diff = [c for c in self.__previous_children if c not in self.children] if len(diff) == 0 and len(self.__previous_children) == len(self.children): return for child in diff: child.root = None self.__previous_children = self.children.copy() for child in self.children: child.root = self class Child: def __init__(self): self.__root = None @property def root(self): return self.__root @root.setter def root(self, root): if self.__root == root: return if self.__root is not None: try: self.__root.children.remove(self) self.__root.save() except: pass self.__root = root if root is None: return if self not in root.children: root.children.append(self) root.save()
accepted answer of: http://stackoverflow.com/q/49765286
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49866446
type: UnansweredQuestion
has body: When using ax.grid() and moving the spines to the middle of the plot, the grid lines go over the axes labels. Any way to stop this and move the axes labels to "front"? EDIT: It is the ticks labels (the numbers) I'm interested in fixing, not the axis label, which can be easily moved. EDIT: made the MWE and image match exactly EDIT: matplotlib version 2.0.0 #!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = plt.gca() ax.minorticks_on() ax.grid(b=True, which='major', color='k', linestyle='-',alpha=1,linewidth=1) ax.grid(b=True, which='minor', color='k', linestyle='-',alpha=1,linewidth=1) x = np.linspace(-5,5,100) y = np.linspace(-5,5,100) plt.plot(x,y) plt.yticks([-5,-4,-3,-2,-1,0,1,2,3,4,5]) ax.spines['left'].set_position(('data', 0)) plt.show()
tagged with: matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/86750003
has title: ax.grid overwrites ticks labels when spine is in centre
score: 0
has comment: http://stackoverflow.com/comment/86767472
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/86749993

http://stackoverflow.com/comment/86821685
has text: That, I understand, but it seems the function is still runnung at the end of the run another function is called, so first, is it possible? Doesn't the execution stops when it calls another function?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49898476

http://stackoverflow.com/a/49856786
type: Answer
has body: A small function which solves it: def unique_comb(a): return list(set(itertools.chain(*a))) For example: unique_comb(([1, 4, 7], [8, 2, 5], [8, 1, 4, 6])) If you want to pass a list as an argument to the function, rather than a list inside a tuple, just remove the * (which unpacks the list). If you want to apply it to the entire array in one statement without defining a function: a3 = [list(set(itertools.chain(*row))) for row in a2]
downvote count: 0
answers question: http://stackoverflow.com/q/49856426
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49856426

http://stackoverflow.com/a/49873743
has comment: http://stackoverflow.com/comment/123740530
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86762870
answers question: http://stackoverflow.com/q/49873707
has comment: http://stackoverflow.com/comment/86763314
accepted answer of: http://stackoverflow.com/q/49873707
has comment: http://stackoverflow.com/comment/86770584
type: Answer
has comment: http://stackoverflow.com/comment/86768392
has body: You need to try that: \s*([\S]+)$ Regex 101 Demo Explanation: \s* zero or more whitespace characters [\S]+ followed by one or more non whitespace characters $ followed by end of line. By that way, you are guaranteed to match the last occurance of whitespace characters as that will be followed by no further whitespace characters. The reason behind your regex did not work because \w+ only covers A-Za-z0-9_ So, / doesn't match in two of your example.
score: 2

http://stackoverflow.com/comment/98339231
has text: I mean the contour has Gaussian behavior but the results of the parameter is very close to the mean value I considered in Gaussian equation.
type: Comment
comment on: http://stackoverflow.com/a/50277755
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86852045
has text: @GPhilo. any pointers for getting the column names?
score: 0
comment on: http://stackoverflow.com/q/49916232
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/87120787
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50047896
type: AnswerComment
has text: I know how to do that

http://stackoverflow.com/a/55813011
downvote count: 0
has body: According to the locations section of the parameter listing in the Developer documentation for the Streaming end-point: -122.75,36.8,-121.75,37.8,-74,40,-73,41 translates to San Francisco OR New York City so, accordingly, your code should be formatted to ... stream.filter(locations=[-4.62,41.97,10.49,51.1,-87.6,24.73,-75.41,32.12]) as a single list of all locations following the South-West and North-East grouping; thereby, as a sanity check please ensure that your locations list be a multiple of four (allowing for a latitude and longitude each for SW and NE coordinates for each bounding box) and also that NE coordinates > SW coordinates. Please be sure to keep in mind that the stream API end-point permits the filtering of only ...25 0.1-360 degree location boxes.
has comment: http://stackoverflow.com/comment/102372018
has comment: http://stackoverflow.com/comment/99581089
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49799031
type: Answer
answers question: http://stackoverflow.com/q/49799031
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/86663958
has text: Error : if value_to_mask == "NaN" or np.isnan(value_to_mask): TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49824027
score: 0

http://stackoverflow.com/comment/86683207
comment on: http://stackoverflow.com/q/49833151
score: 0
has text: @ScottBoston Thanks a lot, Scott. It's done.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49921758
has comment: http://stackoverflow.com/comment/86975897
type: Answer
accepted answer of: http://stackoverflow.com/q/49787924
score: 4
has body: To view norm or global norm in Tensorboard you can manually calculate it. For the norm (not global) you obtain gradient as usual using compute_gradients and compute gradient l2 norm using tf.norm. This gives you a scalar value. You can add it to Tensorboard using tf.summary.scalar. For the global norm you can compute it using tf.global_norm and then add it to Tensorboard (also scalar summary). EDIT: Please note that tf.norm expects single tensor. So you need to compute norm and add to to Tensorboard for each gradients tensor. The same as you do when using tf.summary.histogram to view values.
upvote count: 4
has comment: http://stackoverflow.com/comment/86881645
has comment: http://stackoverflow.com/comment/86961637
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49787924

http://stackoverflow.com/comment/86788525
type: AnswerComment
has text: Correction on previous comment: `mirror` is the **y**-coordinate of the mirror, not the x.
comment on: http://stackoverflow.com/a/49885898
type: Comment
score: 0

http://stackoverflow.com/comment/86590110
has text: if currentValue == "Red": mc.objExists, mc.hyperShade(objects='lambert1') mc.objExists, mc.hyperShade(assign='red') elif currentValue == "Blue": mc.objExists, mc.hyperShade(objects='lambert1') mc.objExists, mc.hyperShade(assign='blue')
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49786843

http://stackoverflow.com/comment/86725493
score: 0
has text: Only that I do is download a file, and save him to a specific folder, this is the example file.
type: QuestionComment
comment on: http://stackoverflow.com/q/49855419
type: Comment

http://stackoverflow.com/comment/86617875
score: 0
type: Comment
type: QuestionComment
has text: its (none,15,4)
comment on: http://stackoverflow.com/q/49801165

http://stackoverflow.com/comment/86601540
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49784872
has text: If you use `numpy.set_printoptions(linewidth=150)` you may be able to print all 12 columns without carriage return.

http://stackoverflow.com/q/49906434
has title: Using tensorflow reduce_sum on tensorflow placeholder results in random error
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86832911
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/86833417
type: Question
has body: I am implementing a Replicated Softmax Model in tensorflow. Given a batch of data, I have to sum along the rows (yielding a column vector) and I have to take an outer product of this with the hidden units bias. Using tf.matmul(tf.squeeze(tf.reduce_sum(visible_units, 1,keepdims=True)), tf.expand_dims(self.h, 1)) causes this error InvalidArgumentError (see above for traceback): In[0] is not a matrix Here visible_units is a tf.placeholder (dimension: batch_size x n_visible_units) and self.h is hidden layer bias (n_hidden_units). The error doesn't make sense and seems completely unrelated. If I replace tf.matmul(tf.squeeze(tf.reduce_sum(visible_units, 1,keepdims=True)), tf.expand_dims(self.h, 1)) with just self.h my code runs fine. EDIT: tf.squeeze(tf.reduce_sum(visible_units, 1,keepdims=True)) generates a 1-D tensor so just had to reshape this.
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/86835017
type: Comment
type: QuestionComment
has text: @PaulPanzer I suppose we just differ in what we believe the OP is intending to ask. They closed with the first duplicate themselves - and a dynamically allocated array in C does not prevent resizing either.
score: 0
comment on: http://stackoverflow.com/q/49908780

http://stackoverflow.com/a/49863358
downvote count: 0
has comment: http://stackoverflow.com/comment/86741969
has body: I suppose you want to develop your own code and not use libraries or built-in functions. Your code is fine. There's just one simple mistake: change the slice index from size to 1 in this line arr = arr[size:], where 1 means size - (size-1) def split(arr, size): arrs = [] while len(arr) &gt; size: pice = arr[:size] arrs.append(pice) arr = arr[1:] arrs.append(arr) return arrs output: [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] It also works for other sizes: print split(x, 3) print split(x, 4) [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]] [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
has comment: http://stackoverflow.com/comment/86742042
type: Answer
has comment: http://stackoverflow.com/comment/86741889
has comment: http://stackoverflow.com/comment/86742791
has comment: http://stackoverflow.com/comment/86742854
answers question: http://stackoverflow.com/q/49863276
upvote count: 3
score: 3

http://stackoverflow.com/a/49839619
score: 3
upvote count: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49839547
has body: This is a recursive divide-and-conquer algorithm, in a sense. Bit shifting left by 1 effectively divides a number by 2 (discarding any remainder). minProductHelper divides smaller by 2 using s = smaller &gt;&gt; 1 and then returns the recursively derived sum of s * bigger and (smaller - s) * bigger. Because of the properties of addition and multiplication, you have that ((smaller - s) * bigger) + (s * bigger) == smaller * bigger which is the outcome you want. You have two base cases which are when smaller is either 0 or 1, so you can imagine that a call to minProduct(a,b) will keep cutting a or b into halves (and those halves into halves, etc.) until all it has to do is sum a bunch of products involving 0 and some number or 1 and some number, which can be determined without having to use the * operator. The smaller number is always cut in half rather than the larger number because this allows the base cases to be reached with less recursive calls.
type: Answer
accepted answer of: http://stackoverflow.com/q/49839547

http://stackoverflow.com/comment/86841001
type: Comment
score: 0
type: AnswerComment
has text: Ah you're right, it doesn't find multiple duplicates. I'll make a note of that in my answer.
comment on: http://stackoverflow.com/a/49912465

http://stackoverflow.com/comment/86659480
comment on: http://stackoverflow.com/a/49815668
type: AnswerComment
has text: Many thanks, these are very good tips. I'll find some time to look into this today.
type: Comment
score: 0

http://stackoverflow.com/a/49920709
type: AcceptedAnswer
has body: The last revision of MySQL Connector/ODBC 5.1 was released over five (5) years ago. Upgrading the driver to the latest GA version (5.3.10) and upgrading iODBC appears to have resolved the issue.
answers question: http://stackoverflow.com/q/49848567
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49848567
score: 1

http://stackoverflow.com/q/49897735
tagged with: django
tagged with: django-rest-framework
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49898372
score: 3
has answer: http://stackoverflow.com/a/53496778
tagged with: python
type: UnansweredQuestion
has title: What is different between "DRF Throttling" and "Django Axes"
has comment: http://stackoverflow.com/comment/87025427
upvote count: 3
has body: The "Django-Rest-Framework (DRF) Throttling" can help to prevent bruteforce attacks and failed login attempts. Then why do we need to use "Django axes", "Django defender", "django-ratelimit" or similar components? Thanks In Advance
answer count: 2
downvote count: 0

http://stackoverflow.com/q/49803159
tagged with: python
tagged with: portforwarding
score: 0
answer count: 0
upvote count: 1
has title: How to avoid portforwarding in network programming
downvote count: 1
has body: I've tried programming chat application (server, client) but I have problem with receiving packets on my server. Application is working correctly but only when I have opened port my router. My question is: is there a way to avoid portforwarding on router? It would be better if my application could just make rule in firewall or something like that. Also, app is written in python and I'm using TCP protocol for connecting. Thanks for answers
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86620991
tagged with: network-programming
tagged with: server
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86620938

http://stackoverflow.com/comment/86704634
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49843550
type: AnswerComment
has text: I recommend you note that `[...]` is called `character class` and means one character which is included in the `set` which is represented by `[...something...] `. And I'll happy to see you understand search modifier `lazy`, `greedy`, and `possessive`(or `atomic group`). Thank you:-)

http://stackoverflow.com/q/49763362
tagged with: python-3.x
has title: Can't build optional modules readline and _curses when compiling Python3.4 from source on CentOS7
upvote count: 2
has body: When compiling Python 3.4.3 from source on CentOS 7 the README indicates to run ./configure make make test sudo make install On the second step, make, I see Python build finished successfully! The necessary bits to build these optional modules were not found: _bz2 _curses _curses_panel _dbm _gdbm _lzma _sqlite3 _ssl _tkinter readline zlib To find the necessary bits, look in setup.py in detect_modules() for the module's name. But nothing in the source code for setup.py indicates what to do? It seems like I already have the requisite package? $ sudo yum install readline ... Package readline-6.2-10.el7.x86_64 already installed and latest version Nothing to do How do I get the readline module for python 3?
downvote count: 0
answer count: 1
favorite count: 0
tagged with: centos
score: 2
type: AnsweredQuestion
tagged with: python
accepted answer: http://stackoverflow.com/a/49763363
tagged with: readline
linked to: http://stackoverflow.com/q/26129623
has answer: http://stackoverflow.com/a/49763363
type: Question

http://stackoverflow.com/comment/86778849
score: 1
comment on: http://stackoverflow.com/a/49866616
type: Comment
has text: Hi Noobie, I have not come across something like this, it seems like there are some empty nodes or other formatting issues in your XML but that's just guessing...
type: AnswerComment

http://stackoverflow.com/a/49835113
type: AcceptedAnswer
downvote count: 2
answers question: http://stackoverflow.com/q/49834883
score: 31
type: Answer
has body: This is kind of ugly (I think the matplotlib solution you used in your question is better, FWIW), but you can always create a temporary DataFrame with the index as a column usinng df.reset_index() If the index was nameless, the default name will be 'index'. Assuming this is the case, you could use df.reset_index().plot(kind='scatter', x='index', y='columnA')
has comment: http://stackoverflow.com/comment/86685719
has comment: http://stackoverflow.com/comment/86685658
accepted answer of: http://stackoverflow.com/q/49834883
upvote count: 33

http://stackoverflow.com/comment/86752095
has text: I'm worried about the `symbol exch price sizesizesizesizesizesizesizesizesizesizesizesi...` in your data.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49868282

http://stackoverflow.com/a/51462434
has comment: http://stackoverflow.com/comment/122277364
type: Answer
score: 123
has comment: http://stackoverflow.com/comment/105322276
has comment: http://stackoverflow.com/comment/108184569
upvote count: 124
has comment: http://stackoverflow.com/comment/99469654
downvote count: 1
answers question: http://stackoverflow.com/q/49836676
has comment: http://stackoverflow.com/comment/99448907
has comment: http://stackoverflow.com/comment/92289213
has comment: http://stackoverflow.com/comment/105338845
has body: We can clear the error by modifying the pip file. Check the location of the file: $ which pip path -> /usr/bin/pip Go to that location(/usr/bin/pip) and open terminal Enter: $ sudo nano pip You can see: import sys from pip import main if __name__ == '__main__': sys.exit(main()) Change to: import sys from pip import __main__ if __name__ == '__main__': sys.exit(__main__._main()) then ctrl + o write the changes and exit Hope this will do!!
has comment: http://stackoverflow.com/comment/102444289

save
tags question: http://stackoverflow.com/q/49844290
tag name: save
tags question: http://stackoverflow.com/q/49834317
type: Tag
tags question: http://stackoverflow.com/q/49812981

http://stackoverflow.com/comment/86865524
has text: Fab thanks! I had a conflict with mapped drives and the drives' real path, so I used i.name
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49905875
type: Comment

http://stackoverflow.com/a/49762978
downvote count: 0
answers question: http://stackoverflow.com/q/49761161
type: Answer
upvote count: 1
has body: This prints correctly in my terminal, no %20s here. I assume your raw string literal is not respected by the external call to Excel in wb.ActiveSheet.ExportAsFixedFormat(0, path_to_pdf). Try adding quotes: path_to_pdf = r'"G:/Team/EBAs/{}/PDF/{}_EBA_{}.pdf"'.format(curyq, i, curyq) ## path to save pdf file
score: 1

http://stackoverflow.com/comment/86539734
type: Comment
comment on: http://stackoverflow.com/a/49758686
type: AnswerComment
score: 0
has text: The url where facebook gives me the error: https://www.facebook.com/v2.12/dialog/oauth?client_id=160259374640207&redirect_uri=https%3A%2F%2Fdevelopment.com%3A8000%2Fsocial-auth%2Ffacebook%2Flogin%2Fcallback%2F&scope=public_profile+user_friends+email&response_type=code&state=H6tfy30imsJp&auth_type=reauthenticate

http://stackoverflow.com/comment/86824172
type: Comment
has text: I now have ` ` but it still appears to be left-aligned. Sigh. Below that I do see ` ` - wonder if that has anything to do with it (although my data is appearing left aligned)
type: AnswerComment
comment on: http://stackoverflow.com/a/49903930
score: 1

http://stackoverflow.com/a/49779989
type: AcceptedAnswer
score: 5
has comment: http://stackoverflow.com/comment/124533333
downvote count: 0
answers question: http://stackoverflow.com/q/49769546
upvote count: 5
has body: The question looks like "what function is there to calculate the confidence interval". As the given data is in normal distribution, this can be done simply by ci = scipy.stats.norm.interval(0.95, loc=0, scale=1) 0.95 is the alpha value, which specifies a 95 percentile point, as the corresponding 1.96 standard deviations of the mean is given in the formula. (https://en.wikipedia.org/wiki/1.96) the loc=0 specifies the mean value, and scale=1 is for the sigma. (https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule) You may check out @bogatron 's answer for more details on Compute a confidence interval from sample data The following code generates the plot you want. I seeded the random number for reproducibility. import pandas as pd import numpy as np import statsmodels.stats.api as sms import matplotlib.pyplot as plt import scipy s = np.random.seed(100) s= np.random.normal(0,1,2000) plt.figure() _ = plt.hist(s, bins=100) sigma=1 mean=0 ci = scipy.stats.norm.interval(0.95, loc=mean, scale=sigma) print(ci) # cnfidence interval left line one_x12, one_y12 = [ci[0],ci[0]], [0, 20] # cnfidence interval right line two_x12, two_y12 = [ci[1],ci[1]], [0, 20] plt.plot(one_x12, one_y12, two_x12, two_y12, marker = 'o') ci returns (-1.959963984540054, 1.959963984540054) And here is the plot.
type: Answer
accepted answer of: http://stackoverflow.com/q/49769546

http://stackoverflow.com/comment/86843693
type: QuestionComment
type: Comment
has text: @cr3 I totally get your point , my case was that I have a single framework setup for parsing response for all api's in my project , and each api has different messageType in that case i guess checking only `content-type` would be helpful !
comment on: http://stackoverflow.com/q/49906690
score: 0

http://stackoverflow.com/comment/86786268
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49884999
has text: are your values being read in as strings instead of actual floats? You likely need to convert them to numbers with `pd.to_numeric()`. It shouldn't have an issue with the `E+` notation
type: Comment

http://stackoverflow.com/a/49857733
upvote count: 17
answers question: http://stackoverflow.com/q/49857585
type: Answer
score: 17
has body: Since you are storing the school's slug in the URL, it would be better to leave the school field out of the form. Then you can set the school in the form_valid method: from django.shortcuts import get_object_or_404 class StudentCreateView(CreateView): fields = ("name","age",) # don't include 'school' here ... def form_valid(self, form): school = get_object_or_404(School, slug=self.kwargs['school']) form.instance.school = school return super(StudentCreateView, self).form_valid(form)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49857585

http://stackoverflow.com/q/49910683
tagged with: temperature
tagged with: python
has body: I'm reading in multiple files and want to convert a temperature column using pd.read_table converters. The function I'm using to convert Kelvin to Farenheit works on its own, but doesn't work when using the converters parameter. I get a TypeError: unsupported operand type(s) for -: 'str' and 'float'. Currently, my DataFrame looks like this temp date 2006-01-01 294.6 2006-02-01 294.1... df['temp'].dtype is dtype('float64') My function: def k2f(df): return (df-273.15)*1.8+32.00 #also tried lambda x : (x-273.15)*1.8+32.00 Using function on its own: &gt;&gt;&gt;k2f(df) temp date 2006-01-01 70.61 2006-02-01 69.71... How I read in my datafile, df=...: df = pd.read_table('pathto.txt',skiprows=9,delimiter='\s+', usecols=(0,4),index_col=(0), names=('date','temp'),na_values=('na'),parse_dates=True, converters={4:k2f}) #also tried 'temp' keyword to same result Full error message when using df=... above: Traceback (most recent call last): File "mycode.py", line 24, in &lt;module&gt; df = pd.read_table('pathto.txt',skiprows=9,delimiter='\s+',usecols=(0,4),index_col=(0),names=('date','temp'),na_values=('na'),parse_dates=True,converters={4:k2f}) File "/usr/local/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py", line 655, in parser_f return _read(filepath_or_buffer, kwds) File "/usr/local/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py", line 411, in _read data = parser.read(nrows) File "/usr/local/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py", line 982, in read ret = self._engine.read(nrows) File "/usr/local/anaconda2/lib/python2.7/site-packages/pandas/io/parsers.py", line 1719, in read data = self._reader.read(nrows) File "pandas/_libs/parsers.pyx", line 890, in pandas._libs.parsers.TextReader.read (pandas/_libs/parsers.c:10862) File "pandas/_libs/parsers.pyx", line 912, in pandas._libs.parsers.TextReader._read_low_memory (pandas/_libs/parsers.c:11138) File "pandas/_libs/parsers.pyx", line 989, in pandas._libs.parsers.TextReader._read_rows (pan…
tagged with: parameters
score: 0
has title: Pandas- TypeError when using pd.read_table parameter, 'converters'
has comment: http://stackoverflow.com/comment/86874362
tagged with: pandas
tagged with: converters
answer count: 1
has answer: http://stackoverflow.com/a/49911443
type: Question
has comment: http://stackoverflow.com/comment/86838706
type: UnansweredQuestion

http://stackoverflow.com/a/56264202
upvote count: 29
answers question: http://stackoverflow.com/q/49797658
score: 27
has comment: http://stackoverflow.com/comment/121453481
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49797658
has comment: http://stackoverflow.com/comment/126759623
downvote count: 2
has body: My solution is to make a function f() which performs the f-string interpolation after gettext has been called. from copy import copy from inspect import currentframe def f(s: str) -> str: frame = currentframe().f_back return eval(f"f'{s}'", copy(frame.f_globals) | frame.f_locals) Now you just wrap _(...) in f() and don’t preface the string with an f: f(_('Hey, {username}')) Note of caution I’m usually against the use of eval as it could make the function potentially unsafe, but I personally think it should be justified here, so long as you’re aware of what’s being formatted. That said use at your own risk. Remember This isn’t a perfect solution, this is just my solution. As per PEP 498 states each formatting method “have their advantages, but in addition have disadvantages” including this. For example if you need to change the expression inside the string then it will no longer match, therefore not be translated unless you also update your .po file as well. Also if you’re not the one translating them and you use an expression that’s hard to decipher what the outcome will be then that can cause miscommunication or other issues in translation.
has comment: http://stackoverflow.com/comment/136447684
type: Answer
has comment: http://stackoverflow.com/comment/124847879
has comment: http://stackoverflow.com/comment/126759517

http://stackoverflow.com/comment/86727945
type: QuestionComment
score: 0
has text: Yes I have, I have written code for Grayscale, blending the image to centre, transparency strength and scaling image but I tried putting them all together but it doesn't seem to finish the task....it stops short...like I am able to overlay image in centre and grey scale the image but that seems to be it, it won't scale the image up or down and transparency level doesn't go up or down.
comment on: http://stackoverflow.com/q/49841113
type: Comment

http://stackoverflow.com/q/49817234
has body: I'd like to mock an OverflowError because I'd like to test the value of a variable is after that exception is raised. However, I do not know how to replicate an OverflowError with the libraries I am using. Libraries I am using in this specific test is pysolar.solar specifically the get_altitude, get_azimuth and radiation methods After mindlessly trying out different numbers to try to simulate an OverflowError I decided to try out Mocking the function and introducing a side effect. Code I am testing sunposition.py import numpy as np import pandas as pd from pysolar.solar import get_altitude, get_azimuth, radiation as radiation_module def sun_position(lat: float, lon: float, time: pd.Timestamp = None) -&gt; List[float]: if time is None: time = pd.Timestamp.now(tz='UTC') dt = time.to_pydatetime() altitude = get_altitude(lat, lon, dt) azimuth = get_azimuth(lat, lon, dt) try: radiation = radiation_module.get_radiation_direct(dt, altitude) except OverflowError: radiation = np.nan return pd.Series([altitude, azimuth, radiation], index=['Alt', 'Azi', 'Rad']) **What I started to do with patch ** """Test sunposition module""" import unittest import numpy as np import pandas as pd from unittest.mock import MagicMock, patch, Mock from bigfolder.sun import sunposition class TestSunposition(unittest.TestCase): """Test functions in sunposition.""" def test_sun_position_overflow_error(self): error_lat = 23 error_lon = 12 error_time = pd.Timestamp('2007-02-18 15:13:05', tz="UTC") mock_args = {'side_effect': OverflowError} with patch('bigfolder.sun.sunposition.sun_position', **mock_args): # run the test self.assertRaises(OverflowError, sunposition.sun_position(lat=error_lat, lon=error_lon, time=error_time)) if __name__ == '__main__': unittest.main() I was expecting it to give me and OverFlow error... and it did, however my assertion failed anyways with an OverflowError My guess is that I patched at the wrong place? I don't really understand why the test failed regardless when the err…
has title: Adding an OverflowError side effect with patch - Python
accepted answer: http://stackoverflow.com/a/49826584
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49826584
tagged with: mocking
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: patch
tagged with: unit-testing
favorite count: 0
type: Question
tagged with: exception
tagged with: python

http://stackoverflow.com/comment/126429961
score: 0
has text: It's hard to believe that it doesn't accept commas as delimiters. Yes, you can work around that, but it's ugly.
type: AnswerComment
comment on: http://stackoverflow.com/a/49824349
type: Comment

http://stackoverflow.com/comment/86854421
type: AnswerComment
has text: The latter comment is correct. As I mentioned above, the session is used to "persist cookies and certain other things across requests." Therefore you open a Session in your main code and then in the loop use this session object to execute your HTTP calls. Don't forget to close your session afterwards if the loop is not an infinite loop.
type: Comment
comment on: http://stackoverflow.com/a/49881973
score: 0

http://stackoverflow.com/a/49818081
has comment: http://stackoverflow.com/comment/123953254
score: 5
downvote count: 0
has body: TL:DR, Gif are treated as video: VideoFileclip("image.gif") and not as ImageClip("image.gif"). Working code: #!/usr/bin/env python from moviepy.editor import * video = VideoFileClip('./video.mp4') watermark = VideoFileclip("./image.gif") watermaked = CompositeVideoClip([video, watermark], size=video.size) watermaked.write_videofile('./gif_output.mp4', fps=30, threads=1)
answers question: http://stackoverflow.com/q/49817845
upvote count: 5
type: Answer

http://stackoverflow.com/comment/86697284
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49833276
has text: I have been able to scrap the dynamic content. However, it returns only the content on the first page. The other contents are paginated and they have the same url.

http://stackoverflow.com/q/49914497
has comment: http://stackoverflow.com/comment/86844626
has answer: http://stackoverflow.com/a/49914569
has title: Python: next() function returns unexpected 'None'
has comment: http://stackoverflow.com/comment/86844667
tagged with: python
score: -1
type: AnsweredQuestion
tagged with: iterator
possible better answer: http://stackoverflow.com/a/49914569
answer count: 2
has body: it's my first question ever so I'll try to be as clear as I can. I noticed the next() functions and it seems a more elegant solution to use than the classical nested loop. So I run a simple code: liste=['foo','bar','baz'] try: G= (print(x) for x in liste) print(next(G)) print(next(G)) print(next(G)) print(next(G)) except StopIteration: print("That was obviously expected") And I'm expecting: foo bar baz That was obviously expected to appear on my screen, but instead I got: foo None bar None baz None That was obviously expected So my question(s) is simple: Why are there None responses after run ? What is the good way and when is it the good moment to use next() ? Thanks
upvote count: 0
has comment: http://stackoverflow.com/comment/86844585
downvote count: 1
accepted answer: http://stackoverflow.com/a/49914585
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49914585

http://stackoverflow.com/a/49761029
has comment: http://stackoverflow.com/comment/86541193
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86537400
downvote count: 0
answers question: http://stackoverflow.com/q/49760907
has body: If you want to preserve duplicates like this, you can't just call max, you have to compare each value to the result of max. The most readable way to do this is probably to build a dict mapping keys to max lengths, and then compare each tuple against that: result = [] for name, sublist in my_list_of_tuples: d = {} for key, subsub in sublist: if len(subsub) &gt; d.get(key, 0): d[key] = len(subsub) lst =[(key, subsub) for key, subsub in sublist if len(subsub) == d[key]] result.append((name, lst)) You can condense most parts of this down, but it'll probably only make things more opaque and less maintainable. And notice that the naive way to condense a two-pass loop into a single expression (where you calculate max each time through) converts it into a nested (quadratic) loop, so it's going to be even more verbose than you think. Since you've completely changed the problem and now apparently want only the longest sublist (presumably picking arbitrarily when there are duplicates, or non-duplicate-but-same-length values?), things are simpler: result = [] for name, sublist in my_list_of_tuples: keysubsub = max(sublist, key=lambda keysubsub: len(keysubsub[1])) result.append((name, keysubsub)) But that's basically what you already had. You say the problem with it is "… but that does not work for fred, because the max function only returns one item", but I'm not sure what you want instead of one item. If what you're looking for is all distinct lists of the maximum length, you can use a set or OrderedSet instead of a list in the first answer. There's no OrderedSet in the stdlib, but this recipe by Raymond Hettinger should be fine for our purposes. But let's do it manually with a set and a list: result = [] for name, sublist in my_list_of_tuples: d = {} for key, subsub in sublist: if len(subsub) &gt; d.get(key, 0): d[key] = len(subsub) lst, seen = [], set() for key, subsub in sublist: if len(subsub) == d[key] and tuple(subsub) not in seen: seen.add(tuple(subsub)) lst.append((key…
has comment: http://stackoverflow.com/comment/86541694
has comment: http://stackoverflow.com/comment/86542031
has comment: http://stackoverflow.com/comment/86537473
has comment: http://stackoverflow.com/comment/86541350
type: Answer
has comment: http://stackoverflow.com/comment/86541544

http://stackoverflow.com/q/49876024
tagged with: keras
has answer: http://stackoverflow.com/a/53537719
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 3
answer count: 3
has title: Replicating RegisterGradient and gradient_override_map in Keras
upvote count: 3
has answer: http://stackoverflow.com/a/49876121
has comment: http://stackoverflow.com/comment/86767782
has body: Following is the code for registering a gradient and overriding an operation's gradient in tensorflow. # Registering a gradient some_multiplier = 0.5 @tf.RegisterGradient("AdaGrad") def _ada_grad(op, grad): return grad * some_multiplier # Overriding g = tf.get_default_graph() with g.gradient_override_map({"Ada": "AdaGrad"}): model.loss = tf.identity(model.loss, name="Ada") I want to replicate the same thing in keras. I couldn't find any way to do it after searching a lot of things. I tried the following code but it didn't work. The gradient is not being modified. I got the same result with and without gradient override. I checked it with setting some_multiplier to zero. model = Model(...) # Keras model model.compile(loss='sparse_categorical_crossentropy', optimizer=adadelta, metrics=['accuracy']) # Compiling Keras Model @tf.RegisterGradient("AdaGrad") def _ada_grad(op, grad): return grad * some_multiplier g = tf.get_default_graph() with g.gradient_override_map({"Ada": "AdaGrad"}): model.total_loss = tf.identity(model.total_loss, name="Ada")
has answer: http://stackoverflow.com/a/53909904

http://stackoverflow.com/comment/129021237
comment on: http://stackoverflow.com/q/49768770
score: 0
type: Comment
has text: Not sure if you/anyone insist on the `Brew` python version, i wasn't. so I installed the latest version directly from https://www.python.org/downloads/macos/, double click - and that's it. everything works.
type: QuestionComment

http://stackoverflow.com/comment/86687989
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49832802
has text: Thanks so much! I can't believe I didn't think of that. much appreciated!

http://stackoverflow.com/comment/86754040
type: QuestionComment
comment on: http://stackoverflow.com/q/49869328
score: 0
has text: Do read the article @TwistedSim linked to: floats are stored in a binary format, and 1/5 cannot be represented exactly in any finite number of binary digits (just as 1/3 cannot be represented exactly in any finite number of decimal digits).
type: Comment

http://stackoverflow.com/q/49911320
favorite count: 0
has title: Unexpected padding on wrapped QLabel in custom class
type: Question
tagged with: padding
accepted answer: http://stackoverflow.com/a/49911561
tagged with: pyqt
linked to: http://stackoverflow.com/q/29504589
downvote count: 0
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/49911561
answer count: 1
has body: I want to display a border around a QWidget that wraps a QLabel (this is practice for a more complicated widget). I'm using setStyleSheet to create the border. When I did this manually, it worked as expected. However, when I moved the code into its own class (derived from QWidget), the padding is different, and I can't figure out why. import sys from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QMainWindow, QVBoxLayout class WrappedLabel(QWidget): def __init__(self, text=''): super().__init__() self.text = QLabel(text) layout = QVBoxLayout() layout.addWidget(self.text) self.setLayout(layout) self.setStyleSheet('padding: 2px; border: 2px solid red;') class Shell(QMainWindow): def __init__(self): # constructor super().__init__() # call the parent's constructor w = QWidget() # Create the main window content widget self.setCentralWidget(w) # First label unwrapped_label = QLabel('This is a normal QLabel with a border and no padding.') unwrapped_label.setStyleSheet('border: 2px solid gray; padding: 2px;') # Second label wrapped_label = QLabel('This QLabel is manually wrapped in a styled QWidget. ' + 'There is a slight indent compared to the normal QLabel due to padding.') wrapped_layout = QVBoxLayout() wrapped_layout.addWidget(wrapped_label) manual_wrapper = QWidget() manual_wrapper.setObjectName('wrapper') manual_wrapper.setLayout(wrapped_layout) self.setStyleSheet('QWidget#wrapper { border: 2px solid gray; padding: 2px; }') # Third label derived_wrapper = WrappedLabel('This class derives from QWidget and wraps a QLabel like above, but is indented even further and the border is in the wrong spot.') vbox = QVBoxLayout() vbox.addWidget(unwrapped_label) vbox.addWidget(manual_wrapper) vbox.addWidget(derived_wrapper) vbox.addStretch(1) # Squish them together to better see the spacing w.setLayout(vbox) # Setup the rest of the main window appearance self.setGeometry(300,300,640,180) self.setWindowTitle('Testing wrapped labels') self.show() if __name__ == '__main__': ap…
tagged with: pyqt5

http://stackoverflow.com/q/49786024
has answer: http://stackoverflow.com/a/49786352
has answer: http://stackoverflow.com/a/49786134
has answer: http://stackoverflow.com/a/49786150
favorite count: 0
type: Question
has body: I have a dataframe as follows: input_df: name name_group value foo1 a 2 foo2 a 2 foo3 a 2 foo4 a 2 bar1 b bar2 b bar3 b buzz1 c 6 buzz2 c 6 buzz3 c 6 buzz4 c 6 buzz5 c 6 Where every row in each name_group has the same "value", so in this case every name in name_group "a" has the same "value", every name in name_group "b" has the same "value", etc. I want to create a new column "new_vals" that is equal to the min(# of rows in that "name_group", "value" column). If there are missing values in the "value" column for any "name_group", it should just use the # of rows in that "name_group". For my example dataframe, the desired output is: output_df: name name_group value new_vals foo1 a 2 2 foo2 a 2 2 foo3 a 2 2 foo4 a 2 2 bar1 b 3 bar2 b 3 bar3 b 3 buzz1 c 6 5 buzz2 c 6 5 buzz3 c 6 5 buzz4 c 6 5 buzz5 c 6 5 Currently, the way I am achieving this is by looping through each unique value in the "name_group" column, finding the # of rows in that name_group, comparing it to the value in the "value" column, then setting the value of the "new_val" column based on the min value between the two. The results of this for each "name_group" are concatenated to another dataframe until i have my final output. While this method works, I feel as though there must be a more efficient way to do this rather than taking subsets the starting dataframe, processing each "name_group" separately, then combining everything back together. Does anyone have a more pythonic/efficient way of reproducing this functionality? Here's some code reflecting my current process: output_df = pd.DataFrame() for name_group in input_df['name_group'].unique(): # process the data one name group at a time temp_df = input_df.loc[input_df['name_group'] == name_group] max_val = temp_df['value'].max() name_group_cnt = temp_df.shape[0] # if the "value" column is empty, set new_val equal to the number of # rows in that name_group if max_val == '': new_val = name_group_cnt else: new_val = min(max_val, name_group_cnt) temp_df…
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: python
score: 2
has title: How do I efficiently update dataframe values by variable group based on multiple criteria?
answer count: 3
tagged with: pandas
tagged with: dataframe

http://stackoverflow.com/q/49764802
has answer: http://stackoverflow.com/a/49764960
has answer: http://stackoverflow.com/a/49803394
accepted answer: http://stackoverflow.com/a/49764960
type: Question
tagged with: python-import
answer count: 3
downvote count: 0
has title: Get module name programmatically with only PyPI package name
has body: I want to programmatically install and import packages based on a list of package names. For most packages, this is no problem since the package and module names are the same. However, the PyYAML package is one exception since its module is called simply yaml and there are probably more exceptions. Here is the python function I use to install and import the packages/modules: def install_and_import(package): import importlib try: importlib.import_module(package) #needs module name! except ImportError: import pip pip.main(['install', package]) #needs package name finally: globals()[package] = importlib.import_module(package) Calling the function for each package in this list, ['backoff', 'pyyaml'] (parsed from requirements.txt), I get: Collecting backoff Installing collected packages: backoff Successfully installed backoff-1.4.3 Collecting pyyaml Installing collected packages: pyyaml Successfully installed pyyaml-3.12 [...Trackback...] ModuleNotFoundError: No module named 'pyyaml' Is there a way, given just the package name (e.g., pyyaml), to find out the name of the module I actually need to import (e.g., yaml)?
favorite count: 0
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: python-packaging
possible better answer: http://stackoverflow.com/a/73292884
tagged with: python
has answer: http://stackoverflow.com/a/73292884

http://stackoverflow.com/a/49850051
downvote count: 0
has body: You cannot get access to Password field because it's not present on main page. To handle Password field you have to click Login button to get to Login page. Also you need to switch to iframe which contains authentication form from selenium.webdriver.support.ui import WebDriverWait as wait from selenium.webdriver.support import expected_conditions as EC driver.get("https://www.santandertotta.pt/pt_PT/Particulares.html") driver.find_element_by_xpath("//input[@title='Login de Particulares']").click() wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("ws")) user = driver.find_element_by_name("identificacionUsuario") user.send_keys("user") pas = driver.find_element_by_name("claveConsultiva") pas.send_keys("password") pas.submit()
upvote count: 8
answers question: http://stackoverflow.com/q/49848175
type: Answer
score: 8

http://stackoverflow.com/q/49783331
tagged with: function
has comment: http://stackoverflow.com/comment/86582657
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86582929
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49783418
has comment: http://stackoverflow.com/comment/86582058
tagged with: overloading
has answer: http://stackoverflow.com/a/49783418
has body: Imagine I have a two functions def areaSquare(a,b): print( a * b) def areaCircle(radius): print(3.14159 * radius ** 2) And I want to create a third function that is called area. area(areaCircle,radius = 3, repeat = 5) # prints 3.14159 * 9 five times area(areaSquare, a = 2, b = 3, repeat = 6) # prints 2 * 6 six times So the function takes a function as a parameter. Depending on the function which is passed to it as a parameter, it should require additional parameters. Is there a way to achieve this? I know function overloading would be an option. But I do not want to define multiple functions for this purpose.
tagged with: python
has title: Python A function that takes a function as a parameter with its parameters
has comment: http://stackoverflow.com/comment/86582021
tagged with: parameters
has comment: http://stackoverflow.com/comment/86582007
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6289646
score: 0

http://stackoverflow.com/comment/86727469
type: AnswerComment
has text: Hmm i did make that error and have changed the code yet I still get an error. https://pastebin.com/HeUjJ0cp
comment on: http://stackoverflow.com/a/49854836
type: Comment
score: 0

http://stackoverflow.com/comment/86802896
type: Comment
has text: @pissall Do you want your view function to return html and json both? I think your view return is fine. Are you sure you passing the correct get parameter to your view ? like this `localhost:5000/test?type=json`
score: 0
comment on: http://stackoverflow.com/q/49893574
type: QuestionComment

http://stackoverflow.com/comment/86647790
comment on: http://stackoverflow.com/q/49816258
has text: Only generate those combinations of badges that have an effect less than three times. It isn't hard to write and it will beat calling `combinations` and filtering.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86645094
has text: Cheers it helped.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49798962

http://stackoverflow.com/comment/86550206
score: 0
type: Comment
type: QuestionComment
has text: can you provide the csv file as well?
comment on: http://stackoverflow.com/q/49767477

http://stackoverflow.com/comment/86644759
comment on: http://stackoverflow.com/a/49812118
type: AnswerComment
score: 0
type: Comment
has text: Since I am taking the random numbers (integers) between 1 to 11 that does simulates the actual dice sum which can vary between 2 to 12.

http://stackoverflow.com/comment/86570295
score: 0
has text: the last 3rd 2nd code there is a mark "#Here is the error""
type: Comment
comment on: http://stackoverflow.com/q/49777533
type: QuestionComment

http://stackoverflow.com/q/49805514
answer count: 1
has answer: http://stackoverflow.com/a/49921665
favorite count: 0
type: Question
tagged with: c++
tagged with: blob
type: UnansweredQuestion
downvote count: 2
upvote count: 5
linked to: http://stackoverflow.com/q/15693900
has comment: http://stackoverflow.com/comment/86626543
tagged with: python
has title: Extract biggest blob with opencv
tagged with: opencv
score: 3
has comment: http://stackoverflow.com/comment/86659672
has body: I have a binary image depicting humans as white blobs and the background as black. I want to "crop" the biggest (or the 3 biggest) blobs from the big image using opencv. How would one go around doing this?

http://stackoverflow.com/comment/86747496
comment on: http://stackoverflow.com/q/49865981
score: 0
type: Comment
has text: @poke right so i think the crux of my question was: when you do `B(A)`, `foo` isn't added to `B`'s namespace, rather `__dict__` contains all the attributes that were created specifically within `B` and not inherited from elsewhere, yeh?
type: QuestionComment

http://stackoverflow.com/a/49884886
answers question: http://stackoverflow.com/q/49863514
score: 0
has body: possibly add a condition to test if there is a line. remember you are looking for lines of a particular length. the second image has none. i tried your code and commented minLineLength = img.shape[1] - 300 your code works with only particluar images. if you need to use any image comment out the lines #img = img[:, 10:img.shape[1]-10] minLineLength = 10 #img.shape[1] - 300 it works if this is the case the final code i executed is import cv2 import numpy as np img = cv2.imread('test.jpg') #img = img[:, 10:img.shape[1]-10] gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize=3) minLineLength = 20 #img.shape[1] - 300 lines = cv2.HoughLinesP(image=edges, rho=0.02, theta=np.pi / 500, threshold=10, lines=np.array([]), minLineLength=minLineLength, maxLineGap=2) a, b, c = lines.shape for i in range(a): cv2.line(img, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 2, cv2.LINE_AA) cv2.imwrite('result.png', img)
has comment: http://stackoverflow.com/comment/86786403
type: Answer

http://stackoverflow.com/comment/86671937
has text: Hint: Replace `pattern.match` with `pattern.search`.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49828266

http://stackoverflow.com/comment/86726808
score: 0
type: Comment
has text: Did you get an error? Remember, you have to click `btn4` before `cb_get()` is ever called.
type: AnswerComment
comment on: http://stackoverflow.com/a/49855884

http://stackoverflow.com/q/49895360
has answer: http://stackoverflow.com/a/49895494
tagged with: pandas
score: 1
tagged with: python
favorite count: 0
type: Question
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49895494
has body: How can I get top5 max() values per month? CUrrently, I'm getting the max value for each month. df1 = df['balance'].resample('M').max()
has title: How can I get top5 max() values per month pandas
type: AnsweredQuestion

http://stackoverflow.com/comment/86707962
comment on: http://stackoverflow.com/q/49846491
has text: I ... err ... you don't. Time deltas are _not_ times. They are _lengths of time_. If you have a datetime, and you add/subtract a time delta, you get a new datetime, but the timedelta's themselves do not represent any specific point in time. You're asking "what time is three minutes?" That doesn't make any sense without a reference, IE "three minutes from _when_?"
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86750455
type: Comment
comment on: http://stackoverflow.com/a/49867397
type: AnswerComment
score: 0
has text: I have so many values in my list (20000 values) that i didn't notice that one of them was an INF, thx

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/49850182
tags question: http://stackoverflow.com/q/49888686
tags question: http://stackoverflow.com/q/49874921
tags question: http://stackoverflow.com/q/49894411
tags question: http://stackoverflow.com/q/49837155
tags question: http://stackoverflow.com/q/49896064
tags question: http://stackoverflow.com/q/49915867
tags question: http://stackoverflow.com/q/49916289
tags question: http://stackoverflow.com/q/49880276
tags question: http://stackoverflow.com/q/49782433
type: Tag
tags question: http://stackoverflow.com/q/49889137

http://stackoverflow.com/a/49765403
upvote count: 1
has body: As df['nullsum'] is a Series, and such comparison is not possible, it throws an error. You would want to compare the value of nullsum at every row. df['mean']= df.apply(lambda x: np.mean(x[:3]) if x['nullsum'] &lt; 2 else np.nan,axis=1) Here x takes row by row, so x['nullsum'] gives the value at that particular row.
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49765266
downvote count: 0

http://stackoverflow.com/a/49887004
upvote count: 1
has comment: http://stackoverflow.com/comment/86823762
has comment: http://stackoverflow.com/comment/86791939
has comment: http://stackoverflow.com/comment/86791883
answers question: http://stackoverflow.com/q/49886726
type: Answer
has comment: http://stackoverflow.com/comment/86802052
has body: a is of type Sequence[Any] not str. If you are sure that a will always be a string, you can cast the type with print_str(cast(str, a)). _S = Sequence[Any] def process_sequence(s: _S) -&gt; _S: return s def print_str(word: str): print(word) def print_sequence_of_ints(ints: Sequence[int]): for i in ints: print(i) a = process_sequence("spam") print_str(a) # a is of type Sequence[Any] not str a = process_sequence([1,2,3,42]) print_sequence_of_ints(a) You can also use T = TypeVar('T') instead of Sequence[Any], but you lose some typing information and protection.
score: 1
downvote count: 0

http://stackoverflow.com/a/49834407
has comment: http://stackoverflow.com/comment/86684342
has body: Create an array of unique days that are holidays and offset them by one day days = pd.Series(df[df.Holiday == 1].index).add(pd.DateOffset(1)).dt.date.unique() Create a new column with the one day holiday offsets (days) df['DayAfter'] = np.where(pd.Series(df.index).dt.date.isin(days),1,0) Holiday AnyNumber DayAfter Datum 2014-01-01 20:00:00 1 9 0 2014-01-01 20:30:00 1 2 0 2014-01-01 21:00:00 1 3 0 2014-01-01 21:30:00 1 3 0 2014-01-01 22:00:00 1 6 0 2014-01-01 22:30:00 1 1 0 2014-01-01 23:00:00 1 1 0 2014-01-01 23:30:00 1 1 0 2014-01-02 00:00:00 0 1 1 2014-01-02 00:30:00 0 2 1 2014-01-02 01:00:00 0 1 1 2014-01-02 01:30:00 0 1 1
accepted answer of: http://stackoverflow.com/q/49833339
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49833339

http://stackoverflow.com/comment/86705311
type: Comment
comment on: http://stackoverflow.com/a/49834494
score: 0
type: AnswerComment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169035/discussion-between-keyur-potdar-and-yadav).

http://stackoverflow.com/q/49889399
has title: Page not found (404) - Django urls and views
answer count: 1
has answer: http://stackoverflow.com/a/49889761
accepted answer: http://stackoverflow.com/a/49889761
favorite count: 0
type: Question
has body: I'm trying to make a web server with Django for making "parrot bot". I'm using python3.5 Django apache2.4 The error I'm getting : Page not found (404) Request Method: GET Request URL: http://54.95.30.145/ Using the URLconf defined in bot.urls, Django tried these URL patterns, in this order: ^keyboard/ ^message The empty path didn't match any of these. This is my project bot/urls.py code. from django.conf.urls import url, include urlpatterns = [ url(r'',include('inform.urls')), ] This is my app inform/urls.py code. from django.conf.urls import url from . import views urlpatterns = [ url(r'^keyboard/',views.keyboard), url(r'^message',views.message), ] This is my inform/views.py code. from django.http import JsonResponse def keyboard(request): return JsonResponse({ 'type' : 'text', }) def message(request): message = ((request.body).decode('utf-8')) return_json_str = json.loads(message) return_str = return_json_str['contetn'] return JsonResponse({ 'message': { 'text' : return_str } }) Please help me.
tagged with: webserver
tagged with: django
tagged with: django-urls
tagged with: python
type: AnsweredQuestion
tagged with: django-views
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86823973
comment on: http://stackoverflow.com/q/49902236
score: 0
type: QuestionComment
has text: Yes, the best [MCVE](https://stackoverflow.com/help/mcve) is where we can just paste the code into IPython (maybe after creating an input data file) and then tinkering.
type: Comment

aes
tag name: aes
tags question: http://stackoverflow.com/q/49767968
type: Tag

http://stackoverflow.com/a/49920851
upvote count: 2
downvote count: 0
type: Answer
has body: If somebody is interested: I have approximated it now with an integral of the distributions (unfortunately not quite the 1-liner I was searching for): data1 = np.random.normal(size=9000) data2 = np.random.normal(size=5000, loc=0.5, scale=1.5) num_bins = 100 xmin = min(data1.min(), data2.min()) xmax = max(data1.max(), data2.max()) bins = np.linspace(xmin, xmax, num_bins) weights1 = np.ones_like(data1) / float(len(data1)) weights2 = np.ones_like(data2) / float(len(data2)) hist_1 = np.histogram(data1, bins, weights=weights1)[0] hist_2 = np.histogram(data2, bins, weights=weights2)[0] tvd = 0.5*sum(abs(hist_1 - hist_2)) print("overlap: {:2.2f} percent".format((1-tvd)*100)) plt.figure() ax = plt.gca() ax.hist(data1, bins, weights=weights1, color='red', edgecolor='white', alpha=0.5)[0] ax.hist(data2, bins, weights=weights2, color='blue', edgecolor='white', alpha=0.5)[0] plt.show()
has comment: http://stackoverflow.com/comment/117421919
score: 2
answers question: http://stackoverflow.com/q/49880306

http://stackoverflow.com/comment/86830112
type: Comment
type: QuestionComment
has text: You can't. Sleep does exactly what it says, it puts your entire program to sleep (meaning: it can't respond to mouse and keyboard events)
comment on: http://stackoverflow.com/q/49906993
score: 2

http://stackoverflow.com/q/49806884
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/87278596
has comment: http://stackoverflow.com/comment/86885382
has comment: http://stackoverflow.com/comment/87541068
tagged with: python
has title: Scrapy spider cannot crawl a url but scrapy shell does it successfully
has comment: http://stackoverflow.com/comment/87501832
score: 3
upvote count: 3
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/50325314
tagged with: web-scraping
tagged with: scrapy
favorite count: 0
type: Question
tagged with: craigslist
has comment: http://stackoverflow.com/comment/87218153
has comment: http://stackoverflow.com/comment/87616521
has comment: http://stackoverflow.com/comment/87666257
has body: I am trying to scrape craiglist. When I try to fetch https://tampa.craigslist.org/search/jjj?query=bookkeeper in the spider I am getting the following error: (extra newlines and white space added for readability) [scrapy.downloadermiddlewares.retry] DEBUG: Retrying &lt;GET https://tampa.craigslist.org/search/jjj?query=bookkeeper&gt; (failed 1 times): [&lt;twisted.python.failure.Failure twisted.internet.error.ConnectionLost: Connection to the other side was lost in a non-clean fashion: Connection lost.&gt;] But, when I try to crawl it on scrapy shell, it is being crawled successfully. [scrapy.core.engine] DEBUG: Crawled (200) &lt;GET https://tampa.craigslist.org/search/jjj?query=bookkeeper&gt; (referer: None) I don't know what I am doing wrong here. I have tried forcing TLSv1.2 but had no luck. I would really appreciate your help. Thanks!
has comment: http://stackoverflow.com/comment/87080362
has comment: http://stackoverflow.com/comment/87218036

http://stackoverflow.com/q/49835133
type: AnsweredQuestion
tagged with: python-2.7
has body: I have two independent python modules running in the background on my device. Even though I need them to be independent, I need some string data transferred from one to the other every few seconds. I'm currently doing it by writing the data into a text file which is constantly being monitored by the two. Is there any better way to do it? Something faster, more secure if possible.
accepted answer: http://stackoverflow.com/a/49835259
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86685384
has comment: http://stackoverflow.com/comment/86685414
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49835259
has comment: http://stackoverflow.com/comment/86685458
has comment: http://stackoverflow.com/comment/86685408
tagged with: python
has comment: http://stackoverflow.com/comment/86685383
tagged with: data-transfer
has title: What are some good ways to transfer data between two independent python programs?
score: 2

http://stackoverflow.com/comment/86767601
type: QuestionComment
has text: how do you want to resolve ties? `{'id': 255, ..` and `{'id': 257..` have the same sum (`110`).
comment on: http://stackoverflow.com/q/49875939
score: 2
type: Comment

http://stackoverflow.com/comment/86847932
has text: try to fix the indentation on your code
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49916232
type: QuestionComment

http://stackoverflow.com/q/49894820
downvote count: 0
has comment: http://stackoverflow.com/comment/88780781
favorite count: 0
type: Question
has body: I`m working on creating an exe file to distribute the pycharm project. This project contains PyQt5. I am using pyinstaller and I have the following problems. C:\Users\mskim\PycharmProjects\DataGathering&gt;pyinstaller Main.py 203 INFO: PyInstaller: 3.3.1 203 INFO: Python: 3.6.5 218 INFO: Platform: Windows-10-10.0.16299-SP0 234 INFO: wrote C:\Users\mskim\PycharmProjects\DataGathering\Main.spec 234 INFO: UPX is not available. 234 INFO: Extending PYTHONPATH with paths ['C:\\Users\\mskim\\PycharmProjects\\DataGathering', 'C:\\Users\\mskim\\PycharmProjects\\DataGathering'] 234 INFO: checking Analysis 234 INFO: Building Analysis because out00-Analysis.toc is non existent 234 INFO: Initializing module dependency graph... 250 INFO: Initializing module graph hooks... 250 INFO: Analyzing base_library.zip ... 3201 INFO: running Analysis out00-Analysis.toc 3201 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable required by c:\program files\python36\python.exe 4017 INFO: Caching module hooks... 4017 INFO: Analyzing C:\Users\mskim\PycharmProjects\DataGathering\Main.py 4695 INFO: Processing pre-find module path hook distutils 5774 INFO: Processing pre-find module path hook site 5774 INFO: site: retargeting to fake-dir 'c:\\program files\\python36\\lib\\site-packages\\PyInstaller\\fake-modules' 9034 INFO: Processing pre-safe import module hook six.moves 20155 INFO: Processing pre-find module path hook PyQt5.uic.port_v3 20171 INFO: Processing pre-find module path hook PyQt5.uic.port_v2 20249 INFO: Loading module hooks... 20249 INFO: Loading module hook "hook-cv2.py"... 20265 INFO: Loading module hook "hook-distutils.py"... 20265 INFO: Loading module hook "hook-encodings.py"... 20381 INFO: Loading module hook "hook-lib2to3.py"... 20397 INFO: Loading module hook "hook-matplotlib.backends.py"... 21049 INFO: Matplotlib backend "GTK": ignored Gtk* backend requires pygtk to be installed. 21539 INFO: Matplotlib backend "GTKAgg": ignored Gtk* backend …
tagged with: python
tagged with: pyinstaller
type: UnansweredQuestion
has title: pyinstaller lib not found, Matplotlib, etc
answer count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/86580579
comment on: http://stackoverflow.com/q/49782514
score: 0
type: Comment
has text: What exactly do you mean by `copy the result` ?
type: QuestionComment

http://stackoverflow.com/a/49864393
type: Answer
answers question: http://stackoverflow.com/q/49863243
has body: string = ["panda","shark","python"] df["b"] = df["a"].apply(lambda y:[x for x in string if x in y][0] if len([x for x in string if x in y])==1 else "") Output: a b 0 it_python 1 my_shark 2 my_shark 3 the_panda 4 my_shark 5 my_shark a b 0 it_python python 1 my_shark shark 2 my_shark shark 3 the_panda panda 4 my_shark shark 5 my_shark shark
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49863243

http://stackoverflow.com/comment/86741729
comment on: http://stackoverflow.com/q/49853578
type: QuestionComment
has text: Please explicitly state your question. I'd say it could be "_How do I make a `dok_matrix` smaller than a regular non-sparse matrix, or even a dict?_"
score: 0
type: Comment

http://stackoverflow.com/comment/86838380
has text: Try to vectorise first, eg via a package. If that fails, profile your code. If your numerical calculations are expensive you might find numba helpful.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49911183

http://stackoverflow.com/comment/86561960
has text: A single underscore at the start of a method name generally indicates it is for internal use only - see [PEP 8](https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles)
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/49773496

http://stackoverflow.com/q/49852576
has title: Upgrade Python version while running a Python program
tagged with: python-3.x
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/2547554
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/49852931
has comment: http://stackoverflow.com/comment/86719877
has body: I would like to upgrade my Python version from 2.6.6 to the newest version of 3.6.5 on a server. However, there is a program that has been running for multiple days and will be running for a week or more. Will my program continue to run until it finishes if I upgrade my Python version? P.S.: I ran my Python program with the screen command so I wouldn't have to stop it to be able to upgrade my Python version.
has answer: http://stackoverflow.com/a/49852745
tagged with: upgrade
tagged with: python
tagged with: python-2.x
has answer: http://stackoverflow.com/a/49853261

http://stackoverflow.com/comment/86778531
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49880545
has text: What do you want to do with the elements of `oelt`?

http://stackoverflow.com/comment/86786258
has text: It doesn't look like your csv was read correctly. It looks like the columns names were also read into the first row of the dataframe.
type: Comment
comment on: http://stackoverflow.com/q/49884740
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86615372
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49800202
type: AnswerComment
has text: This could let me get the right histogram, but I wonder could I get the new shape and scale parameters without time 1000.

http://stackoverflow.com/q/49911442
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86838865
tagged with: python
has answer: http://stackoverflow.com/a/49912041
accepted answer: http://stackoverflow.com/a/49912041
has comment: http://stackoverflow.com/comment/86852413
downvote count: 0
score: 1
upvote count: 1
tagged with: regression
answer count: 1
tagged with: scipy
has body: I'm working on a program that can calculate the slope using the linregress native scipyy function, but I'm getting two errors (depending on how I try to fix it). The two lists should be two-dimensional, basically x and y values. from __future__ import division from scipy.stats import linregress import matplotlib.pyplot as mplot import numpy as np xs=[[20.0, 80.0, 45.0, 42.0, 93.0, 98.0, 65.0, 43.0, 72.0, 36.0, 9.0, 60.0, 47.0, 84.0, 31.0, 46.0, 57.0, 76.0, 27.0, 85.0, 0.0, 39.0, 2.0, 56.0, 68.0, 6.0, 41.0, 28.0, 61.0, 12.0, 32.0, 1.0, 54.0, 77.0, 18.0, 86.0, 62.0, 23.0, 30.0, 69.0, 4.0, 71.0, 64.0, 92.0, 24.0, 79.0, 8.0, 35.0, 49.0, 53.0, 7.0, 59.0, 70.0, 37.0, 13.0, 15.0, 73.0, 89.0, 96.0, 83.0, 22.0, 95.0, 19.0, 67.0, 5.0, 88.0, 38.0, 50.0, 55.0, 52.0, 81.0, 58.0, 11.0, 51.0, 99.0, 78.0, 25.0, 33.0, 40.0, 75.0, 3.0, 91.0, 48.0, 90.0, 82.0, 26.0, 10.0, 16.0, 21.0, 66.0, 14.0, 87.0, 74.0, 97.0, 94.0, 44.0, 29.0, 17.0, 63.0, 34.0], [87.0, 17.0, 69.0, 72.0, 76.0, 62.0, 20.0, 77.0, 5.0, 49.0, 81.0, 3.0, 24.0, 36.0, 44.0, 91.0, 99.0, 35.0, 43.0, 50.0, 12.0, 54.0, 46.0, 30.0, 37.0, 45.0, 90.0, 85.0, 70.0, 83.0, 38.0, 22.0, 23.0, 0.0, 60.0, 47.0, 26.0, 1.0, 95.0, 73.0, 65.0, 94.0, 84.0, 8.0, 34.0, 56.0, 66.0, 13.0, 75.0, 52.0, 19.0, 55.0, 67.0, 39.0, 21.0, 80.0, 98.0, 33.0, 11.0, 68.0, 40.0, 32.0, 2.0, 79.0, 82.0, 93.0, 96.0, 88.0, 14.0, 92.0, 41.0, 89.0, 28.0, 29.0, 42.0, 6.0, 86.0, 74.0, 58.0, 16.0, 31.0, 64.0, 15.0, 53.0, 25.0, 59.0, 61.0, 78.0, 51.0, 7.0, 57.0, 9.0, 97.0, 63.0, 48.0, 71.0, 18.0, 10.0, 4.0, 27.0]] ys=[[155.506, 50.592, 104.447, 111.318, 36.148, 36.87, 74.266, 106.413, 58.341, 122.563, 180.555, 85.202, 96.84, 50.726, 126.56, 100.686, 88.303, 54.797, 138.487, 44.946, 200.9, 116.524, 193.652, 82.8, 65.823, 184.436, 113.738, 133.458, 83.765, 167.408, 129.491, 200.469, 89.238, 51.799, 159.217, 49.382, 78.443, 146.051, 129.045, 63.805, 185.564, 65.614, 74.243, 43.408, 140.863, 53.446, 182.767, 127.373, 94.494, 91.079, 187.194, 81.254, 68.702, 121.368, 164.75…
favorite count: 0
type: Question
has title: Python: Linregress slope and y-intercept

http://stackoverflow.com/q/49884112
favorite count: 0
tagged with: unit-testing
type: Question
has comment: http://stackoverflow.com/comment/86784918
score: 7
has body: Because LiveServerTestCase inherits from TransactionTestCase, the default behavior is to delete the test data at the end of every test method. I would like to use the LiveServerTestCase class, but preserve the test data from method to method. In this example, test2 fails because the database is truncated at the end of test1. My understanding is that if I were using TestCase, it would roll back the transactions at the end of each test and return the database to its starting condition. Is it possible for me to imitate that behavior while using the LiveServerTestCase? class TestTheTests(LiveServerTestCase): @classmethod def setUpTestData(cls): print('running setUpTestData') call_command('loaddata', 'datasources.yaml' ) @classmethod def setUpClass(cls): print('starting setUpClass') cls.setUpTestData() # load the data for the entire test class super().setUpClass() @classmethod def tearDownClass(cls): print('finished tearDownClass') super().tearDownClass() def setUp(self): self.browser = webdriver.Chrome() def tearDown(self): self.browser.quit() When I run both the tests together, this test passes: def test1(self): print('test 1 running') self.assertEquals(8, DataSource.objects.count(),'There should be 8 DataSource objects in test1') This test fails: def test2(self): print('test 2 running') self.assertEquals(8, DataSource.objects.count(),'There should be 8 DataSource objects in test2') Both would pass if the database records were not being dropped at the end of test1.
tagged with: python
has answer: http://stackoverflow.com/a/64461409
type: UnansweredQuestion
answer count: 1
downvote count: 0
has title: Preserve data across LiveServerTestCase test methods?
tagged with: django
upvote count: 7
linked to: http://stackoverflow.com/q/29378328

http://stackoverflow.com/a/50824512
score: 8
has comment: http://stackoverflow.com/comment/88698314
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88862477
downvote count: 1
has body: Updating twine solved the problem for me. For this, execute the following command before doing twine upload dist/*: python3 -m pip install --user --upgrade twine
upvote count: 9
accepted answer of: http://stackoverflow.com/q/49806586
type: Answer
answers question: http://stackoverflow.com/q/49806586

http://stackoverflow.com/comment/86699777
comment on: http://stackoverflow.com/q/49837578
type: QuestionComment
score: 0
has text: If you're using the `commands` extension, why are you processing commands in `on_message`?
type: Comment

http://stackoverflow.com/comment/86692843
type: QuestionComment
has text: @Roy_123 I can't see numpy doing any good here since converting your list to array alone takes longer than your list comprehension.
comment on: http://stackoverflow.com/q/49838872
score: 0
type: Comment

http://stackoverflow.com/a/49841151
upvote count: 2
has body: In addition to this answer by מתן ל: You can easily compare your input agains itself when reversed - list comprehension makes this trivial: Simple 1-word and case-aware test: word = "SomemoS" print(word == word[::-1]) # word[::-1] simply reverses the word and prints True if same Case insensitive and allow punctuation A palindrom is readable from both sides. Depending on the rules for palindrom-ness you might allow for ignored casing and even eleminate whitespaces and punctuation marks. apply lower() to it do not care about whitespace and punctuation word = [c.lower() for c in "No, it can assess an action." if c not in ',. !?'] print(word == word[::-1]) # True as well
downvote count: 0
answers question: http://stackoverflow.com/q/49841052
type: Answer
has comment: http://stackoverflow.com/comment/86697133
score: 2

http://stackoverflow.com/q/49835581
has answer: http://stackoverflow.com/a/49835703
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has body: I have my code like this : import xlsxwriter workbook = xlsxwriter.Workbook('result.xlsx') sheet = workbook.get_worksheet_by_name('result') but sheet always be None I have checked my result.xlsx.I'm sure result.xlsx have 'result' sheet. Why?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/68279425
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: xlsxwriter
tagged with: python
has title: xlsx get_worksheet_by_name return none?
score: 2
answer count: 2

http://stackoverflow.com/comment/86757202
comment on: http://stackoverflow.com/a/49870158
type: Comment
type: AnswerComment
score: 0
has text: @JoeyLU Yours is a pandas Series command, where as mine is a simple python inbuilt operation on string

http://stackoverflow.com/comment/86551048
has text: But why the result changes when I put "b==a"?
comment on: http://stackoverflow.com/a/49767532
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49894702
has comment: http://stackoverflow.com/comment/86811857
has body: It looks like you are missing the quotes around the filepath syntax to use near '/home/ubuntu/pythonscript/ftp/INV_COST_FEED_GARBJ_20180417_00.txt into table ftp' at line 1 See docs The file name must be given as a literal string. On Windows, specify backslashes in path names as forward slashes or doubled backslashes. The character_set_filesystem system variable controls the interpretation of the file name.
has comment: http://stackoverflow.com/comment/86807463
score: 0
has comment: http://stackoverflow.com/comment/86811402
has comment: http://stackoverflow.com/comment/86810612
has comment: http://stackoverflow.com/comment/86805245
type: Answer
has comment: http://stackoverflow.com/comment/86808015
answers question: http://stackoverflow.com/q/49894244
has comment: http://stackoverflow.com/comment/86809391
has comment: http://stackoverflow.com/comment/86815858
has comment: http://stackoverflow.com/comment/86804991

http://stackoverflow.com/a/49781984
has body: In Python 3.6+ you can use Literal String Interpolation. Creating filenames in a loop can me done in the following way: for i in range(1000, 2001): filename = f'streamflow{i}.nc' ... Regarding the other answers proposing putting an outer loop around the code above, I think that you actually want to do sth like that: for i in range(1000, 2001): filename = f'streamflow{i}.nc' # read data # Some logic here for i in range(1000, 2001): filename = f'streamflow{i}.nc' # write data (once to each file) However, if you really want/need to append some data to these files numerous times, just use an outer loop as offered in the other answers.
answers question: http://stackoverflow.com/q/49781727
type: Answer
score: 0

http://stackoverflow.com/q/49809032
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86640223
has body: I was trying to track the error of the whole data set and compute the error of the whole data set in pytorch. I wrote the following (reproducible example and fully contained) in cifar10 pytorch 0.3.1: import torch from torch.autograd import Variable import torch.optim as optim import torchvision import torchvision.transforms as transforms from math import inf from pdb import set_trace as st def error_criterion(outputs,labels): max_vals, max_indices = torch.max(outputs,1) train_error = (max_indices != labels).sum().data[0]/max_indices.size()[0] return train_error def evalaute_mdl_data_set(loss,error,net,dataloader,enable_cuda,iterations=inf): ''' Evaluate the error of the model under some loss and error with a specific data set. ''' running_loss,running_error = 0,0 for i,data in enumerate(dataloader): if i &gt;= iterations: break inputs, labels = extract_data(enable_cuda,data,wrap_in_variable=True) outputs = net(inputs) running_loss += loss(outputs,labels).data[0] running_error += error(outputs,labels) return running_loss/(i+1),running_error/(i+1) def extract_data(enable_cuda,data,wrap_in_variable=False): inputs, labels = data if enable_cuda: inputs, labels = inputs.cuda(), labels.cuda() #TODO potential speed up? if wrap_in_variable: inputs, labels = Variable(inputs), Variable(labels) return inputs, labels def train_and_track_stats(enable_cuda, nb_epochs, trainloader,testloader, net,optimizer,criterion,error_criterion, iterations=inf): ''' Add stats before training ''' train_loss_epoch, train_error_epoch = evalaute_mdl_data_set(criterion, error_criterion, net, trainloader, enable_cuda, iterations) test_loss_epoch, test_error_epoch = evalaute_mdl_data_set(criterion, error_criterion, net, testloader, enable_cuda, iterations) print(f'[-1, -1], (train_loss: {train_loss_epoch}, train error: {train_error_epoch}) , (test loss: {test_loss_epoch}, test error: {test_error_epoch})') ## ''' Start training ''' print('about to start training') for epoch in range(nb_epochs): # loop…
type: Question
accepted answer: http://stackoverflow.com/a/49812919
has answer: http://stackoverflow.com/a/49823771
answer count: 2
has title: How does one manually compute the error of the whole data set in pytorch?
tagged with: pytorch
has answer: http://stackoverflow.com/a/49812919
has comment: http://stackoverflow.com/comment/86638672
tagged with: neural-network
downvote count: 0
tagged with: machine-learning
upvote count: 1
possible better answer: http://stackoverflow.com/a/49823771
favorite count: 0
has comment: http://stackoverflow.com/comment/86663231
type: AnsweredQuestion
tagged with: conv-neural-network

http://stackoverflow.com/comment/86712861
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49811167
has text: Haha. I appreciate the help. Unfortunately, I don't think this answers the question. I could of course hard-code the value and shape of min_value. But that is not very useful if I want to change the batch-size at run-time. I guess my question was asking if there was a better way, as I haven't been able to find anything else online.

http://stackoverflow.com/a/54993570
type: Answer
upvote count: 16
answers question: http://stackoverflow.com/q/49791282
downvote count: 0
score: 16
has body: I know this has been asked a while ago, but just solved a similar problem in a project, so posting it here to help out if anyone else faces this issue. full_search = django_filters.CharFilter(method='search_by_full_search', label='Recherche') # change label field to reflect what the filter name should be class Meta: model = myModel fields = ['full_search', ] def search_by_full_search(self, qs, name, value): for term in value.split(): qs = qs.filter(Q(serial__icontains=term) | Q(id__icontains=term) | Q(name__icontains=term)) return qs

http://stackoverflow.com/comment/86699487
comment on: http://stackoverflow.com/a/49840659
type: Comment
score: 0
type: AnswerComment
has text: I have edited the original question in the context of your input.

http://stackoverflow.com/q/49876691
has title: Django imports are failing after nesting apps in an apps folder
has comment: http://stackoverflow.com/comment/86797812
tagged with: python
has body: Here is what I did: I wrapped my 12 Django apps in an apps folder in my Django project. I added sys.path.append(os.path.join(BASE_DIR, 'apps')) in settings.py (before INSTALLED_APPS declaration) sothat I don't need to specify the apps folder when importing my apps. I changed every 12 apps.py files to set name = apps.myappname INSTALLED_APPS are still defined with myappname (not apps.myappname) Here is what I have so far: Code works normally Unit tests, when run app by app, 100% works for the 12 apps. Unit tests, when run as a whole, at some point of execution, fail with errors like this one: ImportError: Failed to import test module: apps.badges.tests Traceback (most recent call last): File "/usr/lib/python3.6/unittest/loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "/usr/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name __import__(name) File "/vagrant/fugo/fugoproj/apps/badges/tests.py", line 10, in &lt;module&gt; from .factories import BadgeFactory File "/vagrant/fugo/fugoproj/apps/badges/factories.py", line 6, in &lt;module&gt; from .models import Badge File "/vagrant/fugo/fugoproj/apps/badges/models.py", line 51, in &lt;module&gt; models.Model): File "/home/ubuntu/fenv/lib/python3.6/site-packages/django/db/models/base.py", line 118, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class apps.badges.models.Badge doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Here is the badges/factories.py file in error: from datetime import timedelta import factory from django.utils import timezone from .models import Badge # some code On every test which fails, it seems related to the relative import for the model (from .models import SomeModel). If I replace this with from myappname.models import SomeModel, this solve the error. Any idea on something wrong in my code? I'd like to keep my relative imports. How to explain it does not fail when running tests app by a…
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/86797654
type: UnansweredQuestion
tagged with: django
tagged with: unit-testing
type: Question

http://stackoverflow.com/comment/86851795
has text: Ok, I think you are right, after cleaning out the close handle stuff. I can open/write/close the socket more then 64 times without crash, though its against what this (https://learn.microsoft.com/en-us/previous-versions/windows/embedded/ms881660%28v=msdn.10%29) MSDN artical suggested ... As to the python socket, I don't know, if python will check the parameter and stop me from using the unknown parameters ? I'll try, if that works, it would be surely great.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49915868
type: Comment

http://stackoverflow.com/comment/86598804
has text: Do you have a really old version of pip installed (check with `pip --version`). Note that `MySQL-python` hasn't been updated [since 2014](https://pypi.python.org/pypi/MySQL-python/1.2.5). Are you sure you want to install that, and not the fork `mysqlclient`?
type: Comment
comment on: http://stackoverflow.com/q/49791885
score: 0
type: QuestionComment

http://stackoverflow.com/comment/86566752
score: 0
comment on: http://stackoverflow.com/q/49775610
type: QuestionComment
has text: also when I am calling the function insert [l.insert (l,65,5)]; I get the error TypeError: insert() takes exactly 2 arguments (3 given). but insert() takes 3 arguments
type: Comment

http://stackoverflow.com/comment/86726310
has text: Post a clean source image please.And you method is ineffecient.
score: 0
comment on: http://stackoverflow.com/q/49854608
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/86718749
type: Comment
comment on: http://stackoverflow.com/a/49843706
has text: Thank you very much m Newville.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/86678020
type: Comment
comment on: http://stackoverflow.com/a/49831092
type: AnswerComment
has text: When a dataframe, df is passed to your one-liner code. 1. The order of index changes, 2. The order of cell values, that are lists in this case, when seperated also changes. Hence it's not the most effective solution, as maintaining the order of list is important.
score: 0

http://stackoverflow.com/q/49881196
tagged with: python
has body: I have this program, import pandas as pd import numpy as np from random import * n = 10 k = 10 for h in range (k): x[k] = [uniform(0, 10) for p in range(n)] what I want is for k = 1 X = np.column_stack((x[1])) for k=2 X = np.column_stack((x[1],x[2])) for k=3 X = np.column_stack((x[1],x[2],x[3])) and so on how can I do that in loop, please
has answer: http://stackoverflow.com/a/49894153
has title: Using "for" to insert colomns in the matrix
tagged with: matrix
score: 0
answer count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86786140
tagged with: for-loop
type: UnansweredQuestion

http://stackoverflow.com/a/49788531
downvote count: 1
answers question: http://stackoverflow.com/q/49788464
type: Answer
score: 0
upvote count: 1
has body: Union and intersection without using using sets: setA = [1,2,3,4,5,6,7,8,9] setB = [1,5,0,9] intersection = [i for i in setA if i in setB] list_union = list({i: i for i in setA + setB}.values()) print(intersection) print(list_union) Output: [1, 5, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] Explanation: For union: [i for i in setA if i in setB] Simply loops through setA and adds elements that are also found in setB For intersection: list({i: i for i in setA + setB}.values()) Creates a dictionary where the keys and values are the result of setA + setB. Since keys in a dictionary are unique, duplicates don't show up in the final dictionary, and list(dct.values()) is used to pull just the values needed from the dictionary.

http://stackoverflow.com/q/49833866
downvote count: 0
accepted answer: http://stackoverflow.com/a/49843108
tagged with: altair
favorite count: 0
has answer: http://stackoverflow.com/a/49843108
type: Question
has title: Making dashboards using altair
has body: I would like to use the excellent altair library to create dashboards. Is there a way to create the dashboards and not show any code? I see some really nice examples here: https://altair-viz.github.io/case_studies/exploring-weather.html but the code is visible too. Also, what is the best (well tested/easy to use) frontend for altair? Colab? Jupyter?
has answer: http://stackoverflow.com/a/67428170
tagged with: python
upvote count: 12
has answer: http://stackoverflow.com/a/50912867
type: AnsweredQuestion
score: 12
possible better answer: http://stackoverflow.com/a/67428170
answer count: 3

http://stackoverflow.com/comment/86639403
type: QuestionComment
comment on: http://stackoverflow.com/q/49812521
score: 3
has text: Remove your random.seed() call.
type: Comment

http://stackoverflow.com/a/62887498
has comment: http://stackoverflow.com/comment/116981116
downvote count: 0
has comment: http://stackoverflow.com/comment/130066617
upvote count: 9
answers question: http://stackoverflow.com/q/49834883
type: Answer
has comment: http://stackoverflow.com/comment/111656627
score: 9
has body: A more simple solution would be: df['x1'] = df.index df.plot(kind='scatter', x='x1', y='columnA') Just create the index variable outside of the plot statement.

http://stackoverflow.com/comment/86579686
type: AnswerComment
has text: Great work! I had to add **kwargs to both `g` and `f` to make it work. I'm very happy. Thanks a lot.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49776472

http://stackoverflow.com/q/49861566
answer count: 1
has title: find minimum from text file
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49861708
tagged with: python
type: Question
has body: I am new to Python and I am trying to figure out how to get my program to find the minimum after it reads specific columns and each rows from the file. Can anyone help me with this? This is how an example of how my text file looks like: 05/01 80 2002 5 1966 19 2000 45 2010 06/22 77 1980 4 1945 22 1986 58 2000 --------------------------------------------------------------------------- Day Max Year Min Year Max Year Min Year --------------------------------------------------------------------------- 08/01 79 2002 8 1981 28 1900 54 1988 08/02 79 1989 5 1971 31 1994 60 1998 This is my code(below) that I have so far. def main () file = open ('file.txt', 'r') for num in file.read().splitlines(): i = num.split() if len(i) &gt; 5: print('Day:{}\n' .format(i[0])) print('Year:{}\n' .format(i[2])) print('Lowest Temperature:{}'.format(i[1])) This is the output I get from my code. (it prints out text as well) : Day:Day Year:Year Lowest Temperature:Max Day: 3/11 Year:1920 Lowest Temperature:78 Day:11/02 Year:1974 Lowest Temperature:80 Day:11/03 Year:1974 Lowest Temperature:74 I am trying to find the lowest temperature from my text file and print out the day and the year associated with that temp. My output should look like this. Thanks to everyone who is willing to help me with this. Day:10/02 Year:1994 Lowest Temperature:55
type: UnansweredQuestion
score: 0

http://stackoverflow.com/q/49766186
score: -4
answer count: 1
has comment: http://stackoverflow.com/comment/86549698
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86553277
has title: how to search keyword without ordering and search keywords which embedded special character without ordering
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/49767831
downvote count: 4
has body: update 2 i edit your suggestion to do 5 cases, near can do all cases, but it has extra results, redundant results, how to improve or is there another better solution? case 1 row1 = "search key $ @ $ words today" re.findall(r'[(?=k&amp;e&amp;y&amp;w&amp;o&amp;r&amp;d&amp;s)]*[ \$\@]*', row1, re.DOTALL) ['se', '', 'r', '', '', ' ', 'key $ @ $ ', 'words ', '', 'od', '', 'y', ''] case 2 row1 = "search key words today" re.findall(r'[(?=k&amp;e&amp;y&amp;w&amp;o&amp;r&amp;d&amp;s)]*[ \$\@]*', row1, re.DOTALL) ['se', '', 'r', '', '', ' ', 'key ', 'words ', '', 'od', '', 'y', ''] case 3 need help row1 = "search key wrods today" re.findall(r'[(?=k&amp;e&amp;y&amp;w&amp;o&amp;r&amp;d&amp;s)]*[ \$\@]*', row1, re.DOTALL) ['se', '', 'r', '', '', ' ', 'key ', 'wrods ', '', 'od', '', 'y', ''] case 4 need help row1 = "search key $ @ $ wrods today" re.findall(r'[(?=k&amp;e&amp;y&amp;w&amp;o&amp;r&amp;d&amp;s)]*[ \$\@]*', row1, re.DOTALL) ['se', '', 'r', '', '', ' ', 'key $ @ $ ', 'wrods ', '', 'od', '', 'y', ''] case 5 row1 = "search key wrds today" re.findall(r'[(?=k&amp;e&amp;y&amp;w&amp;o&amp;r&amp;d&amp;s)]*[ \$\@]*', row1, re.DOTALL) ['se', '', 'r', '', '', ' ', 'key ', 'wrds ', '', 'od', '', 'y', ''] udpate 1 case 1 is ok row1 = "search key $ @ $ words today" re.sub(r' ',r'[ \$\@]*', r'key words') re.findall(re.sub(r' ',r'[ \$\@]*', r'key words'), row1, re.DOTALL) case 2 is ok row1 = "search key words today" re.sub(r' ',r'[ \$\@]*', r'key words') re.findall(re.sub(r' ',r'[ \$\@]*', r'key words'), row1, re.DOTALL) case 3 need help row1 = "search key wrods today" re.sub(r' ',r'[ \$\@]*', r'key words') re.findall(r'(?=k|e|y|[ \$\@]*|\ |w|o|r|d|s)', row1, re.DOTALL) ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] case 4 need help row1 = "search key $ @ $ wrods today" re.sub(r' ',r'[ \$\@]*', r'key words') re.findall(r'(?=k|e|y|[ \$\@]*|\ |w|o|r|d|s)', row1, re.DOTALL) ['', '', '', '', '', '', '', '', '', '', '', '', …
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/86937329
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49912996
has text: Hi, I wanna hit the two keys at the same time instead of one after another
type: Comment

http://stackoverflow.com/comment/86671221
score: 0
comment on: http://stackoverflow.com/q/49811960
has text: The accepted answer in @moooeeeep's first link includes a comment on how `None` can be passed explicitly to get the same effect as leaving the end index empty.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86589727
score: 0
comment on: http://stackoverflow.com/q/49787167
type: Comment
type: QuestionComment
has text: Why not exported directly into PNG?

http://stackoverflow.com/comment/86806532
type: Comment
type: AnswerComment
score: 0
has text: Good to have such folks like yourself on this website! Yous are an asset ;) Take care!
comment on: http://stackoverflow.com/a/49895055

http://stackoverflow.com/comment/86834484
comment on: http://stackoverflow.com/q/49909061
type: Comment
type: QuestionComment
has text: I think I understood... they are the elements that are allowed to apear four times. See answer :)
score: 0

http://stackoverflow.com/comment/86615359
score: 0
has text: You probably indented your multi-line string, making the URL invalid.
comment on: http://stackoverflow.com/q/49800216
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86544449
has text: Ah sorry I think I was a little vague. I only wanted to fill certain ones with 0's and keep others blank. For example, take John's 2123320 and 2234903. Because he only took Math on 2234903 I want that to be a 99 and the other 3 columns of that "group" to be 0's only in that row. For his 2123320, I want it to be completely blank because that No. does not belong to John at all. Also is it possible to select for at least 2 distinct No.'s?
type: AnswerComment
comment on: http://stackoverflow.com/a/49764028
score: 0
type: Comment

http://stackoverflow.com/comment/86845875
comment on: http://stackoverflow.com/q/49914990
score: 1
type: Comment
type: QuestionComment
has text: Your error is because the third parameter of `re.sub` should be a string not a file object.

http://stackoverflow.com/comment/86691564
type: Comment
comment on: http://stackoverflow.com/a/49838201
has text: I tried 'pip install 'pygame~=3.6' and it said that pip was outdated, so I got pip 10.0.0 and now there's a fatal error whenever I try to get anything.
type: AnswerComment
score: 0

http://stackoverflow.com/q/49916452
has comment: http://stackoverflow.com/comment/86850151
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49920187
has comment: http://stackoverflow.com/comment/86848751
tagged with: python
has comment: http://stackoverflow.com/comment/86851338
type: AnsweredQuestion
has body: I am new to scrapy and I've come across a complicated case. I have to make 3 get requests in order to make Product items. product_url category_url stock_url First, I need a request to product_url and a request to category_url to fill out the fields of Product items. I then need to refer to stock_url's response to determine whether to save or discard the created items. Here's what I'm doing right now: In my spider, def start_requests(self): product_url = 'https://www.someurl.com/product?' item = ProductItem() yield scrapy.Request(product_url, self.parse_products, meta={'item':item}) def parse_products(self, response): # fill out 1/2 of fields of ProductItem item = response.meta['item'] item[name] = response.xpath(...) item[id] = response.xpath(...) category_url = 'https://www.someurl.com/category?' yield scrapy.Request(category_url, self.parse_products2, meta={'item':item}) def parse_products2(self, response): # fill out rest of fields of ProductItem item = response.meta['item'] item[img_url] = response.xpath(...) item[link_url] = response.xpath(...) stock_url = 'https://www.someurl.com/stock?' yield scrapy.Request(stock_url, self.parse_final, meta={'item':item}) def parse_final(self, response): item = response.meta['item'] for each prod in response: if prod.id == item['id'] &amp; !prod.in_stock: #drop item Question: I was told before to handle the item-dropping logic in the pipeline. But whether I drop an item or not depends on making another GET request. Should I still move this logic to the pipelines/ is this possible without inheriting scrapy.Spider?
score: 0
has comment: http://stackoverflow.com/comment/86850882
has comment: http://stackoverflow.com/comment/86850074
has title: multiple requests to make an item in scrapy
answer count: 1
tagged with: web-scraping
upvote count: 1
tagged with: scrapy
accepted answer: http://stackoverflow.com/a/49920187
has comment: http://stackoverflow.com/comment/86849419
downvote count: 1

http://stackoverflow.com/q/49856219
tagged with: python-imaging-library
tagged with: osgeo
score: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
has title: Adding alpha to .dds file
tagged with: python
accepted answer: http://stackoverflow.com/a/49862406
has answer: http://stackoverflow.com/a/49862406
type: AnsweredQuestion
has body: how can I add to a .dds file (without alpha), an alpha channel? The source for the alpha data, is a 8bit gray tiff. I tried gdal_merge but it seems that adds transparency to the rgb and not a new alpha channel. Thank you!
tagged with: imagemagick

http://stackoverflow.com/q/49867654
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: function inputs in classes
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49867681
score: -2
tagged with: pyqt
has body: So i have started using classes in python and i am still learning how it works. so in this part of my code and i found something that i don't understand. def Button(self): self.Button = QPushButton("Push me Bitch!",self) self.Button.setGeometry(QtCore.QRect(500, 500, 5, 5)) self.Button.resize(self.Button.minimumSizeHint()) self.Button.clicked.connect(self.ButtonPress(someInput)) # Do functions def ButtonPress(self , someInput): print('someInput') self.OutputBox1.setText('I Has Been Pressed!') And this is the error that i got: Traceback (most recent call last): File "C:\Users\Gebruiker\Desktop\Python shizzle\BijHillen\BijGui.py", line 92, in &lt;module&gt; ex = Example() File "C:\Users\Gebruiker\Desktop\Python shizzle\BijHillen\BijGui.py", line 40, in __init__ self.Button() File "C:\Users\Gebruiker\Desktop\Python shizzle\BijHillen\BijGui.py", line 68, in Button self.Button.clicked.connect(self.ButtonPress(5)) File "C:\Users\Gebruiker\Desktop\Python shizzle\BijHillen\BijGui.py", line 74, in ButtonPress self.OutputBox1.setText('I Have Been Pressed!!!') AttributeError: 'Example' object has no attribute 'OutputBox1' If i remove the someInput. Then there is no problem. How does this work? Best regards
downvote count: 3
answer count: 1

http://stackoverflow.com/a/49892988
type: Answer
has comment: http://stackoverflow.com/comment/100647524
has body: If you are concerned that the format of the file stays the same (and if there are comments that they should be preserved), you can do: import ruamel.yaml yaml = ruamel.yaml.YAML() yaml.preserve_quotes = True yaml.explicit_start = True with open('input.yaml') as fp: data = yaml.load(fp) my_dict = { '001': '000-111-2222', '002': '000-111-2223', '003': '000-111-2224', } for k in my_dict: data.setdefault(k, {})['phone'] = my_dict[k] with open('output.yaml', 'w') as fp: yaml.dump(data, fp) After which output.yaml contains: --- '001': name: Ben email: ben@test.com phone: 000-111-2222 '002': name: Lisa email: lisa@test.com phone: 000-111-2223 '003': name: Alex email: alex@test.com phone: 000-111-2224 Notes: The yaml.preserve_quotes = True is not really necessary, as for scalars that need quotes ( your strings starting with zero ) single quotes are the default, and there are no superfluous quotes in your input either. I use data.setdefault(k, {})['phone'] instead of checking if data[k] exists as @Aaron suggested in his source. It will create an (empty) dict if the key k is not in data. If you only want to update matching keys, then use the following in the for loop: try: data[k]['phone'] = my_dict[k] except KeyError: pass You need yaml.explicit_start = True to get the --- at the document start. ruamel.yaml doesn't automatically preserve that. If you need the document end marker (...) as well use: yaml.explicit_end = True If you want the phone number to appear between name and email, then use: data.setdefault(k, {}).insert(1, 'phone', my_dict[k]) which gives: --- '001': name: Ben phone: 000-111-2222 email: ben@test.com '002': name: Lisa phone: 000-111-2223 email: lisa@test.com '003': name: Alex phone: 000-111-2224 email: alex@test.com (i.e. 0 means insert before the first key, 1 before the second key, etc.)
has comment: http://stackoverflow.com/comment/100666901
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/100666718
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49887681
has comment: http://stackoverflow.com/comment/100669211
has comment: http://stackoverflow.com/comment/100717368
has comment: http://stackoverflow.com/comment/100662764
has comment: http://stackoverflow.com/comment/100668481
answers question: http://stackoverflow.com/q/49887681
score: 3

http://stackoverflow.com/q/49777828
has comment: http://stackoverflow.com/comment/86570941
type: Question
has title: Create HTML Table with multiple python lists
tagged with: http://stackoverflow.com/tag/html
possible better answer: http://stackoverflow.com/a/49777907
tagged with: python
type: AnsweredQuestion
tagged with: html-table
score: 0
tagged with: list
answer count: 2
has body: I have three lists and would like to write them into a html file to create a table. My lists are: host, ip, sshkey I already tried: with open("index.html", "a") as file: for line in host: file.write(" " + line + " " + ip + " + sshkey + " " file.close() I got the error: TypeError: cannot concatenate 'str' and 'list' objects And when I try: file.write(" " + line + " " + ip[0] + " + sshkey[0] + " " I get this: Hostname1 IP1 SSHkey1 Hostname2 IP1 SSHkey1 Hostname3 IP1 SSHkey1 But I want this outcome: Hostname1 IP1 SSHkey1 Hostname2 IP2 SSHkey2 Hostname3 IP3 SSHkey3
accepted answer: http://stackoverflow.com/a/49777921
upvote count: 1
has comment: http://stackoverflow.com/comment/86570962
downvote count: 1
has answer: http://stackoverflow.com/a/49777907
has answer: http://stackoverflow.com/a/49777921
favorite count: 0

http://stackoverflow.com/q/49820759
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49821104
type: Question
tagged with: mongodb
linked to: http://stackoverflow.com/q/6814151
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15242746
score: 0
has comment: http://stackoverflow.com/comment/86657370
has body: I have a large Mongo DB document with one JSON document per line. I need to convert it to columnar format (Pandas DF or CSV) to be able to analyze and draw same insights. I don't have enough experience to parse Mongo DB and I am not sure whether I do it right. What I have done so far: To be able to use json.loads I have added a comma at the end of each line and wrapped the massive into []. The sample(part of 1 JSON) looks like this: { "id" : "12345id" , "price" : 202.4, "order_id" : "bc2341" , "order_time" : { "date" : "2018-03-27T12:22:50.935+0000" }, "work_data" : { "worker_id" : "5938686", "job" : [ { "id" : "663442", "approx_time" : "2018-03-27T12:13:58.33Z", "job_type" : null }, { "id" : "663442", "approx_time" : "2018-03-27T12:13:58.33Z", "job_type" : null }]} I have made this code to write to CSV: report_file = open('..result.csv', 'w') writer = csv.writer(report_file) for row in config_file: jobs = row.get('work_data',{}).get('job',{}) jobs_str = '' if isinstance(jobs, list): for job in jobs: jobs_str += job.get('approx_time', '') writer.writerow((row['order_time']['date'], jobs_str)) report_file.close It works, but I can't figure out how to split multiples jobs into different columns to get different approx_time. Can someone help with the solution? Maybe there are better ways to convert JSONs from MongoDB to CSV/Pandas? In the end I need something like this: 1 row per 1 JSON, if multiple jobs in JSON, then they must be in columns +---------+--------+---------------+--------+---------------+ | id |id_job_1| approx_time_1 |id_job_2| approx_time_2 | +---------+--------+---------------+--------+---------------+ | 12345id | 664442 | 27.03.2018 | 663442 | 27.03.2018 | | 22345id | 633442 | 27.03.2018 | 622442 | 27.03.2018 | +---------+--------+---------------+--------+---------------+
has title: MongoDB nested JSONs to Pandas DF/CSV
tagged with: pandas
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/49786487
has comment: http://stackoverflow.com/comment/86614336
downvote count: 0
tagged with: selenium
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86588934
tagged with: webdriver
favorite count: 0
type: Question
has body: I have some code here that opens an existing webpage and clicks a button labeled "HTTP Ping". It opens the firefox browser but does not actually connect to the page or click the one button the page features. Any help? #!/usr/bin/python from selenium import webdriver driver=webdriver.Firefox() driver.get("http://www.cloudping.info/") element1 = driver.find_element_by_link_text("HTTP Ping") element1.click() Now I'm receiving feedback: Traceback (most recent call last): File "./finalProject", line 9, in &lt;module&gt; driver=webdriver.Firefox() File "/home/pjvaglic/.local/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 80, in __init__ self.binary, timeout) File "/home/pjvaglic/.local/lib/python2.7/site-packages/selenium/webdriver/firefox/extension_connection.py", line 52, in __init__ self.binary.launch_browser(self.profile, timeout=timeout) File "/home/pjvaglic/.local/lib/python2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 68, in launch_browser self._wait_until_connectable(timeout=timeout) File "/home/pjvaglic/.local/lib/python2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 108, in _wait_until_connectable % (self.profile.path)) selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: /tmp/tmpTfjrqh If you specified a log_file in the FirefoxBinary constructor, check it for details.
has title: Python - selenium webpage open
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86588781
tagged with: scripting
tagged with: python
has comment: http://stackoverflow.com/comment/86589936
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/86588353
answer count: 0
has comment: http://stackoverflow.com/comment/86588446

http://stackoverflow.com/comment/86840249
comment on: http://stackoverflow.com/a/49911979
score: 0
has text: Thanks, but not quite. Where your code seems to output all the possible combinations of each member of the target array individually, it does so mutually exclusive to the other members of the target array. I will try to clarify my OP, but said here: if you use 1 and 2 to make 3, then you can't use 1 or 2 to make 8 in that result set. Using your output format it would include: Set1: {3: [(1, 2)], 8: [(3, 5)]} Set2: {3: [(3)], 8: [(1, 2, 5)]} Set3: {8: [(1, 3, 4)]} etc...
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/86784997
comment on: http://stackoverflow.com/a/49884135
type: AnswerComment
score: 1
type: Comment
has text: You we're right. userDetails=request.form doesn't work.

http://stackoverflow.com/q/49865334
has title: Python & Numba: incorrect checksum for freed object
answer count: 1
has comment: http://stackoverflow.com/comment/86746571
favorite count: 0
type: Question
tagged with: numpy
tagged with: memory-management
tagged with: numba
has comment: http://stackoverflow.com/comment/86746635
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
has body: I'm trying to use a loop to update an array in Numba, as I know that Numba doesn't support array creation. In a nutshell, my function looks like: @jit(nopython=True) def innerFunc(arr): for i in range(10000): arr[i] = arr[i] * 100 return arr def outerFunc(arr): arr = innerFunc(arr) return arr def main(): ####Create two numpy arrays with 10,000 random numbers each#### ####and call them arr1 and arr2#### outerFunc(arr1) outerFunc(arr2) return arr1, arr2 However, when I run main, I keep seeing an error like this: incorrect checksum for freed object - object was probably modified after being freed. *** set a breakpoint in malloc_error_break to debug And this error doesn't always occur at the same place. Sometimes the error occurs after the first outerFunc is finished, but it could show up even before the first outerFunc is done. Does it have to do with the fact that I'm doing an inplace update, calling outerFunc twice, or both? Am I doing something with memory management?
has answer: http://stackoverflow.com/a/49865730
accepted answer: http://stackoverflow.com/a/49865730

http://stackoverflow.com/comment/86548159
type: QuestionComment
has text: You should see your device or avd when you run `adb devices`, then you can use `culebra` to connect to it. I'm not sure what you mean by *create AVD* but `culebra` **uses** them, it does not **create**
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49762454

http://stackoverflow.com/comment/86722635
score: 0
type: Comment
type: AnswerComment
has text: the view runs on the server so file is generated serverside, you can try NamedTemporaryFile if you are using it in production.
comment on: http://stackoverflow.com/a/49852014

http://stackoverflow.com/comment/87226108
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49892504
has text: Thank you very much @RickM.! It solved my problem :)

http://stackoverflow.com/a/49912041
accepted answer of: http://stackoverflow.com/q/49911442
answers question: http://stackoverflow.com/q/49911442
type: Answer
score: 4
upvote count: 4
has body: You have two problems: When interpreted as arrays, your variables xs and ys are two-dimensional with shape (2, 100). When linregress is given both arguments x and y, it expects them to be one-dimensional arrays. As you can see in the "Returns" section of the docstring, linregress returns five values, not four. You'll have to call linregress twice, and handle the five return values. For example, In [144]: slope, intercept, rvalue, pvalue, stderr = linregress(xs[0], ys[0]) In [145]: slope, intercept, rvalue Out[145]: (-1.7059670627062702, 187.5658196039604, -0.9912859597363385) In [146]: slope, intercept, rvalue, pvalue, stderr = linregress(xs[1], ys[1]) In [147]: slope, intercept, rvalue Out[147]: (-1.2455432103210327, 121.51968891089112, -0.9871123119133126)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/86559912
has text: Look for `connected components labeling algorithm` implementation
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49771746

http://stackoverflow.com/a/49854725
type: Answer
has body: LabelEncoder will encode the categories based on alphabetic order and stored in classes_ attribute. By default this is the case: from sklearn.preprocessing import LabelEncoder le = LabelEncoder() le.fit(['Phd', 'Msc','Bsc', 'O Levels','No education']) ll.classes_ # Output: array(['Bsc', 'Msc', 'No education', 'O Levels', 'Phd'], dtype='|S12') How many categories are there? If less, you can yourself do the conversion by using a dict, similar to this answer here: my_dict = {'Phd':4, 'Msc':3 , 'Bsc':2, 'O Levels':1, 'No education':0} y = ['No education', 'O Levels','Bsc', 'Msc','Phd'] np.vectorize(my_dict.get)(y) # Output: array([0, 1, 2, 3, 4])
upvote count: 1
answers question: http://stackoverflow.com/q/49854070
downvote count: 0
score: 1

http://stackoverflow.com/a/49830024
type: Answer
answers question: http://stackoverflow.com/q/49829789
score: 0
has body: You need to open the output file in append mode. def generate_daily_totals(input_filename, output_filename): """Returns date followed by the sum of values""" infile = open(input_filename) for line in infile: content = line.split(",") date = content[0] total = sum(map(float, content[1:])) # No need for the inner loop rounded_total = "{:.2f}".format(total) summary = date + " " + "=" + " " + rounded_total outfile = open(output_filename, "a") outfile.write(summary + '\n') generate_daily_totals('data60.txt', 'totals60.txt') Output written to the file: 2006-04-10 = 1399.46 2006-04-10 = 2822.36 2006-04-10 = 2803.81 2006-04-10 = 1622.71 2006-04-10 = 3119.60 2006-04-10 = 2256.14 2006-04-10 = 3120.05 2006-04-10 = 1488.00

http://stackoverflow.com/q/49784216
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49784258
score: 1
has body: I am new in Python and my question might be too obvious, but I did not find a sufficiently good answer. Suppose I have a 2D array a=np.array([[1,2,3],[4,5,6],[7,8,9]]). How can I subscribe those elements that satisfy a condition? Suppose, I want to increase by one those elements of a that are greater than 3. In Matlab, I would do it in 1 line: a(a&gt;3)=a(a&gt;3)+1. What about Python? The result should be [[1,2,3],[5,6,7],[8,9,10]]. I am aware that there are functions that can return the indeces I need, like np.where. I am also aware that there is a way of indexing 2D array with two 1D arrays. I was not able to combine those together. Of course, I am able to do it with for loop. I am interested, is there a convenient Matlab-like way of doing this? Thanks
answer count: 1
linked to: http://stackoverflow.com/q/35607818
favorite count: 0
type: Question
tagged with: numpy
has title: Python: fast subscription of the elements in 2D array that satisfy a condition
tagged with: arrays
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49784258

http://stackoverflow.com/q/49832053
has comment: http://stackoverflow.com/comment/86679500
has comment: http://stackoverflow.com/comment/86679530
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86679600
answer count: 1
has body: I am trying to read tab seperated csv into a Dataframe, but only heading is delimited but not values Below is my code import pandas as pd import csv dfs = pd.read_csv('C:\Users\LENOVO\Downloads\9.csv',sep='\t',engine='python') Headers: Product Id Product Name Product Type UoM Weight(KG/Grams) Volume(Cubic meters) SAP ValuationClass Planner Deletion Flag SKU ID SKU Description Input File: my o/p is: Columns got seperated but values didnt. When i try to print first column in df, it throwing keyerror I tried: lineterminator and all other previous similar responses, but nothing worked Any help will be much appreciated
type: Question
has comment: http://stackoverflow.com/comment/86679462
has title: Reading tab seperated csv to Dataframe
has comment: http://stackoverflow.com/comment/86695235
has comment: http://stackoverflow.com/comment/86694242
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49832212

http://stackoverflow.com/a/49863153
answers question: http://stackoverflow.com/q/49854953
downvote count: 0
has body: Pretty sure that I had the exact same problem as you. I am using Python 2.7.14 64-bit, and when I try to install pip using get-pip.py, I get the exact same error. I fixed this by simply running the following command: python -m ensurepip --default-pip This then installed pip. This is because the version of Python I downloaded is packaged with pip. Note that this installed pip without the wheel portion, so I then had to run: python -m pip install --upgrade pip setuptools wheel After that, everything was ready to go.
upvote count: 7
score: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86752190
has comment: http://stackoverflow.com/comment/105519335
accepted answer of: http://stackoverflow.com/q/49854953
type: Answer
has comment: http://stackoverflow.com/comment/86833400

http://stackoverflow.com/comment/86560480
score: 0
type: Comment
type: QuestionComment
has text: Im a college student trying to get through finals I dont got that kinda time to read a tour.
comment on: http://stackoverflow.com/q/49770885

http://stackoverflow.com/comment/104151291
score: 5
type: AnswerComment
comment on: http://stackoverflow.com/a/49906297
has text: using `.` instead of `text()` is actually more reliable because it will work even if there are several text nodes inside the element (it would concatenate them)
type: Comment

http://stackoverflow.com/comment/86577161
comment on: http://stackoverflow.com/q/49778805
type: QuestionComment
has text: This is more of a response to data type differences between windows and linux. I am unpacking from binary, so I couldn't give you a test case. The function I am using is listed in the original post.
score: 0
type: Comment

http://stackoverflow.com/a/49851394
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49851179
has body: You should use doulble underscore to get table's ForeignKey (One-To-Many) relationship fields and related_name (field_name_set by default) to access to Many-To-One (ForeignKey that references the table) objects. There are docs: Lookups that span relationships It's also good for perfomance to use select_related and prefetch_related.

http://stackoverflow.com/comment/86656900
comment on: http://stackoverflow.com/a/49820886
type: AnswerComment
has text: And if it's shorter, it can't need all the replacements.
score: 1
type: Comment

http://stackoverflow.com/comment/86746645
score: 0
comment on: http://stackoverflow.com/a/49863217
type: AnswerComment
type: Comment
has text: I don't disagree. This is the kind of question that already has been asked 12 times on stackoverflow in slightly different formats. IMO it's best to either choose to be helpful or mark it as a duplicate and move on.

http://stackoverflow.com/a/49911299
upvote count: 7
answers question: http://stackoverflow.com/q/49911206
score: 7
type: Answer
has body: Normalize your outputs so they are in the range 0, 1. Make sure your normalization function lets you transform them back later. The sigmoid activation function always outputs between 0, 1. Just make sure your last layer has sigmoid activation to restrict your output into that range. Now you can take your outputs and transform them back into the range you wanted. You could also look into writing your own activation function to transform your data.
downvote count: 0

http://stackoverflow.com/q/49830584
tagged with: recurrent-neural-network
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49831251
type: UnansweredQuestion
has body: I am trying to build a machine translation model. model = Sequential() model.add(Embedding(english_vocab_size,512, input_length = 15)) model.add(LSTM(512)) model.add(RepeatVector(output_sequence_length)) model.add(LSTM(512,return_sequences=True)) model.add(TimeDistributed(Dense(french_vocab_size, activation='sigmoid'))) print (model.summary()) When I print the model summary I get this: I don't understand this. Why is it printing 10 layers whereas I have set only 5 in my code? Thanks for any suggestions.
answer count: 1
has title: Meaning of Keras model summary
tagged with: python
tagged with: keras
tagged with: deep-learning
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/49913956
has comment: http://stackoverflow.com/comment/86853537
has comment: http://stackoverflow.com/comment/86851153
has comment: http://stackoverflow.com/comment/86852653
has comment: http://stackoverflow.com/comment/86854121
has comment: http://stackoverflow.com/comment/86853990
has comment: http://stackoverflow.com/comment/86858682
score: 0
has comment: http://stackoverflow.com/comment/86865012
answer count: 0
has body: I write this code for computing ecdh key. Use OpenSSL-1_0_2o. The C code is there(all of include and lib is just OpenSSL only) void *KDF_MD5(const void *in, size_t inlen, void *out, size_t *outlen) { MD5_CTX ctx; MD5_Init(&amp;ctx); MD5_Update(&amp;ctx, in, inlen); MD5_Final((unsigned char*)out, &amp;ctx); *outlen = MD5_DIGEST_LENGTH; return out; } bool DoEcdh(int nid, unsigned char * szServerPubKey, int nLenServerPub, unsigned char * szLocalPriKey, int nLenLocalPri, unsigned char * szShareKey, int *pLenShareKey) { const unsigned char *public_material = (const unsigned char *)szServerPubKey; const unsigned char *private_material = (const unsigned char *)szLocalPriKey; EC_KEY *pub_ec_key = EC_KEY_new_by_curve_name(nid); if (!pub_ec_key) return FALSE; pub_ec_key = o2i_ECPublicKey(&amp;pub_ec_key, &amp;public_material, nLenServerPub); if (!pub_ec_key) return FALSE; EC_KEY *pri_ec_key = EC_KEY_new_by_curve_name(nid); if (!pri_ec_key) return FALSE; pri_ec_key = d2i_ECPrivateKey(&amp;pri_ec_key, &amp;private_material, nLenLocalPri); if (!pri_ec_key) return FALSE; if (MD5_DIGEST_LENGTH != ECDH_compute_key((void *)szShareKey, MD5_DIGEST_LENGTH, EC_KEY_get0_public_key(pub_ec_key), pri_ec_key, KDF_MD5)) { EC_KEY_free(pub_ec_key); EC_KEY_free(pri_ec_key); return FALSE; } *pLenShareKey = MD5_DIGEST_LENGTH; if (pub_ec_key) { EC_KEY_free(pub_ec_key); pub_ec_key = NULL; } if (pri_ec_key) { EC_KEY_free(pri_ec_key); pri_ec_key = NULL; } return TRUE; } then, I rewrite in Python ctypes, just use python with libeay32.dll in Windows OR libcrypto.so in Linux. When I call C function ECDH_compute_key raise an OSError. this function: result = ECDH_compute_key(ShareKey_p, outlen, server_ECpoint, pri_ec, mykdf) Error: # ------- OSError: exception: access violation reading 0xFFFFFFFFCDC562C0 from ecdhlib.openssl_wrapper import OpenSSL import ctypes from ctypes import c_int, c_char_p, pointer from ctypes import * from hashlib import md5 class Ecdh(object): def __init__(self, curve='secp224r1'):…
linked to: http://stackoverflow.com/q/48788549
has comment: http://stackoverflow.com/comment/86852912
has comment: http://stackoverflow.com/comment/86887097
has comment: http://stackoverflow.com/comment/86852471
tagged with: pointers
type: Question
tagged with: ctypes
type: UnansweredQuestion
has title: ctypes use Pointer and CFUNCTYPE
tagged with: python

http://stackoverflow.com/a/49870246
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49870206
type: Answer
answers question: http://stackoverflow.com/q/49870206
has body: From PEP8: Wildcard imports (from &lt;module&gt; import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance). Generally you want to import only what you need, and make sure imports are explicit (e.g. the third option in your list, but sometimes also the fourth option).
score: 2
upvote count: 2

http://stackoverflow.com/q/49846350
has answer: http://stackoverflow.com/a/49852328
type: Question
score: 0
type: UnansweredQuestion
tagged with: selenium
has body: I need to constantly reload a web page as quickly as possible and check, if something has changed. But when I tried the following, it didn't work. I used something like this: while True: driver.get(driver.getCurrentUrl()) source = driver.page_source -- checking for change -- while using the Edge webdriver (it was the fastest one), but when the change already occured, the webdriver was still getting the old version of the page. I don't know if the driver can save the page in cache or something, but I need to make sure, that I will always get the current version. How can I achieve that?
has comment: http://stackoverflow.com/comment/86766225
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/86765937
has title: How to validate the changes in a webpage after reloading the webpage through selenium (python)?
tagged with: reload
answer count: 1
tagged with: python
tagged with: webdriver

http://stackoverflow.com/q/49898007
answer count: 2
has answer: http://stackoverflow.com/a/49899513
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86813124
has comment: http://stackoverflow.com/comment/86813199
favorite count: 0
type: Question
has title: Time operations on a dataframe column
accepted answer: http://stackoverflow.com/a/49899513
tagged with: datetime
has body: For this dataframe I'm trying for each value id2 of the column Id calculate the difference of time betweeen the previous and following row with id value id1. Then keep just the closest row in term of time. Id time value id1 14:07:53.158 1 id2 14:07:53.358 2 id1 14:07:54.462 3 id1 14:10:09.560 4 id2 14:10:10.160 5 id1 14:10:10.520 6
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49899109
possible better answer: http://stackoverflow.com/a/49899109
score: 2
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/q/49909524
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49910581
upvote count: 1
tagged with: python
has body: I have a loop that creates subsets of a larger data frame, which are then used as input for a function for analysis. This function returns a list. I used prints to see where it stops. So for the first run in the loop I can see the subset, the list output of the function, but when it starts again, second run, I see the second subset but than at the function I get the following error: &lt;ipython-input-11-8f6203e297e3&gt; in ssd(x, y) 8 9 for i in range(x.shape[0]): ---&gt; 10 spread_cumdiff += (x[i] - y[i]) **2 11 12 return spread_cumdiff Note the above part is the last part "before" the python-error below. In fact, above has 2 more similar blocks, ie function a) which contains function b) which contains the block above. ~/anaconda3/envs/thesis/lib/python3.5/site-packages/pandas/core/series.py in __getitem__(self, key) 621 key = com._apply_if_callable(key, self) 622 try: --&gt; 623 result = self.index.get_value(self, key) 624 625 if not is_scalar(result): ~/anaconda3/envs/thesis/lib/python3.5/site-packages/pandas/core/indexes/base.py in get_value(self, series, key) 2558 try: 2559 return self._engine.get_value(s, k, -&gt; 2560 tz=getattr(series.dtype, 'tz', None)) 2561 except KeyError as e1: 2562 if len(self) &gt; 0 and self.inferred_type in ['integer', 'boolean']: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() KeyError: 0 I have it something along these lines: df_test = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)), columns=['a', 'b', 'c', 'd', 'e'], index = ['20100101', '20100102', '20100103', '20100104', '20100105'] dfs = [] N = 3 for x in np.arange(len(df_test)+1)[N:]: df1 = df_test.iloc[np.arange(x - N, x)] test_l…
tagged with: tuples
tagged with: list
answer count: 2
tagged with: dynamic
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49927418
tagged with: loops
has title: Python: KeyError: 0 - function that creates a list from subsets of data frame accessed via a loop
favorite count: 0
has comment: http://stackoverflow.com/comment/86868149

http://stackoverflow.com/comment/86799389
has text: Thanks a lot! There is only 1 tiny issue. Conv1D expects 3d input, but it is saying my input dim=4 when I reshape it to (100,64,1). I guess there is an implicit batch_size dimension as dim[0]. How should I solve that? By the way, can I use conv2D with kernel dimension=(1,1d_filter_len) in this case, and then reshape the CNN output to (100,num_lstm_neuron) ?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49871182
type: AnswerComment

alignment
tags question: http://stackoverflow.com/q/49797171
tags question: http://stackoverflow.com/q/49894640
tag name: alignment
type: Tag

http://stackoverflow.com/comment/86687621
has text: And also can you add the output of `brew doctor`?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49788769
type: Comment

http://stackoverflow.com/comment/86660719
type: Comment
comment on: http://stackoverflow.com/q/49822552
score: 1
type: QuestionComment
has text: yes, when looking at the source of that module it is a normal `def` function

http://stackoverflow.com/a/49874130
score: 0
has comment: http://stackoverflow.com/comment/86763870
has comment: http://stackoverflow.com/comment/86763891
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49873805
has body: One solution is to convert your series to a datetime object, then use pd.Series.dt.strftime. CSV files are not type sensitive, so converting to string is a reliable way of ensuring your output is in the format you expect. df = pd.DataFrame({'Duration': ['00:00:00.001000', '00:00:00.002000', '00:00:00.205000']}) df['Duration'] = pd.to_timedelta(df['Duration']) df['DurationStr'] = (df['Duration'] + pd.Timestamp('20180101')).dt.strftime('%H:%M:%S:%f') print(df) # Duration DurationStr # 0 00:00:00.001000 00:00:00:001000 # 1 00:00:00.002000 00:00:00:002000 # 2 00:00:00.205000 00:00:00:205000 print(df.dtypes) # Duration timedelta64[ns] # DurationStr object # dtype: object
accepted answer of: http://stackoverflow.com/q/49873805
type: Answer

http://stackoverflow.com/comment/86661914
type: AnswerComment
has text: Oh! Now I understand properly the desired output. I will edit my answer. A priori, I expect `numpy` to be a little faster, I don't know if this is an important factor for you
comment on: http://stackoverflow.com/a/49822663
score: 0
type: Comment

http://stackoverflow.com/comment/86599875
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49792651
has text: Forgot to mention that one - doesn't do anything either, tried with orient = 'index' too which gives the following error. 'AttributeError: 'list' object has no attribute 'values'' I should mention that the initial data sits with each row as an item in a list.
score: 0

http://stackoverflow.com/q/49914346
tagged with: python-2.7
score: 0
tagged with: text-extraction
accepted answer: http://stackoverflow.com/a/49914823
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49915670
possible better answer: http://stackoverflow.com/a/49915670
answer count: 2
has title: Python: Extract random no. of lines from a text file between markers
tagged with: extract
has comment: http://stackoverflow.com/comment/86844452
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/86845530
has answer: http://stackoverflow.com/a/49914823
has body: I have some text files containing 1000+ lines. It contains some lines in the format: seq open @ 2018/02/26 23:07:51 node: \nodes\wroot.nod (wroot) seq call @ 2018/02/26 23:07:51 node: ttt retrieve BIOS data using F:\tools64\BiosConfigUtility64.exe /GetConfig:\working\bcudump.txt BCU is working seq done @ 2018/02/26 23:07:55 node:ttt seq call @ 2018/02/26 23:07:55 node: fff Open the firewall Firewall opened seq done @ 2018/02/26 23:07:57 node: fff seq call @ 2018/02/26 23:07:57 node: \nodes\wchkefierror.bat (wroot#9^wchkefierror) seq done @ 2018/02/26 23:07:57 node: \nodes\wchkefierror.bat (wroot#9^wchkefierror) seq call @ 2018/02/26 23:07:57 node: \nodes\wuutmont.bat PTEFIE (wroot#12^wuutmont) SENDING UUTMonitor.exe /timeevent:PTEFIE seq done @ 2018/02/26 23:07:58 node: \nodes\wuutmont.bat PTEFIE (wroot#12^wuutmont) seq call @ 2018/02/26 23:07:58 node: \nodes\wProcessInit.bat (wroot#13^wProcessInit) 02/26/2018 23:07:59 : @@@@ begin_\process\ProcessInit.bat &lt;BISCON Version=xxxx"&gt; x y &lt;/BISCON&gt; \process\ProcessInit.bat:::Parsing branding variables from INI files... found \flags\custom.ini PRODUCTIONLOCK not defined in custom.ini \process\ProcessInit.bat:::Calling SETVAR.BAT generated from INI data... 02/26/2018 23:08:04 : @@@@ end\process\ProcessInit.bat seq done @ 2018/02/26 23:08:04 node: \nodes\wProcessInit.bat (wroot#13^wProcessInit) seq log @ 2018/02/26 23:08:04 node: skipping wroot#14^wbios as \flags\bios_flash_wnd.trg file not exists seq call @ 2018/02/26 23:08:04 node: aaa Get SkeletonPO from \working\ubera.ini seq done @ 2018/02/26 23:08:04 node: aaa I want to extract the lines between seq call and seq done in a list and insert NULL in the list if the line starts with seq open or seq log. As you can see there may be any random no. of lines even 0 between seq call and seq done. I have been trying to find answers but to no avail. Also I am new in python. Expected output for the above sample: NULL retrieve BIOS data using F:\tools64\BiosConfigUtility…
type: AnsweredQuestion

http://stackoverflow.com/comment/86552126
type: Comment
type: AnswerComment
has text: Nice as always! What do you think about my solution? :)
score: 0
comment on: http://stackoverflow.com/a/49767434

http://stackoverflow.com/comment/86781178
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49882051
has text: Have you profiled your code?
score: 0

http://stackoverflow.com/q/49882684
tagged with: pip
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86782272
has title: Upgraded to pip9.0.3 - *STILL* getting tlsv1 error & can't install packages/libs : Linux
tagged with: ssl
tagged with: python
has body: I recently updated pip (as prompted) to 9.0.3 and immediately have fallen foul of the tlsv1 error, eg Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:646)'),)': /simple/pywakeonlan/ Could not fetch URL https://pypi.python.org/simple/pywakeonlan/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/pywakeonlan/ (Caused by SSLError(SSLError(1, '[SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:646)'),)) - skipping Could not find a version that satisfies the requirement pywakeonlan (from versions: ) No matching distribution found for pywakeonlan I've checked out as many of the obviously related questions on SO as I can, but none of them hold a direct answer that I can see. Running pip with --trusted-host makes no difference. os is Puppy Linux Precise (= Ubuntu 12.04 basically) I've upgraded my OpenSsl to 1.0.2f, but to no avail. Python 3.5.0 (default, Aug 28 2017, 17:57:13) [GCC 4.6.3] on linux import ssl print(ssl.OPENSSL_VERSION) OpenSSL 1.0.1 14 Mar 2012 Clearly there's a mismatch of os OpenSSL version and what Python is picking up. Short of upgrading to a later os version (this fixes it, I've tested it - but brings other unrelated difficulties for me), the only glimmer I have is that I might need to recompile Python now that I have upgraded OpenSSL? Is this correct? If so, do I only need the recompiled interpreter plus some selected libs such as ssl perhaps? Or do I need to install the entire suite again?
type: Question
has comment: http://stackoverflow.com/comment/86781770
score: 0
has comment: http://stackoverflow.com/comment/86782397
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/86706186
type: Comment
comment on: http://stackoverflow.com/a/49844212
type: AnswerComment
score: 0
has text: Thanks a lot for showing another route! Actually, I was using something very similar to your first solution @sacul. But it was taking too long on my machine. Thanks once more!

http://stackoverflow.com/q/49866071
has answer: http://stackoverflow.com/a/49866465
accepted answer: http://stackoverflow.com/a/49866465
tagged with: python
has comment: http://stackoverflow.com/comment/86748001
score: 2
type: AnsweredQuestion
tagged with: pandas
upvote count: 2
linked to: http://stackoverflow.com/q/41370695
has comment: http://stackoverflow.com/comment/86747678
has title: Overwriting existing dataframe in loop
has comment: http://stackoverflow.com/comment/86747935
has comment: http://stackoverflow.com/comment/86747679
has comment: http://stackoverflow.com/comment/86747966
answer count: 1
downvote count: 0
has body: I am trying to transform elements in various data frames (standardize numerical values to be between 0 and 1, one-hot encode categorical variables) but when I try to overwrite the dataframe in a loop it doesn't modify the existing dataframe, only the loop variable. Here is a dummy example: t = pd.DataFrame(np.arange(1, 16).reshape(5, 3)) b = pd.DataFrame(np.arange(1, 16).reshape(5, 3)) for hi in [t, b]: hi = pd.DataFrame(np.arange(30, 45).reshape(5, 3)) But when I run this code both t and b have their original values. How can I overwrite the original dataframe (t or b) while in a loop? The specific problem I'm running into is when trying to use get_dummies function in the loop: hi = pd.get_dummies(hi, columns=['column1'])
has comment: http://stackoverflow.com/comment/86748211
favorite count: 0
type: Question

http://stackoverflow.com/q/49907455
has comment: http://stackoverflow.com/comment/86831055
has comment: http://stackoverflow.com/comment/86831093
has answer: http://stackoverflow.com/a/58524517
accepted answer: http://stackoverflow.com/a/49916688
tagged with: python
answer count: 13
downvote count: 1
has answer: http://stackoverflow.com/a/49916688
has answer: http://stackoverflow.com/a/52313492
has title: Hide Code when exporting Jupyter notebook to HTML
has comment: http://stackoverflow.com/comment/86831222
has answer: http://stackoverflow.com/a/56699655
has answer: http://stackoverflow.com/a/67431748
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55305881
score: 99
has answer: http://stackoverflow.com/a/69387570
has answer: http://stackoverflow.com/a/66065955
tagged with: jupyter
has answer: http://stackoverflow.com/a/78808332
upvote count: 100
linked to: http://stackoverflow.com/q/55306404
favorite count: 0
has body: I'm looking for a way to hide code cells (inputs) when export my .iipynb file to a HTML. I don't want the code cells to be visible at all (not some button that turn them off/on). The output is for people that have no idea what a programming language is. I tried many things that I found on the internet but nothing seems to work. Thanks
type: Question
has answer: http://stackoverflow.com/a/60106597
has answer: http://stackoverflow.com/a/62716293
has answer: http://stackoverflow.com/a/72462601
possible better answer: http://stackoverflow.com/a/58524517
has answer: http://stackoverflow.com/a/77690297

http://stackoverflow.com/comment/86747100
type: Comment
type: QuestionComment
score: 0
has text: your format must match ` 1952-02-04 00:00:00` -add the hours:minutes:seconds format specifier.
comment on: http://stackoverflow.com/q/49865877

http://stackoverflow.com/q/49790212
has title: i want to download file from google drive using Drive Api
tagged with: google-apis-explorer
tagged with: python
has body: in this code : file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M' request = drive_service.files().get_media(fileId=file_id) fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print "Download %d%%." % int(status.progress() * 100) I don't know how to get file_id , I was getting file_id while uploading but now I am not able to figure out how to get file_id of the file which is present on Google Drive. Ex. if my uploaded file has name A001002.pdf , how can i get file id for this file. there is some reference online which i am not able to understand. link: files.list any help?
has answer: http://stackoverflow.com/a/53926460
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49790515
upvote count: 1
score: 1
tagged with: google-api-python-client
favorite count: 0
type: Question
tagged with: google-drive-api
type: UnansweredQuestion
tagged with: google-api

http://stackoverflow.com/a/49883783
type: Answer
answers question: http://stackoverflow.com/q/49883646
score: 2
downvote count: 0
has body: You have a typo in r = praw.reddit(user_agent = "Replyer Bot"). Use: r = praw.Reddit(user_agent = "Replyer Bot") Take a look at the Quick Start page
upvote count: 2

http://stackoverflow.com/comment/86839198
type: Comment
type: QuestionComment
has text: @RafaelC The meaning of `-` are `None` or the equivalent in `pandas` for `Not a date time`
comment on: http://stackoverflow.com/q/49910451
score: 0

http://stackoverflow.com/comment/86764503
has text: Yep I got 120 GB RAM. It does read the entire file, I was just wondering If there is a way to do that faster.
score: 0
comment on: http://stackoverflow.com/q/49874492
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86616316
has text: `.to_dict(orient="list")` should return the values like they want.
type: AnswerComment
comment on: http://stackoverflow.com/a/49800757
score: 1
type: Comment

http://stackoverflow.com/comment/86828761
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49890700
type: Comment
has text: @MichaelSibille: you simply need to define then at any point before you use them.

http://stackoverflow.com/a/49912440
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: The instance member or instance variable of a class is different from class attribute or class property. this mocked the attr only by keeping all class attributes. import mock from app import App from app import Base import unittest from StringIO import StringIO class TestApp(unittest.TestCase): @mock.patch('sys.stdout', new_callable=StringIO) def test_mock_instance_var(self, mocked_stdout): base = Base() app = App() mock_base = mock.MagicMock(name='Base', spec=Base) instance = mock_base.return_value instance.attr.return_value = 'mmm' base.attr = instance.attr.return_value self.assertEqual(base.attr, 'mmm') app.base = base self.assertEqual(app.base.attr, 'mmm') # the print stdout of show() app.base.show() self.assertEqual(mocked_stdout.getvalue(), 'mmm\n')
type: Answer
accepted answer of: http://stackoverflow.com/q/49785120
has comment: http://stackoverflow.com/comment/87122417
answers question: http://stackoverflow.com/q/49785120

http://stackoverflow.com/q/49786260
type: Question
tagged with: vtk
score: 3
has answer: http://stackoverflow.com/a/51511713
accepted answer: http://stackoverflow.com/a/51511713
tagged with: python
has title: using vtkTimerCallback with QVTKRenderWindowInteractor not working
linked to: http://stackoverflow.com/q/51285797
type: AnsweredQuestion
upvote count: 3
downvote count: 0
has body: Ive got a problem with vtk (8.1), pyqt5 (5.10.1). If I use the vtkCallBackTimer with the "original" vtk.vtkRenderWindowInteractor() its all working fine. But if I use the vtk.qt.QVTKRenderWindowInteractor.QVTKRenderWindowInteractor() the callback function is executed successively with no pause. Here is the example: import sys from PyQt5 import QtWidgets import vtk from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor from mainwindow import Ui_MainWindow class vtkTimerCallback(): def __init__(self): self.timer_count = 0 def execute(self, obj, event): print(self.timer_count) self.actor.SetPosition(self.timer_count, self.timer_count, 0) iren = obj iren.GetRenderWindow().Render() self.timer_count += 1 class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super (ExampleApp, self).__init__(parent) self.setupUi(self) sphereSource = vtk.vtkSphereSource() sphereSource.SetCenter(0.0, 0.0, 0.0) sphereSource.SetRadius(5) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(sphereSource.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor # &lt;-- WOKRING renderWindowInteractor = QVTKRenderWindowInteractor(self.frame) # &lt;-- NOT WORKING (self.frame is a QFrame in the mainwindow.ui) renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(actor) renderer.SetBackground(1, 1, 1) # Background color white renderWindow.Render() renderWindowInteractor.Initialize() cb = vtkTimerCallback() cb.actor = actor renderWindowInteractor.AddObserver('TimerEvent', cb.execute) #**************** renderWindowInteractor.CreateRepeatingTimer(1000) #Pause between new function call in millisecs, # with the QVTKRenderWindowInteractor the pause is ignored ????? #**************** renderWindowInteractor.Start() def main(): app = QtWidgets.QApplication(sys.argv) trudeUI …
tagged with: pyqt
answer count: 1
tagged with: callback
favorite count: 0

http://stackoverflow.com/comment/86759544
score: 0
type: Comment
has text: @Nav My solution doesn't includes `driver.find_element_by_id("TribID")` but **By.NAME,"TribName"**
type: AnswerComment
comment on: http://stackoverflow.com/a/49778379

http://stackoverflow.com/a/49792122
accepted answer of: http://stackoverflow.com/q/49791848
answers question: http://stackoverflow.com/q/49791848
type: AcceptedAnswer
downvote count: 0
has body: One possible way is to get a list of the patches using ax.patches. Therefore, you can use the existing list comprehension that you use to remove the patches using your list, but instead replace the list with ax.patches(): for i in range(100): [...] rect_lst = getListOfRandomRects(n='random', dim=img.shape[0:2]) [ax.add_patch(patches.Rectangle((r[0], r[1]), r[2], r[3], linewidth=1, facecolor='none')) for r in rect_lst] plt.pause(0.1) plt.draw() [p.remove() for p in reversed(ax.patches)]
has comment: http://stackoverflow.com/comment/86598854
type: Answer
has comment: http://stackoverflow.com/comment/86650944
score: 11
upvote count: 11

inverse
tags question: http://stackoverflow.com/q/49817984
type: Tag
tag name: inverse

http://stackoverflow.com/comment/86783487
has text: I'll throw that in there!
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49883681

http://stackoverflow.com/a/49910920
score: 2
downvote count: 0
has body: I don't think you've described what you're trying to do adequately. However, IIUC def shifty(d): return d.iloc[(np.arange(len(d)) % 2).argsort(kind='mergesort')] df.groupby(df.ID.str[0], group_keys=False).apply(shifty) ID value 0 A1 11 2 A2 12 4 A3 13 1 A1 11 3 A2 12 5 A3 13 6 B1 21 8 B2 22 10 B3 23 7 B1 21 9 B2 22 11 B3 23 12 C1 31 14 C2 32 16 C3 33 13 C1 31 15 C2 32 17 C3 33
type: Answer
answers question: http://stackoverflow.com/q/49910665
upvote count: 2

http://stackoverflow.com/comment/87190567
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49873779
has text: @EB88, no such luck so far.

http://stackoverflow.com/a/49808253
score: 0
has body: First, your methods should either be static or have self as first argument. Once that is fixed, you could use random.choice instead to choose the method out of a list. This has the advantage of not depending on the methods' names. import random class Calculate: @staticmethod def add(x, y): return x + y @staticmethod def sub(x, y): return x - y @staticmethod def mult(x, y): return x * y @staticmethod def div(x, y): return x/y @classmethod def random_op(cls, x, y): return random.choice([ cls.add, cls.sub, cls.mult, cls.div ])(x, y)
answers question: http://stackoverflow.com/q/49808177
type: Answer

http://stackoverflow.com/comment/86798524
type: Comment
comment on: http://stackoverflow.com/q/49891302
score: 3
type: QuestionComment
has text: Theoretically, the eigenvalue 0 has multiplicity 2, and the eigenspace associated with it is two dimensional. In effect, the codes have found different bases for that eigenspace, but that's OK, because the basis is not unique. (The eigenspace itself is unique.)

http://stackoverflow.com/comment/86724089
comment on: http://stackoverflow.com/q/49840045
score: 0
has text: Hi, none of the solutions to that question seems to work for me. Have already allowed access from less secure apps.
type: Comment
type: QuestionComment

django-rest-framework
tags question: http://stackoverflow.com/q/49857165
tags question: http://stackoverflow.com/q/49817397
tags question: http://stackoverflow.com/q/49903122
tags question: http://stackoverflow.com/q/49885019
tags question: http://stackoverflow.com/q/49895472
tags question: http://stackoverflow.com/q/49909224
tags question: http://stackoverflow.com/q/49771998
tags question: http://stackoverflow.com/q/49797630
tags question: http://stackoverflow.com/q/49869376
tags question: http://stackoverflow.com/q/49828916
tags question: http://stackoverflow.com/q/49796497
tags question: http://stackoverflow.com/q/49778708
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/49892526
tags question: http://stackoverflow.com/q/49904804
tags question: http://stackoverflow.com/q/49880159
tags question: http://stackoverflow.com/q/49761879
tags question: http://stackoverflow.com/q/49805651
tags question: http://stackoverflow.com/q/49913996
tags question: http://stackoverflow.com/q/49873536
tags question: http://stackoverflow.com/q/49898084
tags question: http://stackoverflow.com/q/49791580
type: Tag
tags question: http://stackoverflow.com/q/49772781
tags question: http://stackoverflow.com/q/49910137
tags question: http://stackoverflow.com/q/49853623
tags question: http://stackoverflow.com/q/49820088
tags question: http://stackoverflow.com/q/49902603
tags question: http://stackoverflow.com/q/49862560
tags question: http://stackoverflow.com/q/49875399
tags question: http://stackoverflow.com/q/49878711
tags question: http://stackoverflow.com/q/49797941
tags question: http://stackoverflow.com/q/49897735
tags question: http://stackoverflow.com/q/49902586
tags question: http://stackoverflow.com/q/49780580
tags question: http://stackoverflow.com/q/49813584
tags question: http://stackoverflow.com/q/49793314
tags question: http://stackoverflow.com/q/49765182
tags question: http://stackoverflow.com/q/49824899
tags question: http://stackoverflow.com/q/49770344
tags question: http://stackoverflow.com/q/49879103
tags question: http://stackoverflow.com/q/49840767
tags question: http://stackoverflow.com/q/49891245

http://stackoverflow.com/comment/86804665
comment on: http://stackoverflow.com/q/49878233
score: 0
type: Comment
has text: @YvesDaoust Here is the goal : https://imgur.com/gallery/aLZsN
type: QuestionComment

http://stackoverflow.com/a/49863024
has comment: http://stackoverflow.com/comment/86742008
downvote count: 0
has comment: http://stackoverflow.com/comment/86741606
has comment: http://stackoverflow.com/comment/86742924
has comment: http://stackoverflow.com/comment/86741806
has comment: http://stackoverflow.com/comment/86742860
has comment: http://stackoverflow.com/comment/86742214
has comment: http://stackoverflow.com/comment/86742805
has comment: http://stackoverflow.com/comment/86743039
has comment: http://stackoverflow.com/comment/86742893
has comment: http://stackoverflow.com/comment/86743297
has comment: http://stackoverflow.com/comment/86741363
has comment: http://stackoverflow.com/comment/86741754
type: Answer
has comment: http://stackoverflow.com/comment/86741935
upvote count: 1
has comment: http://stackoverflow.com/comment/86742068
has comment: http://stackoverflow.com/comment/86741820
has comment: http://stackoverflow.com/comment/86741670
has comment: http://stackoverflow.com/comment/86742676
has comment: http://stackoverflow.com/comment/86743187
has comment: http://stackoverflow.com/comment/86743398
answers question: http://stackoverflow.com/q/49862691
has body: I have been practicing flask for last few months. I hope this may help you. I tried to make it simple and easy to understand for you because you are new to Flask. Use render_template to connect your route function with html template ( make sure html template is in templates directory. BackEnd from flask import Flask, render_template app = Flask(__name__) @app.route('/test') def test(): text = 'Hello World' return render_template('test.html', text=text) if __name__ == '__main__': app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True app.debug = True app.run(host='0.0.0.0', port=5000) Inside Jinja template, to print the variable came from backend {{ text }}
score: 1
has comment: http://stackoverflow.com/comment/86742136
has comment: http://stackoverflow.com/comment/86741769

http://stackoverflow.com/q/49904428
answer count: 2
upvote count: 2
downvote count: 0
favorite count: 0
type: Question
has title: Convert standard 24 hour format to a range of 99 python
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86824790
has answer: http://stackoverflow.com/a/49904687
has body: The task is to convert an input in seconds to a time that is readable for humans in the format HH:MM:SS. import time def make_readable(seconds): return time.strftime('%H:%M:%S', time.gmtime(seconds)) So far this is what I have, and it works. The only problem is that the hours should be displayed in a range from 00 - 99, currently it is in 24 hours. e.g. with an input of 359999 seconds, it should output 99:59:59. This is also the maximum time by the way. Errors: '00:00:00' should equal '24:00:00' '03:59:59' should equal '99:59:59' '20:36:54' should equal '44:36:54' Question: How to put the hours in the 99 format?
has answer: http://stackoverflow.com/a/49904588
has comment: http://stackoverflow.com/comment/86824688
score: 2

http://stackoverflow.com/comment/86703025
type: Comment
type: AnswerComment
score: 0
has text: Thanks ..But i wrote it wrong by mistake on here ..on the actual code that i have on python i wrote it right
comment on: http://stackoverflow.com/a/49844193

http://stackoverflow.com/q/49771837
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/86562878
has comment: http://stackoverflow.com/comment/86564299
tagged with: matplotlib
answer count: 1
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/86563135
has title: Using PyQt5 to embed a dynamical bar chart
has body: I wrote the following code in python to show a bar chart in the GUI generated by PyQt5. import sys from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout, \ QLineEdit, QMessageBox, QInputDialog, QLabel, QHBoxLayout, QGridLayout, QStackedLayout, QFormLayout from PyQt5 import QtCore, QtGui, QtWidgets import time import matplotlib matplotlib.use("TkAgg") from matplotlib.lines import Line2D import matplotlib.animation as animation from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar import matplotlib.pyplot as plt # data import numpy as np #import matplotlib.pyplot as plt import pandas as pd import os import csv #define the path to data pathToData='C:/RC/python/data/' dataName= '31122017ARB.csv' # import data=pd.read_csv(pathToData+dataName, delimiter=';',encoding='cp1252') # percent MW data['MWP']=data[' MW ']/sum(data[' MW ']) #aggregate by Best datag=data.groupby('Best', as_index=False).agg({'MW': 'sum'}) x=["BE"+s for s in[str(s) for s in [int(x) for x in datag.iloc[:,0].tolist()]]] y=datag.ix[:,1].tolist() figure = plt.figure() H = np.array([[100, 2, 39, 190], [402, 55, 369, 1023], [300, 700, 8, 412], [170, 530, 330, 1]]) Z = np.array([[3, 290, 600, 480], [1011, 230, 830, 0], [152, 750, 5, 919], [340, 7, 543, 812]]) class Window(QDialog): def __init__(self, parent=None): super(Window, self).__init__(parent) # a figure instance to plot on self.figure = plt.figure() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init_ self.im = None self.canvas = FigureCanvas(self.figure) self.canvas.mpl_connect('button_press_event', self.on_button_press_event) # this is the Navigation widget # it takes the Canvas widget and a parent self.toolbar = NavigationToolbar(self.canvas, self) self.timer = QtCore.QTimer(self) self.timer.timeout.connect(self.plot) self.timer.setInterval(5000) # Jus…
has comment: http://stackoverflow.com/comment/86763828
accepted answer: http://stackoverflow.com/a/50096183
type: Question
has comment: http://stackoverflow.com/comment/86558920
tagged with: python
has comment: http://stackoverflow.com/comment/86627339
favorite count: 0
has answer: http://stackoverflow.com/a/50096183

http://stackoverflow.com/q/49800444
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86615842
score: 4
has body: I am writing in python and have all my functionalities for analyzing datasets. Now, I would like to turn these functions into a user-ready application that, in a sense, works like an .exe app. In bokeh, I saw that you could create a plot, table...etc; however, is it possible to create a GUI where you can: upload a file for analysis load functions from my written python to analyze the uploaded file graph the results onto a graph click different buttons that can take you to different (so-called) pages so that you can perform different functions. basically it can go from one page to the other kind of like a webpage where you click one button it links you to the next page for another purpose and home to go back. Could you potentially do this with bokeh?
has answer: http://stackoverflow.com/a/49801008
has title: Bokeh and how to make it into a GUI
tagged with: windows
tagged with: user-interface
downvote count: 0
answer count: 1
tagged with: bokeh
favorite count: 0
type: Question
upvote count: 4
tagged with: testing
has comment: http://stackoverflow.com/comment/86616236

http://stackoverflow.com/comment/86766153
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49874809
score: 0
has text: @J...S I have added some more info to answer. Please check that

http://stackoverflow.com/a/49844193
answers question: http://stackoverflow.com/q/49844007
has comment: http://stackoverflow.com/comment/86703025
type: Answer
has body: I don't see where this error comes from, however, more likely an error will occur due to your misspelling of "temp_string" as "temp_sting", which will of course throw a NameError later
score: 0

http://stackoverflow.com/q/49829286
has answer: http://stackoverflow.com/a/50083558
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: nan
favorite count: 0
type: Question
downvote count: 0
tagged with: null
upvote count: 1
type: UnansweredQuestion
tagged with: simplejson
answer count: 1
has body: I have been using the simplejson module to correctly handle all NaN --> null conversions (going from python to json). Specifically: I've been using the ignore_nan=True flag in the simplejson.dump function). I can't seem to find the equivalent functionality going the other way i.e. from JSON null to a nan - with the simplejson.load function. The default seems to be to read in the nulls to None. How to accomplish this?
has title: Convert JSON null to nan in simplejson.load()?

http://stackoverflow.com/q/49866943
has comment: http://stackoverflow.com/comment/86749422
downvote count: 1
favorite count: 0
type: Question
tagged with: linux
upvote count: 0
has title: How do I select the correct version of python from Linux Terminal
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49866984
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/49866962
has body: I'm trying to install Azure SDK on raspberry pi. I'm following this [tutorial][1] I am at this part where I need to select Python 3.5, but I don't know how to properly enter it into the terminal. You can also specify the version you want by running sudo ./setup.sh [--python-version|-p] [2.7|3.4|3.5]. If you run script without parameter, the script will automatically detect the version of python installed (Search sequence 2.7->3.4->3.5). Make sure your Python version keeps consistent during building and running.
possible better answer: http://stackoverflow.com/a/49866984
has answer: http://stackoverflow.com/a/49866962

http://stackoverflow.com/q/49882737
has comment: http://stackoverflow.com/comment/86781521
upvote count: 1
duplicate of: http://stackoverflow.com/q/31964108
has comment: http://stackoverflow.com/comment/86781566
has body: When trying to execute a python file through a paramiko SSHClient, I'm getting the error: ImportError: No module named rospy In the line of that file that contains the rospy import. I'm only getting this error when trying to run the code using paramiko i.e: ssh=paramiko.SSHClient() ssh.connect(ipaddress,22,username,pw) stdin, stdout, stderr = ssh.exec_command('python path/to/file.py') When executing the command through a terminal, it works as desired. I only get the import error when trying to use paramiko. I'm unsure as to why this is occurring and any assistance would be greatly appreciated. Thanks. Edit: further tinkering and experimentation has shown that it is a path issue, but the path for both the computer I am using and the target device are the same, but when I run echo $PATH on paramiko, the path element /opt/ros/indigo/bin/ is not included
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
has title: Unable to import module when using paramiko sshclient
tagged with: python
tagged with: paramiko
has comment: http://stackoverflow.com/comment/86781789
has comment: http://stackoverflow.com/comment/86783046
has comment: http://stackoverflow.com/comment/86781928
answer count: 0
score: 1

http://stackoverflow.com/comment/86784661
type: QuestionComment
has text: I cleaned up the text and reformatted the URL as code.
score: 0
comment on: http://stackoverflow.com/q/49855199
type: Comment

http://stackoverflow.com/q/49761020
has comment: http://stackoverflow.com/comment/86546188
type: Question
has comment: http://stackoverflow.com/comment/86540900
upvote count: 2
has comment: http://stackoverflow.com/comment/86539421
type: UnansweredQuestion
tagged with: curve-fitting
tagged with: python
has title: scipy.optimize curve_fit return initial values of params
has comment: http://stackoverflow.com/comment/86540121
has body: I'm trying to switch from wolfram mathematica to python. I wrote a program that calculates the IR spectrum of reflection. Now I need to make sure that the program adjusts the theoretical spectrum to the experimental one. For this, I decided to use curve_fit. But the problem is that curve_fit returns the initial value and does not even try to fit the parameter to the desired value. Can you help me in solving this problem? fir.py import numpy as np import time import inspect import matplotlib.pyplot as plt from scipy.optimize import curve_fit from math import pi from stack import stack from tmm.parser import n_parser from tmm.refindex import n_calc from tmm.cohtmm import tmm start_time = time.time() print(f'===========START PROGRAM=============') STACK = stack def fit_func(x_data, x): frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) print(f'Value - {x}') parse_stack = n_parser(STACK, values) d = [] # thickness for layer in parse_stack: if layer != 1: d.append(layer['d']) else: d.append(np.inf) r = np.array([]) for w in x_data: n = np.array([]) for layer in parse_stack: if layer != 1: n_value, eps = n_calc(layer.get('n'), w) n = np.append(n, n_value) else: n = np.append(n, 1) # get reflectance power l_vac = 10 ** (-2) / w r_val = tmm('s', n, d, theta, l_vac) r = np.append(r, r_val) return r """ Input parameters """ degree = pi / 180 theta = 13 * degree # incidence angle pol = 's' # polarisation exp_file_name = 'result.txt' # experiment filename # w_min = 350 # from wavelength # w_max = 4000 # to wavelength # Load and plot experimental result to np.array exp_x, exp_y = np.loadtxt(exp_file_name, delimiter=' ', unpack=True) init_values = [400] low = [180] high = [888] popt, pcov = curve_fit(fit_func, exp_x, exp_y, p0=init_values, bounds=(low, high)) print(f'=========END ({round((time.time() - start_time), 3)} seconds)===========') plt.figure() plt.plot(exp_x, exp_y, exp_x, fit_func(exp_x, *popt)) plt.show() stack.py from numpy import inf sub…
answer count: 0
has comment: http://stackoverflow.com/comment/86539999
score: 1
downvote count: 1
tagged with: scipy
favorite count: 0

http://stackoverflow.com/comment/86783221
type: Comment
type: AnswerComment
has text: Fair enough, I will go crawl back in my hole instead of trying to be helpful. In the meantime, perhaps you could do something helpful @jpp? Or do you prefer to nitpick answers instead of making them.
comment on: http://stackoverflow.com/a/49882977
score: 0

http://stackoverflow.com/comment/86571535
type: QuestionComment
has text: You're not passing any `data` to `rt()`.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49778093

http://stackoverflow.com/comment/86601548
has text: Please change `c:\python32\tools\Scripts` to c:\python32\Scripts and it open a new terminal and it should work for you . also navigate to c:\python32\Scripts folder and check if easy_install exists or not
comment on: http://stackoverflow.com/q/49793017
score: 0
type: Comment
type: QuestionComment

gradient-descent
tags question: http://stackoverflow.com/q/49865952
tag name: gradient-descent
tags question: http://stackoverflow.com/q/49847953
tags question: http://stackoverflow.com/q/49862270
type: Tag

http://stackoverflow.com/q/49909507
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86835485
has comment: http://stackoverflow.com/comment/86834972
has comment: http://stackoverflow.com/comment/86835153
has body: I'm attempting to compare two txt files and find the new lines from one file and write them into a new file. I noticed that the new lines are written in a different order every time I run the program. Is there a way to preserve the original order? I noticed that the disorder stems from read().splitlines() on lines 2 and 3. My code: with open("C:/Temp/1_attlog.dat", "r") as f1, open("C:/Temp/attlog.dat","r") as f2, open("C:/Temp/attlog_new.dat", "w") as n: f_a = set(f1.read().splitlines()) f_b = set(f2.read().splitlines()) for line in f_a: count_line += 1 if line not in f_b: print(line) count_new_lines += 1 n.writelines(line)
has answer: http://stackoverflow.com/a/49909766
tagged with: python
score: -1
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 2
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/49909766
has title: How to retrieve each line of a text file in order [python 3]

http://stackoverflow.com/comment/86772391
comment on: http://stackoverflow.com/q/49878281
score: 1
type: QuestionComment
type: Comment
has text: Removing from a list while iterating through it doesn't work well. Better to just use listcomp. [i for i in data nums.issubset(i)]

http://stackoverflow.com/q/49890996
linked to: http://stackoverflow.com/q/47318119
has comment: http://stackoverflow.com/comment/94092479
score: 3
tagged with: python-2.7
answer count: 0
tagged with: pandas
upvote count: 3
has comment: http://stackoverflow.com/comment/90238109
has comment: http://stackoverflow.com/comment/94301505
downvote count: 0
has comment: http://stackoverflow.com/comment/91522003
has title: python ImportError: C extension: No module named timedeltas not built
favorite count: 0
type: Question
has body: These days I want to use pyinstaller package my code into .exe file. After I run the .exe file tell me this problem. So how do I solve this problem. (I use python 2.7.14) Thanks
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/94257045
tagged with: python

http://stackoverflow.com/comment/86742520
has text: Instead of iterating over all the scales in your list, just print the value of `event.widget`.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49863501

http://stackoverflow.com/comment/86730700
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49858009
has text: Yes I did, have alluded to that in the question now

http://stackoverflow.com/q/49809148
has body: I have been examining the latest version of retrain.py from tensorflow, but I ran into confusion between trained graph and saved model. To elaborate: In Line 1307 in retrain.py, we give the path to save our "trained graph". This is saved as a .pb file. This graph we then use to further classify our dataset (using label_image.py) In the new version of retrain.py, there is also a saved_model path (In Line 1482). This also saves a .pb file. The code explains that it is an "exported model" for "serving". I do not understand the difference between the two .pb files (output_graph.pb and saved_model.pb) the code generates. What is the importance of saved_model.pb and where it can be used? What does "serving" mean here? Any explanation or probably links to explanation would be of great help. Thanks N Regards, Pradip
tagged with: tensorflow
type: Question
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/87814582
has title: Transfer Learning API for Image Classification from Tensorflow
answer count: 1
has answer: http://stackoverflow.com/a/52691601
accepted answer: http://stackoverflow.com/a/52691601

http://stackoverflow.com/q/49856936
tagged with: scikit-learn
tagged with: decision-tree
has body: I have a numpy array of dimension (81,38) as a training data features, and another list of length 82 as the labels. I trained my DecisionTreeClassifier using them, and I want to visualize the tree, but the following error appeared: edges = np.collections.defaultdict(list) AttributeError: module 'numpy' has no attribute 'collections' this is my code: from sklearn import tree df = df.from_csv("file_path.csv") clf = tree.DecisionTreeClassifier() df = df.as_matrix() print(df.shape) print(len(train_df['label'].values.tolist())) clf = clf.fit(df,train_df['label'].values.tolist()) data_feature_names = [ 'goEmbed1', 'goalexa1', 'goscapy1', 'goEmbed2', 'goalexa2', 'goscapy2', 'goEmbed3', 'goalexa3', 'goscapy3', 'goEmbed4', 'goalexa4', 'goscapy4', 'goEmbed5', 'goalexa5', 'goscapy5', 'goStdAlex', 'goAvgAlexa', 'goStdCos','goAvgCos', 'bingEmbed1', 'bingalexa1', 'bingscapy1', 'bingEmbed2', 'bingalexa2', 'bingscapy2', 'bingEmbed3', 'bingalexa3', 'bingscapy3', 'bingEmbed4', 'bingalexa4', 'bingscapy4', 'bingEmbed5', 'bingalexa5', 'bingscapy5', 'bingStdAlex', 'bingAvgAlexa', 'bingStdCos','bingAvgCos'] # Visualize data dot_data = tree.export_graphviz(clf, feature_names=data_feature_names, out_file=None, filled=True, rounded=True) graph = pydotplus.graph_from_dot_data(dot_data) colors = ('turquoise', 'orange', 'red', 'yellow','blue','purple') edges = np.collections.defaultdict(list) for edge in graph.get_edge_list(): edges[edge.get_source()].append(int(edge.get_destination())) for edge in edges: edges[edge].sort() for i in range(2): dest = graph.get_node(str(edges[edge][i]))[0] dest.set_fillcolor(colors[i]) graph.write_png('tree2.png') I tested my code on another example of data, and It works perfectly, but I don't know that is the problem here. This is the testing data that I used: X = [ [180, 15,0], [177, 42,0], [136, 35,1], [174, 65,0], [141, 28,1]] Y = ['man', 'woman', 'woman', 'man', 'woman']
type: AnsweredQuestion
tagged with: data-visualization
tagged with: python
accepted answer: http://stackoverflow.com/a/49856967
possible better answer: http://stackoverflow.com/a/49856971
has answer: http://stackoverflow.com/a/49856967
has answer: http://stackoverflow.com/a/49856971
type: Question
tagged with: numpy
score: 0
answer count: 2
has title: Module 'numpy' has no attribute 'collections', plotting a decision tree

http://stackoverflow.com/q/49883378
has title: breakpoints not working in pycharm
tagged with: breakpoints
upvote count: 0
tagged with: flask-socketio
answer count: 1
has answer: http://stackoverflow.com/a/49884223
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86783000
tagged with: pycharm
type: UnansweredQuestion
has body: I have a flask-socketIO application where the breakpoints in my socket.py file are not working. in __init__.py i have the following code: from flask import Flask from flask_socketio import SocketIO async_mode = None app = Flask(__name__) app.config.from_object('config') socketio = SocketIO(app, async_mode=async_mode) from .auth import SamlManager saml_manager = SamlManager() saml_manager.init_app(app) from app import views, socket, saml_func &lt;end&gt; socket.py: from app import socketio @socketio.on('my_event', namespace='/socket') def test_message(message): emit('my_response', {'data': 'received data'}) if I put a breakpoint anywhere in socket.py, including the imports However, any other code such as views.py, breakpoints are working views.py: from app import app, socketio, saml_manager from flask import render_template @app.route('/', methods=['GET', 'POST']) @app.route('/index', methods=['GET', 'POST']) @saml_manager.login_required def index(): return render_template('index.html', async_mode=socketio.async_mode) Any idea why breakpoints would not be working for socket but would be working for views since I am calling them the same way?
tagged with: python
score: -1
tagged with: flask

http://stackoverflow.com/a/79006156
answers question: http://stackoverflow.com/q/49819971
type: Answer
score: 0
has body: I encountered the same issue, and after reading Nathan's comment, I realized I had a similar problem: my file was also empty. In my case, I was using Git LFS to track .png files, and they were added as LFS files. To resolve the issue, I had to explicitly pull those files using the following command: git lfs pull --include "/path/to/files" Once the files were properly downloaded, everything worked as expected.

http://stackoverflow.com/q/49879944
has comment: http://stackoverflow.com/comment/86788316
has body: Consider the following code import timeit import numpy as np MyArray = np.empty((10000, 10000, 1)) print((MyArray.size, MyArray.shape, MyArray.dtype, np.isfortran(MyArray))) print(timeit.timeit(lambda: MyArray[0], number=10000)) print(timeit.timeit(lambda: MyArray.take(0), number=10000)) MyTwoArrays = np.empty((10000, 10000, 2)) MyArray = np.split(MyTwoArrays, 2, axis=2)[0] print((MyArray.size, MyArray.shape, MyArray.dtype, np.isfortran(MyArray))) print(timeit.timeit(lambda: MyArray[0], number=10000)) print(timeit.timeit(lambda: MyArray.take(0), number=1)) and its output on my system: (100000000, (10000, 10000, 1), dtype('float64'), False) 0.05690493136299911 0.06236779451013045 (100000000, (10000, 10000, 1), dtype('float64'), False) 0.0569617025453055 1.6303121549025763 The two versions of MyArray are the same size, shape, data type and data ordering. Still, obtaining the 0th element is 300,000 times slower when using numpy.take with the result of numpy.split, compared to simple indexing with that same result or numpy.take with a "native" numpy array. Why is that? Can I fix that? Update: This seems to be related to views: MyArray = MyArray.copy() fixes the problem. Still, I am interested in why [0] works equally as fast, while numpy.take slows down for views. Another update: I have noticed that the slow-down depends on the array dimension (not the number of array dimensions, but the number of array elements). I achieve access times of up to 8 seconds for a single 0th element. I find this is the most surprising aspect of this issue. Whatever numpy.take does internally, I see no reason why this additional "level of indirection" should be slower to compute when indices are larger. Third update: Following @hpaulj's comment that MyArray.take(0) and MyArray[0] are not equivalent, here is a corrected code example. (I had made that mistake by means of my MATLAB intuition and stopped verifying my minimal example at one point. I do not want to replace the original example si…
tagged with: python
has answer: http://stackoverflow.com/a/49884403
has comment: http://stackoverflow.com/comment/86781757
possible better answer: http://stackoverflow.com/a/49880605
score: 2
tagged with: numpy
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49880605
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49884403
downvote count: 0
has title: Why is numpy.take slow on the result of numpy.split when simple indexing is not?
favorite count: 0
type: Question
tagged with: performance
tagged with: multidimensional-array

http://stackoverflow.com/comment/86775402
type: AnswerComment
has text: but is this a script?
comment on: http://stackoverflow.com/a/49879822
score: 0
type: Comment

http://stackoverflow.com/comment/86573103
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49778816
score: 0
has text: Thats because Django prefix the table name with the appname, i think

http://stackoverflow.com/comment/86754348
comment on: http://stackoverflow.com/q/49869562
type: QuestionComment
type: Comment
has text: Please post the snippet of the actual error as printed in full stack trace.
score: 0

http://stackoverflow.com/a/49867504
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49867472
has body: On my first answer I showed you how to get specific columns, my bad. I misread your question. In order to get specific rows, you can use list comprehension. desired_row_indexes = [1, 2, 3, 10, 11, 12] # You can also use ranges desired_rows = [row for idx, row in enumerate(csv_document) if idx in desired_row_indexes] This is actually duplicated
type: Answer
answers question: http://stackoverflow.com/q/49867472
upvote count: 2
score: 1

http://stackoverflow.com/comment/86774924
score: 0
has text: What do you want to do ? Because it seems unclear to me what you're asking. You want to compare 2 HTML copies ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49879471

http://stackoverflow.com/a/49866515
upvote count: 2
score: 2
downvote count: 0
has body: I'll let you take it from here, but this should at least get you going. Note: I see there is some confusion around what variable you are predicting. For this I was predicting the 'Y' which is usually standard. If that's incorrect, just swap the order prior to putting into the create_sequences function. The code should still work, and this is just a starting point for you anyways, you'll need to play around with it quite a bit more to get a good performing network. import numpy as np from keras.models import Sequential from keras.layers import LSTM, Dense from sklearn.preprocessing import MinMaxScaler import pandas as pd np.random.seed(7) df = pd.read_csv('test32_C_data.csv') n_features = 100 def create_sequences(data, window=14, step=1, prediction_distance=14): x = [] y = [] for i in range(0, len(data) - window - prediction_distance, step): x.append(data[i:i + window]) y.append(data[i + window + prediction_distance][0]) x, y = np.asarray(x), np.asarray(y) return x, y # Scaling prior to splitting scaler = MinMaxScaler(feature_range=(0.01, 0.99)) scaled_data = scaler.fit_transform(df.loc[:, ["Y", "X"]].values) # Build sequences x_sequence, y_sequence = create_sequences(scaled_data) # Create test/train split test_len = int(len(x_sequence) * 0.15) valid_len = int(len(x_sequence) * 0.15) train_end = len(x_sequence) - (test_len + valid_len) x_train, y_train = x_sequence[:train_end], y_sequence[:train_end] x_valid, y_valid = x_sequence[train_end:train_end + valid_len], y_sequence[train_end:train_end + valid_len] x_test, y_test = x_sequence[train_end + valid_len:], y_sequence[train_end + valid_len:] # Initialising the RNN model = Sequential() # Adding the input layerand the LSTM layer model.add(LSTM(4, input_shape=(14, 2))) # Adding the output layer model.add(Dense(1)) # Compiling the RNN model.compile(loss='mse', optimizer='rmsprop') # Fitting the RNN to the Training set model.fit(x_train, y_train, epochs=5) # Getting the predicted values y_pred = model.predict(x_test) # P…
has comment: http://stackoverflow.com/comment/86750819
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86789293
accepted answer of: http://stackoverflow.com/q/49862326
has comment: http://stackoverflow.com/comment/86786993
has comment: http://stackoverflow.com/comment/86824513
has comment: http://stackoverflow.com/comment/86820688
answers question: http://stackoverflow.com/q/49862326
type: Answer

http://stackoverflow.com/comment/86664621
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49824331
score: 0
has text: tabs and four spaces are interchangeable, either one works, just make sure you keep it consistent throughout your program

http://stackoverflow.com/q/49799589
has answer: http://stackoverflow.com/a/49804534
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86617712
linked to: http://stackoverflow.com/q/8989825
favorite count: 0
has answer: http://stackoverflow.com/a/49805268
linked to: http://stackoverflow.com/q/18485841
type: Question
has body: I dont know why every time i create a project with this command, it creates an empty folder: django-admin start-project myProject These are the files that I have in my directory: What I noticed is that I do not have the django-admin.py file, is that normal? why when I execute the command, it does not throw me any error? When I go to see the folder created previously, I find an empty folder:
has answer: http://stackoverflow.com/a/49801064
type: UnansweredQuestion
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/3681216
has title: when create a project in django, create a empty folder
answer count: 3

http://stackoverflow.com/comment/86729282
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49857222
type: AnswerComment
has text: or `[list(map(lambda x: x.rsplit('_', 1)[-1], k)) for k, _ in [a, b, c]]` which might be slightly faster. Nevertheless, +1

http://stackoverflow.com/comment/86844705
score: 0
comment on: http://stackoverflow.com/q/49914533
type: Comment
type: QuestionComment
has text: You can use if...elif.....else

http://stackoverflow.com/a/49785737
answers question: http://stackoverflow.com/q/49785391
type: Answer
has body: If its in the format like "12 Apr 2018" then you might be better off using strptime(). You might need to use regex though if its surrounded by other page content. datetime.datetime.strptime("12 Apr 2018", "%d %b %Y") Which will give you back a datetime object like below datetime.datetime(2018, 4, 12, 0, 0)
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/49843027
favorite count: 0
type: Question
tagged with: python-3.x
has title: Using json_normalize for structured multi level dictionaries with lists
has body: I've successfully transferred the data from a JSON file (structured as per the below example), into a three column ['tag', 'time', 'score'] DataFrame using the following iterative approach: for k, v in enumerate(my_request['content']): for k1, v1 in enumerate(v['data']['score']): df.loc[len(df)] = [v['tag_id'], v1['time'], v1['value']] However, while this ultimately achieves the desired result, it takes a huge amount of time to iterate through larger files with the same structure. I'm assuming that an iterative approach is not the ideal way to tackle this sort of problem. Using pandas.io.json.json_normalize instead, I've tried the following: result = json_normalize(my_request, ['content'], ['data', 'score', ['time', 'value']]) Which returns KeyError: ("Try running with errors='ignore' as key %s is not always present", KeyError('data',)). I believe I've misinterpreted the pandas documentation on json_normalize, and can't quite figure out how I should pass the parameters. Can anyone point me in the right direction? (alternatively using errors='ignore' returns ValueError: Conflicting metadata name data, need distinguishing prefix.) JSON Structure { 'content':[ { 'data':{ 'score':[ { 'time':'2015-03-01 00:00:30', 'value':75.0 }, { 'time':'2015-03-01 23:50:30', 'value':58.0 } ] }, 'tag_id':320676 }, { 'data':{ 'score':[ { 'time':'2015-03-01 00:00:25', 'value':78.0 }, { 'time':'2015-03-01 00:05:25', 'value':57.0 } ] }, 'tag_id':320677 } ], 'meta':None, 'requested':'2018-04-15 13:00:00' }
tagged with: python
accepted answer: http://stackoverflow.com/a/49844423
has answer: http://stackoverflow.com/a/49844423
score: 2
type: AnsweredQuestion
tagged with: pandas
upvote count: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/a/49874930
score: 0
type: AcceptedAnswer
has body: Enter num 1Traceback (most recent call last): You pass your script in through stdin and you also want your user input on stdin. input raised it since it got nothing. In any case, you could use a different construct (like process substitution) to "embed" that python code. E.g.: ... python2 &lt;(cat &lt;&lt;"EOF" a=int(input('Enter num 1')) b=int(input('Enter num 2')) print('a=%d ' % a) print('b=%d ' % b) EOF ) ... That won't fail, but is likely not doing what I assume is you wanted it to do. Take the prints and use them to redefine the values of bash variables. For that you would have to wrap the whole python call in another pair if $(...) for command substitution. However, that would also gobble your input prompts (making them invisible and confusing the heck out of shell). I do not think input let's you use stderr for prompts to get around that. (It also has another problem of performing eval on the input, which could expose you to whole array of other problems and is probably not a function you want to use in this case). I am not entirely sure where this script was heading, but I hope this gives you something to go on with.
has comment: http://stackoverflow.com/comment/86765935
accepted answer of: http://stackoverflow.com/q/49874711
type: Answer
answers question: http://stackoverflow.com/q/49874711
has comment: http://stackoverflow.com/comment/86766400

http://stackoverflow.com/comment/86589358
score: 0
type: Comment
has text: @martineau: The answer should now be much less speculative.
type: AnswerComment
comment on: http://stackoverflow.com/a/49786016

http://stackoverflow.com/q/49893460
answer count: 1
tagged with: wxpython
has answer: http://stackoverflow.com/a/49972445
favorite count: 0
type: Question
tagged with: cartopy
has title: An simple interface plotted by matplotlib and cartopy isn't showed in wxpython
tagged with: matplotlib
has body: I'm completely a newcomer in wxpython.The following codes show a simple plot: #-*-coding:utf-8-*- import matplotlib.pyplot as plt import matplotlib.ticker as mticker import cartopy.crs as ccrs from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER from matplotlib.offsetbox import AnnotationBbox,OffsetImage from PIL import Image fig=plt.figure(figsize=(20,10)) ax = plt.axes(projection=ccrs.PlateCarree()) ax.coastlines() ax.stock_img() gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=15, linestyle='--') gl.xlabels_top = False gl.ylabels_left = False gl.xlines = False gl.xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180]) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 15, 'color': 'gray'} gl.xlabel_style = {'color': 'red', 'weight': 'bold'} img=Image.open(r'E:\python_file\untitled\p.png') imagebox=OffsetImage(img,zoom=0.05) imagebox.image.axes=ax ab=AnnotationBbox(imagebox,[55,10],pad=0,frameon=False) ax.add_artist(ab) plt.show() I have tried to make it showed in wxpython,but it doesn't work.The following codes are what i have tried.It's unnecessary to revise the codes,because many wrong codes may be found.I just want to identify the truth i have tried. #-*-coding:utf-8-*- import matplotlib.pyplot as plt import matplotlib.ticker as mticker import cartopy.crs as ccrs from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER from matplotlib.offsetbox import AnnotationBbox,OffsetImage from PIL import Image import wx class Canvas(wx.Panel): def __init__(self,parent): self.fig=plt.figure(figsize=(20,10)) self.ax = plt.axes(projection=ccrs.PlateCarree()) self.ax.coastlines() self.ax.stock_img() self.gl = self.ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=15, linestyle='--') self.gl.xlabels_top = False self.gl.ylabels_left = False self.gl.xlines = False self.gl.xlocator = mticker.FixedLocator([-180, -4…
tagged with: python
accepted answer: http://stackoverflow.com/a/49972445
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/49874809
score: 2
has body: I think you can try something like this: vocab = set() for x in arr: vocab.update(nltk.word_tokenize(x)) set.update() takes an iterable to add elements to existing set. Update: Also, you can look at the working of CountVectorizer in scikit-learn which: converts a collection of text documents to a matrix of token counts. And it uses a dictionary to keep track of the unique words: # raw_documents is an iterable of sentences. for doc in raw_documents: feature_counter = {} # analyze will split the sentences into tokens # and apply some preprocessing on them (like stemming, lemma etc) for feature in analyze(doc): try: # vocabulary is a dictionary containing the words and their counts feature_idx = vocabulary[feature] ... ... And I think it works pretty efficiently. So I think you can also use a dict() instead of set. I am not familiar with working of NLTK, but I think that must also contain something equivalent to CountVectorizer.
upvote count: 2
answers question: http://stackoverflow.com/q/49874500
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86766153

http://stackoverflow.com/a/52601122
answers question: http://stackoverflow.com/q/49803270
type: Answer
has body: According to the anaconda cloud website glmnet package the available version for mac and Ubuntu users. It's not available yet for Windows users. The only way is to install the r version of it with anaconda r-glmnet. conda install -c r r-glmnet
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49818553
answer count: 1
has title: Python setup.py: how to include local package dependency?
downvote count: 0
has comment: http://stackoverflow.com/comment/86655101
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86652299
has body: The question is pretty much self explanatory. I have got a .zip package dependency that I need to include in my python package installation. So how do I include this local dependency in my setup.py? I have got install_requires but this loads my dependency packages from PyPI which is not what I want in this case. The most relevant files in my project are structured as follows: myproject |- setup.py |- mypackage |- __init__.py |- vendor |- __init__.py |- dependencies |- StreamingDataReader.zip I then tried ... include_package_data=True, package_data={ 'StreamingDataReader': ['mypackage/vendor/dependencies/StreamingDataReader.zip'], } ... with no success. My code can't still locate the package: ImportError: No module named 'StreamingDataReader'
has comment: http://stackoverflow.com/comment/86653369
tagged with: setup.py
upvote count: 2
has comment: http://stackoverflow.com/comment/86655270
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67334326
tagged with: python
has comment: http://stackoverflow.com/comment/86653066
has comment: http://stackoverflow.com/comment/86651753
has comment: http://stackoverflow.com/comment/86655409
score: 2
has comment: http://stackoverflow.com/comment/86654515
has comment: http://stackoverflow.com/comment/86653189

http://stackoverflow.com/comment/86840904
has text: That would be the problem. Pip is installing packages for python version 2, but you're using python 3. Does your system have a `pip3` command?
type: QuestionComment
comment on: http://stackoverflow.com/q/49911823
type: Comment
score: 0

http://stackoverflow.com/q/49779981
tagged with: python
has body: I have compiled a small code using the mode function from the statistics library in python. The code is basically taking input from sensors, listing them in an array of 10 inputs and then finding the mode in that list. The problem is that as soon as there are 2 equally common values, the codes gives "StatisticsError: no unique mode". Instead of giving an error, I want it to print the data with the lesser value. This might be possible if I could access the list which the mode function makes and then compare the "2 or more modes", but I don't quite know how to do that. import RPi.GPIO as GPIO import time import math import statistics GPIO.setmode(GPIO.BCM) TRIGA = 23 ECHOA = 24 TRIGB = 17 ECHOB = 27 dist_lista=[] dist_listb=[] print "Distance Measurement In Progress" GPIO.setup(TRIGA,GPIO.OUT) GPIO.setup(ECHOA,GPIO.IN) GPIO.setup(TRIGB,GPIO.OUT) GPIO.setup(ECHOB,GPIO.IN) GPIO.output(TRIGA, False) print "Waiting For Sensor To Settle" time.sleep(1) GPIO.output(TRIGB, False) time.sleep(1) def roundoff(x): return int(math.ceil(x/10.0))*10 def function(TRIG, ECHO, var): dist_list = [] for i in range (0,10): GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO)==0: pulse_start = time.time() while GPIO.input(ECHO)==1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 distance = roundoff(distance) dist_list.append(distance) time.sleep(0.01) if(distance&lt;350 and distance&gt;40): try: print "Distance",var, ":", statistics.mode(dist_list),"cm" except statistics.StatisticsError as e: print "Error: ", e time.sleep(0.1) while True: function(TRIGA, ECHOA, "A") function(TRIGB, ECHOB, "B") GPIO.cleanup() Thank you in advance
tagged with: statistics
score: 2
upvote count: 2
tagged with: gpio
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49781602
has title: Statistics Mode function Exceptions in Python
type: UnansweredQuestion
tagged with: math

image
tags question: http://stackoverflow.com/q/49828748
tags question: http://stackoverflow.com/q/49878233
tags question: http://stackoverflow.com/q/49863767
tags question: http://stackoverflow.com/q/49800308
tags question: http://stackoverflow.com/q/49802395
tags question: http://stackoverflow.com/q/49892205
tags question: http://stackoverflow.com/q/49898283
tags question: http://stackoverflow.com/q/49819314
tags question: http://stackoverflow.com/q/49779430
tags question: http://stackoverflow.com/q/49844449
tags question: http://stackoverflow.com/q/49913079
tags question: http://stackoverflow.com/q/49797743
tags question: http://stackoverflow.com/q/49812913
tags question: http://stackoverflow.com/q/49782232
tags question: http://stackoverflow.com/q/49769496
tags question: http://stackoverflow.com/q/49845169
tags question: http://stackoverflow.com/q/49845734
tags question: http://stackoverflow.com/q/49867706
tags question: http://stackoverflow.com/q/49893501
tags question: http://stackoverflow.com/q/49854608
tag name: image
tags question: http://stackoverflow.com/q/49785496
tags question: http://stackoverflow.com/q/49795388
tags question: http://stackoverflow.com/q/49803139
tags question: http://stackoverflow.com/q/49905149
type: Tag
tags question: http://stackoverflow.com/q/49889908
tags question: http://stackoverflow.com/q/49830808

http://stackoverflow.com/a/49815360
has body: You need to iterate your traversals. In other words, when you make this kind of assignment: a = g.addV('person').property('name', 'Tushar').property('pronoun', 'me') nothing gets sent to the server and "a" does not contain your new vertex. You've simply assigned a Traversal instance to "a" - see this demonstrated in the following in Groovy: gremlin&gt; t = g.addV('person').property('name','tushar').property('pronoun','me');[] gremlin&gt; t.class ==&gt;class org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.DefaultGraphTraversal gremlin&gt; a = t.next() ==&gt;v[0] gremlin&gt; a.class ==&gt;class org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerVertex So, that leads to the next isssue. You are thinking "a" is a Vertex object for which you want to call addE() on, but we've already established that "a" is in fact a Traversal. In the first place, Vertex does not have an addE() method so even if that was a Vertex this approach would not work. Second, because you have a Traversal object which does have an addE() method, you're ending up with this situation demonstrated in Groovy: gremlin&gt; a = g.addV('person').property('name', 'Tushar').property('pronoun', 'me');[] gremlin&gt; b = g.addV('person').property('name', 'Avi').property('pronoun','you');[] gremlin&gt; gremlin&gt; e1 = a.addE('knows').to(b).property('relation','self');[] gremlin&gt; e1.toString() ==&gt;[AddVertexStartStep({pronoun=[me], label=[person], name=[Tushar]}), AddEdgeStep({label=[knows], ~to=[[AddVertexStartStep({pronoun=[you], label=[person], name=[Avi]})]], relation=[self]})] gremlin&gt; gremlin&gt; c = g.addV('subject').property('name','maths');[] gremlin&gt; gremlin&gt; e2 = a.addE('studies').to(c);[] gremlin&gt; e2.toString() ==&gt;[AddVertexStartStep({pronoun=[me], label=[person], name=[Tushar]}), AddEdgeStep({label=[knows], ~to=[[AddVertexStartStep({pronoun=[you], label=[person], name=[Avi]})]], relation=[self]}), AddEdgeStep({label=[studies], ~to=[[AddVertexStartStep({label=[subje…
answers question: http://stackoverflow.com/q/49812448
has comment: http://stackoverflow.com/comment/124126356
upvote count: 18
accepted answer of: http://stackoverflow.com/q/49812448
has comment: http://stackoverflow.com/comment/119991193
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/119999375
downvote count: 0
score: 18
type: Answer
has comment: http://stackoverflow.com/comment/119999386
has comment: http://stackoverflow.com/comment/120010737

http://stackoverflow.com/a/49845317
accepted answer of: http://stackoverflow.com/q/49845245
has body: you are calling methods that are deprecated in latest version of the library and these methods will be removed soon that is why library is suggesting you to use the new methods instead. so just replace wb.get_sheet_by_name("sheet") with wb["sheet"] and wb.remove_sheet(sheet) with with wb.remove(sheet) and your are done from openpyxl import Workbook wb = Workbook() ws = wb.create_sheet(title="resultsheet") for row in range(5,10): ws["A" + str(row)].value = row sheet = wb['Sheet'] wb.remove(sheet) wb.save('newbook.xlsx')
score: 5
upvote count: 5
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49845245
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86670940
type: Comment
type: QuestionComment
has text: @abarnert: If I ditch QueueManager. What data structure can I use to get the next stop?
comment on: http://stackoverflow.com/q/49823312
score: 0

http://stackoverflow.com/comment/86580788
has text: @tgrandje execute: `print(QImageReader.supportedImageFormats())`
comment on: http://stackoverflow.com/a/49781350
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49805557
answers question: http://stackoverflow.com/q/49805395
score: 0
has body: The initial exception says getaddrinfo failed, indicating that a DNS resolution failed. I would run nslookup github.com and see if it resolves.
type: Answer

http://stackoverflow.com/q/49771199
answer count: 2
tagged with: large-files
has comment: http://stackoverflow.com/comment/86557357
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86557412
has body: I have a large log file and I have to extract some useful content from it, this useful content can contain \n in it, the log lines starts with a pattern like Mar12 12:12:12 INFO &lt;content goes here, can have \n in it&gt; so, currently I read the logs like this usefulPattern = re.compile(r'a dict: (.*)') logfile = open('&lt;log file path&gt;','r') logStartPattern = re.compile(r'[A-Z][a-z]{2} \d{2}:\d{2}:\d{2} [A-Z]{4}') lines = logStartPattern.split(logfile.read()) for line in lines: match = usefulPattern.match(line) # line may or may not contain \n depending on what the content is after initial log pattern if match: print match.groups() # do something with useful information with this code I'm getting Memory Error, the problem I see is I'm loading the complete file in memory with .read() I'm looking for a way where I can use the file object like this, so that I don't load all the file content in memory at once. with open('&lt;log file path&gt;', 'r') as logfile: for line in logfile: match = usefulPattern.match(line) # line may or may not contain \n depending on what the content is after initial log pattern if match: print match.groups() # do something with useful information for the above code to work I have to somehow override the reading behavior (probably next method) of file object to read up to the start of the log pattern ([A-Z][a-z]{2} \d{2}:\d{2}:\d{2} [A-Z]{4}) instead of \n
type: Question
score: 0
has comment: http://stackoverflow.com/comment/86557948
has answer: http://stackoverflow.com/a/49771502
has comment: http://stackoverflow.com/comment/86557880
has answer: http://stackoverflow.com/a/49771849
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/86557672
has comment: http://stackoverflow.com/comment/86557446
has title: Can I make a large file object iterate over lines which are split using a regex instead of \n?
linked to: http://stackoverflow.com/q/4634376
tagged with: file-handling

http://stackoverflow.com/comment/86575591
score: 1
type: Comment
type: QuestionComment
has text: Possible duplicate of [ttk.Separator set the length/width](https://stackoverflow.com/questions/37924785/ttk-separator-set-the-length-width)
comment on: http://stackoverflow.com/q/49779701

http://stackoverflow.com/q/49893077
tagged with: python-2.7
has title: How to remove symbols from both sides of a string?
upvote count: 2
has answer: http://stackoverflow.com/a/49893286
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49893142
favorite count: 0
has answer: http://stackoverflow.com/a/49893216
type: Question
has answer: http://stackoverflow.com/a/49893456
answer count: 8
has answer: http://stackoverflow.com/a/52411775
has answer: http://stackoverflow.com/a/49893267
tagged with: python
has answer: http://stackoverflow.com/a/49900556
has answer: http://stackoverflow.com/a/49893109
type: UnansweredQuestion
has body: How would I go about removing characters from the left side of a Python string? Example: string='@!#word ' I know I can use strip('@!# ') to get string='word' but I need a general code to remove all the characters that are not alphabet

http://stackoverflow.com/comment/86617705
type: QuestionComment
comment on: http://stackoverflow.com/q/49786117
score: 0
has text: I install the latest version of vim from the github, but the error is the same. What do i do to change the support for python in build time?
type: Comment

http://stackoverflow.com/q/49878711
tagged with: virtualenv
tagged with: django-rest-framework
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86773571
type: Question
has comment: http://stackoverflow.com/comment/86778557
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86774476
has answer: http://stackoverflow.com/a/52209276
has comment: http://stackoverflow.com/comment/86773008
has body: guys i puled my project from github and i installed all required packages but after makemigrations or runserver commands i get error like below. tying to comment 'social_auth' and social_django ... and command like python3 manage.py migrate --fake myprojectname zero or python3 manage.py migrate --fake social_auth zero or reinstalling packages dont work for me any idea??? error : ..... ...... db.query(q) File "/home/mohammadreza/www/html/academy/uenv/lib/python3.6/site-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1146, "Table 'academy.auth_group' doesn't exist") this is installed app INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework_jwt', 'rest_framework.authtoken', 'social_django', 'rest_social_auth', 'api.v1.blog', 'api.v1.store', 'api.v1.accounts', 'api.v1.manager', ] requirment file: amqp==2.2.2 appdirs==1.4.3 asn1crypto==0.24.0 billiard==3.5.0.3 cached-property==1.3.1 celery==4.1.0 certifi==2018.1.18 cffi==1.11.5 chardet==3.0.4 cryptography==2.1.4 cycler==0.10.0 defusedxml==0.5.0 Django==2.0.4 django-braces==1.12.0 django-cors-headers==2.1.0 django-filter==1.1.0 django-ranged-response==0.2.0 django-redis==4.9.0 djangorestframework==3.7.7 djangorestframework-jwt==1.11.0 gevent==1.2.2 greenlet==0.4.13 gunicorn==19.7.1 idna==2.6 isodate==0.6.0 kiwisolver==1.0.1 kombu==4.1.0 lxml==4.1.1 Markdown==2.6.11 matplotlib==2.2.2 mysqlclient==1.3.12 numpy==1.14.2 oauthlib==2.0.7 olefile==0.45.1 opencv-python==3.4.0.12 Pillow==4.1.1 pycparser==2.18 PyJWT==1.5.3 pyparsing==2.2.0 pytesseract==0.2.0 python-dateutil==2.7.2 python-memcached==1.59 python3-openid==3.1.0 pytz==2017.3 redis==2.10.6 requests==2.18.4 requests-oauthlib==0.8.0 requests-toolbelt==0.8.0 rest-social-auth==1.2.0 six==1.11.0 social-auth-app-django==1.2.0 …
has comment: http://stackoverflow.com/comment/86773115
tagged with: django
has title: django start server error with title auth_group' doesn't exist
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/86778188
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/56474707

http://stackoverflow.com/comment/86719877
has text: You should take a look at http://docs.python-guide.org/en/latest/dev/virtualenvs/
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49852576

http://stackoverflow.com/a/49901176
type: Answer
has body: You extracted it in a wrong way. You have to extract the source archive somewhere else and run pip install . in the extracted directory. After that verify that you have a directory python3.6\Lib\site-packages\rorolite and have a file __init__.py in it. Or download a wheel (*.whl) file and install it using pip install rorolite*.whl.
score: 0
answers question: http://stackoverflow.com/q/49898958

http://stackoverflow.com/a/73266657
score: 5
type: Answer
has body: These solutions are great, but when you have too many columns, you do not want to type all of the column names. So here is what I came up with: column_map = {col: "first" for col in df.columns} column_map["col_name1"] = "sum" column_map["col_name2"] = lambda x: set(x) # it can also be a function or lambda now you can simply do df.groupby(["col_to_group"], as_index=False).aggreagate(column_map)
downvote count: 0
answers question: http://stackoverflow.com/q/49783178
upvote count: 5

http://stackoverflow.com/q/49779647
answer count: 0
tagged with: pylint
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86577296
tagged with: python
has comment: http://stackoverflow.com/comment/86578892
has comment: http://stackoverflow.com/comment/86576948
has comment: http://stackoverflow.com/comment/86577980
has comment: http://stackoverflow.com/comment/86578214
has title: Getting Pylint E1101 - Instance has no such member
score: 0
has body: Pylint doesn't like this code: class sequence(list): def __init__(self, n): list.__init__(self) self += self._generate_collatz_seq(n) self.pivots = self._generate_pivots() self.data = self._make_data() def _collatz_function(self, n): if n % 2 == 0: return(int(n/2)) else: return(3*n + 1) def _generate_collatz_seq(self, x): int(x) sequence_holder = [] while x != 1: sequence_holder.append(x) x = self._collatz_function(x) sequence_holder.append(1) return sequence_holder def _generate_pivots(self): pivots_holder = [] for element in self: if element % 2 != 0: pivots_holder.append(element) return pivots_holder def _make_data(self): data_holder = [] data_holder.append(len(self)) data_holder.append(len(self.pivots)) return data_holder It says E1101: Instance of 'sequence' has no 'pivots' member(56,36) This is before I have made any instances of sequence. I'm sure I haven't gone about my task in the most efficient way, but I can't see that I've done anything wrong.
type: Question
has comment: http://stackoverflow.com/comment/86575519

http://stackoverflow.com/comment/86664615
type: Comment
type: QuestionComment
has text: Why are you allocating a new stack every time you call `push`? (And why are you even defining `stackOfPlates` instead of just using `Stack.Stack`? You seem to be implementing a stack of stacks.
comment on: http://stackoverflow.com/q/49824331
score: 0

http://stackoverflow.com/comment/106152010
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51674554
has text: Good solution. If we used EarlyStopping, we can find the epoch with the best weights by subtracting the 'patience' value from your `number_of_epochs_it_ran`, unless `number_of_epochs_it_ran` equals the number of epochs specified in the `fit` method, in which case the EarlyStopping never kicked in.

http://stackoverflow.com/q/49861106
upvote count: 1
tagged with: keras
downvote count: 1
favorite count: 0
type: Question
has title: How to apply a previously unseen image to a previously saved model?
tagged with: python
tagged with: computer-vision
score: 0
has answer: http://stackoverflow.com/a/49866075
has body: I wanted to know how to apply a previously unseen image to a previously saved CNN model and see how it classifies it ? Code (My attempt) from keras.models import load_model from keras.preprocessing import image import numpy as np img_path = '/Users/eoind/code/1.jpg' model = load_model('food.h5') model.summary() img = image.load_img(img_path, target_size=(100,100)) image = image.img_to_array(img) image = np.expand_dims(image, axis=0) print(image.shape) images = np.vstack([image]) print("classifying images..") image_class = model.predict_classes(images) print(image_class) iPython Console Error ValueError: Error when checking : expected dense_1_input to have 2 dimensions, but got array with shape (1, 100, 100, 3)
tagged with: conv-neural-network
tagged with: deep-learning
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/86787133
score: 0
type: Comment
type: QuestionComment
has text: My `pandas.read_sql` does not parse JSON. Regarding `Series.to_json` how is it not native enough?
comment on: http://stackoverflow.com/q/49884725

http://stackoverflow.com/a/49784875
type: Answer
answers question: http://stackoverflow.com/q/49784784
downvote count: 0
upvote count: 1
has body: indexing only affects the order of the first two axes. swapaxes(0, 1) can be used to reverse the order: In [106]: I,J,K,L = np.meshgrid([1,2,3],['A','B'],[10,20,30,40],['X','Y','Z'], indexing='ij') In [107]: X,Y,Z,W = np.meshgrid([1,2,3],['A','B'],[10,20,30,40],['X','Y','Z'], indexing='xy') In [108]: (I.swapaxes(0,1) == X).all() Out[108]: True In [109]: (J.swapaxes(0,1) == Y).all() Out[109]: True In [110]: (K.swapaxes(0,1) == Z).all() Out[110]: True In [111]: (L.swapaxes(0,1) == W).all() Out[111]: True swapaxes(0, 1) converts xy to ij indexing too (of course): In [112]: (X.swapaxes(0,1) == I).all() Out[112]: True
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49784784
score: 1

pendulum
tag name: pendulum
type: Tag
tags question: http://stackoverflow.com/q/49823699

google-cloud-dataproc
tags question: http://stackoverflow.com/q/49809084
tag name: google-cloud-dataproc
type: Tag

http://stackoverflow.com/q/49861944
type: AnsweredQuestion
tagged with: python-2.7
linked to: http://stackoverflow.com/q/49860980
score: 0
accepted answer: http://stackoverflow.com/a/49862065
has answer: http://stackoverflow.com/a/49862065
duplicate of: http://stackoverflow.com/q/49860980
type: Question
has title: Upgrading PIP (python 2) error
has body: I am using Linux Mint 18 and Python 2.7.12. I have done this before without problems, but doesn't work now. When I do: sudo pip install --upgrade pip it returns Exception: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 324, in run requirement_set.prepare_files(finder) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 821, in unpack_url hashes=hashes File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 659, in unpack_http_url hashes) File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 853, in _download_http_url stream=True, File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/sessions.py", line 521, in get return self.request('GET', url, **kwargs) File "/usr/local/lib/python2.7/dist-packages/pip/download.py", line 386, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/cachecontrol/adapter.py", line 47, in send resp = super(CacheControlAdapter, self).send(request, **kw) File "/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/adapters.py", line 499, in send raise RetryError(e, request=request) RetryError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packa…
answer count: 1
tagged with: pip
tagged with: python

http://stackoverflow.com/q/49767264
tagged with: ubuntu
has answer: http://stackoverflow.com/a/52043953
has title: Why does installing boto3 break my installation of awscli?
has body: I am trying to install boto3 so I can use it in my python script that I want to run on an EC2 instance running Ubuntu 14.04. Anyway I install boto3 it breaks my installation of awscli on the non root user. I install awscli using apt get with sudo apt-get install awscli. After I install it, it works on both the root user and the ubuntu user. ubuntu@ip-10-12-10-8:~$ aws --version aws-cli/1.14.65 Python/2.7.6 Linux/3.13.0-143-generic botocore/1.9.18 ubuntu@ip-10-12-10-8:~$ sudo aws --version aws-cli/1.14.65 Python/2.7.6 Linux/3.13.0-143-generic botocore/1.9.18 I have also tried installing awscli like AWS suggests with sudo pip install awscli --upgrade --user. Also if it means anything pip only runs as the root user maybe thats installed wrong. Here is the output when I install boto3 with pip. But anytime I install boto3 with pip it breaks it for the ubuntu user. I have tried to install boto3 and then install awscli in many different ways and nothing works. Here are the ways I have tried. ubuntu@ip-10-12-10-8:~$ sudo pip install boto3 The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting boto3 /usr/local/lib/python2.7/dist-packages/pip/_vendor/urllib3/util/ssl_.py:339: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/l…
has comment: http://stackoverflow.com/comment/86558918
favorite count: 0
has comment: http://stackoverflow.com/comment/86553391
has comment: http://stackoverflow.com/comment/86549856
has answer: http://stackoverflow.com/a/49772701
type: Question
has answer: http://stackoverflow.com/a/49779394
has comment: http://stackoverflow.com/comment/86555464
upvote count: 5
answer count: 3
score: 5
downvote count: 0
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/86557744
type: UnansweredQuestion
tagged with: boto3

http://stackoverflow.com/comment/86842211
score: 0
type: Comment
type: QuestionComment
has text: Thankyou so much vivek kumar, my problem is solved. All that I was doing wrong by not running this instruction while opening new terminal: [# From tensorflow/models/research/ export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
comment on: http://stackoverflow.com/q/49901479

http://stackoverflow.com/q/49865981
has comment: http://stackoverflow.com/comment/86747528
has title: simple method inheritance in python 3
answer count: 1
has body: Newbie python inheritance question.. when you write the following: class A: def foo(self): print("a") class B(A): pass b = B() getattr(b, "foo") produces &lt;bound method A.foo of &lt;__main__.B object at 0x000000000604CC88&gt;&gt; It looks as if Python creates an attribute foo which is bound to A.foo and it knows that foo is an A method. Should I think of inheritance as simply creating pointers to the base class objects (and the interpreter knows it's a base class object) as opposed to creating a copy of the attribute in the deriving class? Seems like this is an important point but somehow wasn't clear to me initially - came to this question while playing around with super().
has comment: http://stackoverflow.com/comment/86748067
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86747697
has comment: http://stackoverflow.com/comment/86747496
has comment: http://stackoverflow.com/comment/86747882
has comment: http://stackoverflow.com/comment/86747652
tagged with: python
tagged with: inheritance
upvote count: 2
has comment: http://stackoverflow.com/comment/86747422
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49870219
downvote count: 0
accepted answer: http://stackoverflow.com/a/49870219

http://stackoverflow.com/q/49869644
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49869685
type: Question
tagged with: numpy
tagged with: combinations
has comment: http://stackoverflow.com/comment/86754522
has comment: http://stackoverflow.com/comment/86754593
has comment: http://stackoverflow.com/comment/86754758
tagged with: python
has answer: http://stackoverflow.com/a/49869685
has title: Generating all possible combinations in a range using numpy in python
type: AnsweredQuestion
score: 0
has body: I am looking for an efficient way to generate all possible combinations within a certain big range using numpy or any faster method. I tried: from numpy import * from itertools import * dt=dtype('i,i,i,i,i,i') fromiter(combinations(range(10000000),6), dtype=dt, count=-1) but I get a memory error, and even if it worked it will likely take forever to complete. I am looking for combinations that dont repeat. For example, if I needed all 3 number combinations in range(1,5) I will get (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4).

http://stackoverflow.com/q/49890135
has body: I'm training an autoencoder in Keras right now, below is the network structure. input_img = Input(shape=(target_size[0], target_size[1], 3)) x = Conv2D(8, (3, 3), activation = 'relu', padding = 'same')(input_img) x = MaxPooling2D((2, 2), padding = 'same')(x) x = Conv2D(16, (3, 3), activation = 'relu', padding = 'same')(x) x = MaxPooling2D((2, 2), padding = 'same')(x) x = Conv2D(32, (3, 3), activation = 'relu', padding = 'same')(x) encoded = MaxPooling2D((2, 2), padding = 'same')(x) x = Conv2D(32, (3, 3), padding = 'same')(encoded) x = UpSampling2D((2, 2))(x) x = Conv2D(16, (3, 3), activation = 'relu', padding = 'same')(x) x = UpSampling2D((2, 2))(x) x = Conv2D(8, (3, 3), activation = 'relu', padding = 'same')(x) x = UpSampling2D((2, 2))(x) decoded = Conv2D(3, (3, 3), activation = 'sigmoid', padding = 'same')(x) I'm having trouble thinking of a way to: Insert an input layer between where "encoded" is defined and the Conv2D layer after it - the intention is to get the encoding of two different images, create a bunch of iterative "steps" between their encoding, then input these encodings into the "decoder" half of this network to generate an image for every step. I want to make a gif of the output "morphing" from one image to the other. I wanted to try inserting another Conv2D(...) and MaxPooling2D(...) pair right after the input layer, and a corresponding UpSampling2D(...) and Conv2D(...) at the end. I had this idea from NVidia's "Progressive Growing of GANs for Improved Quality, Stability, and Variation" paper, where they trained their GAN to generate really good images at low resolutions, then progressively added more layers at the beginning and end of their network and trained the whole network with the new layers. Does this make sense? Please let me know if I can clarify anything, I feel like this is very specific problem that's hard to explain over text all at once. Thanks!
has comment: http://stackoverflow.com/comment/86884693
has comment: http://stackoverflow.com/comment/86884649
tagged with: deep-learning
score: 1
has comment: http://stackoverflow.com/comment/86808621
has title: How do I insert a Keras layer before previously defined layers?
has comment: http://stackoverflow.com/comment/86884556
type: Question
has comment: http://stackoverflow.com/comment/86881716
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
tagged with: keras
favorite count: 0

http://stackoverflow.com/a/49779467
downvote count: 0
has comment: http://stackoverflow.com/comment/86577260
has comment: http://stackoverflow.com/comment/86577198
upvote count: 1
has comment: http://stackoverflow.com/comment/86582571
has comment: http://stackoverflow.com/comment/86577511
has body: Structure your Code Here are a couple guidelines to help you on your adventure. When developing a programming, you usually want to design it like you are making a factory, elegant individual modules inside a chain of command. Instead of rigid/absolute code with no maintainability, scalability or abstraction of it's concepts Think like legos, components and little bricks, to each their type and task. Data-Structure Start with your data-structures, they are the foundation of what you are working on, simple to make, you only need to know what you are working on to make them. class Station: def __init__(self, _id, _lat, _long): self.id = _id self.lat = _lat self.long = _long Here we have created a class which can be the home of the information from stations.csv this will let us manipulate PythonObjects instead of only iterating through lists (even if we ultimately will, we don't have to deal directly with it when we need it), this will also make your code a lot clearer and a lot easier to read, especially for people other than you. Factories Progress on to adding functionalities to your Classes through methods. We'll start off by creating a factory class, which we could call Utility which would be responsible for importing and populating your classes for exemple, by doing this, we abstract our information layer from our logic layer, so you will never have to manipulate the parsing inside your main programs loop (I am not literally talking about __main__). Let's start with parsing our Station information from our CSV: import csv stations = [] with open('stations.csv', 'r') as f: reader = csv.reader(f) for row in reader: clean_row = row.split(“,”) stations.append(Station(clean_row[0], clean_row[1], clean_row[2]) (This does not take into account the possibility that you have your column names on your first row and assumes they are not.) Now we have populated our list of stations with Station python objects, which we can use to access the data directly as such: print(statio…
has comment: http://stackoverflow.com/comment/86575445
has comment: http://stackoverflow.com/comment/86577916
score: 1
has comment: http://stackoverflow.com/comment/86578505
type: Answer
answers question: http://stackoverflow.com/q/49778369
has comment: http://stackoverflow.com/comment/86575219

http://stackoverflow.com/comment/86652817
has text: Oh i think i can think of a possible reason, it's reading every line as a string {} included, it should read them as a dict.
comment on: http://stackoverflow.com/a/49817843
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/49864367
has body: I have a small code in jupyter notebook: for col in df: # fill NaN using most frequent values df[col].fillna(df[col].value_counts().index[0], inplace=True) print(df[col].isnull().sum()) print(df.isnull().sum()) And here is a problem, my results looks that: 0 0 0 MSSubClass 0 MSZoning 0 LotFrontage 227 In a for loop DataFrame filling all null values, but after for loop my dataFrame has null values again. I checked this in PyCharm and works fine (after loop I haven't any null values). Question: Why does jupyter notebook work in this way? How can I fix it?
score: 0
has comment: http://stackoverflow.com/comment/86745009
answer count: 0
tagged with: pandas
tagged with: jupyter-notebook
type: Question
has title: jupyter, scope of variable only in loop
has comment: http://stackoverflow.com/comment/86744337
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86744245

http://stackoverflow.com/comment/86655991
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49806787
score: 0
has text: no. I think that you are looking at the wrong answer. The code produces three lists.

http://stackoverflow.com/a/49762515
has comment: http://stackoverflow.com/comment/86540809
has comment: http://stackoverflow.com/comment/86540830
score: 2
upvote count: 2
downvote count: 0
has body: I guess that matplotlib.colors.ListedColormap is what you need here: import matplotlib import matplotlib.pyplot as plt colors = 'lime red blue magenta yellow'.split() cmap = matplotlib.colors.ListedColormap(colors, name='colors', N=None) m = [ [1, 0, 2, 0, 0], [1, 1, 1, 2, 0], [0, 4, 1, 0, 0], [0, 4, 4, 1, 2], [1, 3, 0, 0, 1], ] plt.imshow(m, cmap=cmap) plt.show() You may also use (R,G,B) tuples (instead of predefined color strings) in your list if you need more control
has comment: http://stackoverflow.com/comment/86540577
has comment: http://stackoverflow.com/comment/86540922
answers question: http://stackoverflow.com/q/49761923
type: Answer

http://stackoverflow.com/a/77657872
answers question: http://stackoverflow.com/q/49772151
type: Answer
has body: I hope, it will give you a better understanding of uploading, downloading and getting an s3 object # libraries import import boto3 import pandas as pd # configure aws on command line # aws configure # enter your access key, access secret and region in which you create your bucket # You get your access key and access password from security credentials under the iam # if its disabled delete the previous one and then create the new one s3_obj = boto3.client("s3") # object for accessing s3 # Downloading file code s3_obj.download_file( Filename="./local_file_name_which_you_download_from_s3.csv", Bucket="your_bucket_name", Key="file_in_s3_bucket.csv" # ) df = pd.read_csv('./local_file_name_which_you_download_from_s3.csv') df.head() # Uploading file code s3_obj.upload_file( Filename="./local_file_name_which_you_download_from_s3.csv", Bucket="your_bucket_name", Key="file_in_s3_bucket.csv" ) s3_obj_file = s3_obj.get_object(Bucket='bucket_name', Key='file_in_s3_bucket')['Body'].read() df_upload = pd.read_excel(s3_obj_file) df_upload.head()
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/109905422
type: Comment
has text: For such reason, one could feel tortured for no reaching the same results of Central Limit Theorem from this example, since the samples generated for a population, are different, from one machine to another: https://towardsdatascience.com/visualizing-the-central-limit-theorem-with-python-e89d2ce41788
type: AnswerComment
comment on: http://stackoverflow.com/a/49812581
score: 0

http://stackoverflow.com/q/49868823
score: 1
tagged with: utf-8
favorite count: 0
has comment: http://stackoverflow.com/comment/86838037
type: Question
has comment: http://stackoverflow.com/comment/86845639
type: UnansweredQuestion
tagged with: sockets
downvote count: 0
has title: utf-8 issue when using socket in server PC
has comment: http://stackoverflow.com/comment/86759586
upvote count: 1
has comment: http://stackoverflow.com/comment/86759207
tagged with: python
has comment: http://stackoverflow.com/comment/86838002
has comment: http://stackoverflow.com/comment/86845509
has body: I want to send some file from a client PC to a server PC using Python. But when I run the client code, there is a problem. Here is the client code: with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as sock: sock.connect((HOST,PORT)) sock.sendall(filename.encode('utf-8')) print(filename.encode('utf-8')) and this is the server code: filename = self.request.recv(1024) print(filename) filename = filename.decode('utf-8') When I run it within my PC (for example, server=client localhost), it runs perfectly. But in my server PC, print result has some added text like: b'filename\~~~~~~~~~~' filename result error message So I think if the added text is gone when I use my server PC, the problem will be solved. But I dont know how to get there. Please let me know...
answer count: 0

http://stackoverflow.com/a/50128619
has body: I am using a service called pigpiod and rinnung this service on my raspberry pi. I have python library installed for pigpiod service (daemon). and my code to detect the button state is something like !/usr/bin/env python import pigpio import time import datetime if __name__ == "__main__": def cbf(gpio, level): if(pi.read(gpio)!=0): i = datetime.datetime.now() date = i.strftime("%Y-%m-%d %H:%M:%S") print "gpio "+str(gpio)+"button gpio gave 1" print date if(pi.read(gpio)==0): i = datetime.datetime.now() date = i.strftime("%Y-%m-%d %H:%M:%S") print "gpio "+str(gpio)+"button gpio gave 0" print date pi = pigpio.pi() pi.set_mode(23, pigpio.INPUT) while True: cbf(23, pigpio.EITHER_EDGE) Run the python script and press the button. You will get different value as 0 and 1. So basically I am using PIGPIO and Python to detect button press as well as circuit close or open on a specific GPIO of the raspberry PI. To start the pigpio daemon sudo pigpiod To stop the pigpio daemon sudo killall pigpiod github git clone https://github.com/joan2937/pigpio Python Library sudo apt-get update sudo apt-get install pigpio python-pigpio python3-pigpio Link for PIGPIO Download &amp; Install PIGPIO and Run the PIGPIOD service NOTE: I am NOT using RPi.GPIO or GPIO service available on Raspberry. All I have used pigpio for my temperature sensor, RFID card readers etc.
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49787761
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49787761

http://stackoverflow.com/a/52053199
type: Answer
has body: Experiencing the same problem, the only thing that worked for me after having tried the various solutions suggested here -- I'm using Jupyter Notebook on Anaconda -- was installing it through the anaconda platform [Environments]; I hope this helps someone.
score: 0
answers question: http://stackoverflow.com/q/49772348

http://stackoverflow.com/q/49783137
accepted answer: http://stackoverflow.com/a/57608365
type: Question
has answer: http://stackoverflow.com/a/57608365
tagged with: summernote
tagged with: twitter-bootstrap
has title: How can I add Bootstrap 4 to the library django-summernote?
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
has body: I need to add Bootstrap 4 to django-summernote. Is this possible?
tagged with: bootstrap-4
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/101312596
has text: Termux never fails to amaze me!
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49837476

http://stackoverflow.com/q/49896783
tagged with: node.js
score: 0
has answer: http://stackoverflow.com/a/49897987
has body: I've got a strange problem with my automated minify tool. I had to replace yuicompressor with csso, since yuicompressor hasn't updated since 2013 and has many bugs with newer css selectors. This has increased the complexity (as in amount of involved "stuff") to the point where I have no idea how to debug an issue with the command executed. (Or even if it got executed). I've basically got my problem narrowed down to the following python code snippet (currently with a lot of added debug statements to help diagnose the problem): print("node " + os.path.join(getScriptPath(), "css", "csso", "bin", "csso") + " -i " + os.path.join(root, name) + " -o " + os.path.join(root, outname) + " --debug") os.remove(os.path.join(root, outname)) try: result = subprocess.check_output(["node", os.path.join(getScriptPath(), "css", "csso", "bin", "csso"), "-i", os.path.join(root, name), "-o", os.path.join(root, outname), "--debug" ], stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as exc: print("ERROR: Failed to execute CSSO with error:", exc.returncode, exc.output) Note here that getScriptPath() is a small helper function that returns the current path the script file is in. csso is installed by copying the files manually under css/csso/bin/csso. name is a string holding the relative path to the original css file (usually something like ../../domains\mydomain.com\templates\css\style.css), while outname is always the same as name, but with the extension changed to .min.css. If I copy &amp; paste the result of the first print() call directly in a cmd terminal, csso will run and minify my file. But, if I call a batch script that runs a python program that eventually runs the code above (as part of the things it does), nothing is done, with no output. The subprocess.run call used to be a simple shell call, which would have no output. Yet, I still get no output. Here's some example output I'm getting by manually running it (in stderr): ## parsing done in 16 ms Compres…
tagged with: windows
answer count: 1
tagged with: cmd
type: Question
tagged with: csso
type: UnansweredQuestion
has title: Subprocess.check_output does nothing for node.js on windows?
tagged with: python

http://stackoverflow.com/comment/86560027
type: Comment
type: QuestionComment
has text: How is this a python question exactly ? Your problem is not with Python itself but with your system not being able to find the Python interpreter, so you could have the very same problem with just any executable.
comment on: http://stackoverflow.com/q/49769623
score: 0

http://stackoverflow.com/q/49773008
duplicate of: http://stackoverflow.com/q/2158395
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86560836
favorite count: 0
linked to: http://stackoverflow.com/q/2158395
type: Question
linked to: http://stackoverflow.com/q/952914
has body: Is there any quick ways to untangle elements in a list? For example: Given list = [[1,2,3],[4,2],2,1,3] We'll have: list = [1,2,3,4,2,2,1,3]
has title: Python - "Unlist" a nested element in a list
tagged with: python
has answer: http://stackoverflow.com/a/49773050
has answer: http://stackoverflow.com/a/49773159
upvote count: 2
score: 2
tagged with: list
answer count: 2
downvote count: 0

http://stackoverflow.com/a/72322915
type: Answer
score: 1
downvote count: 0
upvote count: 1
has body: For this stack: CentOS: 7 Python: 3.8 GCC: 4.8.5 PyStan: 2.19.1.1 FbProphet: 0.7.1 You need these packages: centos-release-scl devtoolset-8 Enable SCL devtoolset-8 source /opt/rh/devtoolset-8/enable rh-python38-python rh-python38-python-devel pip install pystan==2.19.1.1 Docker image with HTTPD MOD_WSGI and FBPROPHET... FROM centos:7 EXPOSE 80 # Install Apache RUN yum -y update RUN yum -y install centos-release-scl RUN yum -y install httpd httpd-tools rh-python38-python-mod_wsgi.x86_64 devtoolset-8-gcc devtoolset-8-gcc-c++ rh-python38-python rh-python38-python-devel # Copy the wsgi module to Apache HTTP Server modules folder RUN cp /opt/rh/httpd24/root/usr/lib64/httpd/modules/mod_rh-python38-wsgi.so /lib64/httpd/modules/mod_wsgi.so ENV PATH="/opt/rh/rh-python38/root/usr/bin:/opt/rh/rh-python38/root/usr/local/bin:${PATH}" WORKDIR / COPY ROOT . WORKDIR /opt/rh/rh-python38/root RUN ./usr/bin/python3 /etc/get-pip.py RUN chmod +x /usr/local/bin/install-fb.sh && /usr/local/bin/install-fb.sh RUN pip install -r /etc/requirements.txt # Start Apache CMD ["/usr/sbin/httpd","-D","FOREGROUND"] The script install-fb.sh contains this code: $ cat ROOT/usr/local/bin/install-fb.sh #!/bin/bash source /opt/rh/devtoolset-8/enable pip install pystan==2.19.1.1 fbprophet==0.7.1 The reason to put it in its own script is the SCL enable line, to avoid the gcc not found error. I hope this helps, getting all these software packages running together is not a piece of cake :)
answers question: http://stackoverflow.com/q/49889404

http://stackoverflow.com/q/49806184
has answer: http://stackoverflow.com/a/76578711
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/49808806
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/76578711
tagged with: python-2.7
has body: I am trying to use Mateplotlib cartopy to make the plots below. Here is the code that I am using. import cartopy.crs as ccrs fig=plt.figure(figsize=(15,11)) ax = plt.subplot(111, projection=ccrs.PlateCarree(central_longitude=0)) mm = ax.contourf(new_lon[:],lat_post,new_aa[0,:,:],transform=ccrs.PlateCarree(central_longitude=0)) ax.coastlines(resolution='10m'); ax.stock_img(); # the following two lines increaes the vertical distance between the title and the upper tick. from matplotlib import rcParams rcParams['axes.titlepad']=20 # drawing the longitude and latitude ticks. gl = ax.gridlines(crs=ccrs.PlateCarree(central_longitude=0), draw_labels=True,linewidth=2, color='gray', alpha=0.5, linestyle='--') Yet, once I add the following code set_extent ax.set_extent([np.min(new_lon),np.max(new_lon),np.min(lat_post) ,np.max(lat_post)]) The figures becomes like that
answer count: 2
has answer: http://stackoverflow.com/a/49808806
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
type: Question
has title: Cartopy set_extent is not working
tagged with: cartopy

http://stackoverflow.com/q/49902212
upvote count: 3
downvote count: 0
has body: I have a 2D array of arrays defined as follows: traces = [['x1',11026,0,0,0,0], ['x0',11087,0,0,0,1], ['x0',11088,0,0,1,3], ['x0',11088,0,0,0,3], ['x0',11088,0,1,0,1]] I want to find the index of the row which matches multiple conditions of selected columns. For example I want to find the row in this array where row[0]=='x0' &amp; row[1]==11088 &amp; row[3]==1 &amp; row[5]=1 Searching on this criteria should return 4. I attempted to use numpy.where but can't seem to make it work with multiple conditions print np.where((traces[:,0] == 'x0') &amp; (traces[:,1] == 11088) &amp; (traces[:,3] == 1) &amp; (traces[:,5] == 1)) The above creates the warning FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison print np.where((traces[:,0] == 'x0') &amp; (traces[:,1] == 11088) &amp; (traces[:,3] == 1) &amp; (traces[:,5] == 1)) (array([], dtype=int32),) I've attempted to use numpy.logical_and as well and that doesn't seem to work either, creating similar warnings. Any way I can do this using numpy.where without iterating over the whole 2D array? Thanks
has answer: http://stackoverflow.com/a/49902594
favorite count: 0
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/49902594
tagged with: python
has title: Searching 2D array with numpy.where with multiple conditions
type: Question
accepted answer: http://stackoverflow.com/a/49902651
tagged with: numpy
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/49902651

http://stackoverflow.com/q/49801024
has body: I have this code: import pandas as pd import numpy as np import matplotlib.pyplot as plt import sklearn.neighbors as ng def mydist(x, y): return np.sum((x-y)**2) if __name__ == '__main__': nn = ng.KNeighborsClassifier(n_neighbors=3, algorithm='ball_tree',metric='mydist') I am using sci-kit learn 0.18.1 and I get this error ValueError: Metric 'mydist' not valid for algorithm 'ball_tree' I also tried using algorithm = 'brute' but the error persists. What is causing this? How do I use an user defined distance metric correctly?
favorite count: 0
score: 2
type: AnsweredQuestion
has title: Using a user-defined distance metric for k-nn in scikit-learn
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49801253
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49801253
downvote count: 0
tagged with: scikit-learn

http://stackoverflow.com/q/49772293
has answer: http://stackoverflow.com/a/51605061
type: UnansweredQuestion
tagged with: .net
has title: Import issue with IronPython and Visual Studio 2015
tagged with: python
score: 3
has body: I want to integrate IronPython in my .NET C# Library but I have always the following exception Additional information: No module named 'modulename' In my C# library project, I've installed the following IronPython NuGet Install-Package IronPython Install-Package IronPython.StdLib Python simple code (getLogScaledPNG.py): import numpy as np import matplotlib.pyplot as plt def getLogScaledPNG(filename): data = plt.imread(filename); data[data == 0.] = np.nan; logdata = np.log(data); plt.imsave("logimage.png", logdata, cmap="gray"); print 'Scaled Image Saved' C# code: using IronPython.Hosting; var ipy = Python.CreateRuntime(); dynamic getLogScaledPNG = ipy.UseFile(@".\PythonScripts\getLogScaledPNG.py"); getLogScaledPNG.getLogScaledPNG("toto.png"); When I execute this C# code, I've got the following Exception: Additional information: No module named numpy I don't understand where and how can I add this module ? I just have the reference to the IronPython DLLs in my .NET project and I haven't got any folders where I can add this module
upvote count: 3
answer count: 1
downvote count: 0
tagged with: ironpython
favorite count: 0
type: Question
tagged with: c#

http://stackoverflow.com/q/49908444
favorite count: 0
has comment: http://stackoverflow.com/comment/86833129
upvote count: 4
has comment: http://stackoverflow.com/comment/86833070
has comment: http://stackoverflow.com/comment/86833295
has comment: http://stackoverflow.com/comment/86833421
has comment: http://stackoverflow.com/comment/86833042
has comment: http://stackoverflow.com/comment/86833366
type: Question
has comment: http://stackoverflow.com/comment/86832859
has comment: http://stackoverflow.com/comment/86833009
has comment: http://stackoverflow.com/comment/86833385
has body: I have a 100GB text file. The data in that file is in this format: email||username||password_hash I am testing on a 6GB file which I made separately by splitting the bigger file. I am running grep to match the lines and output them. I used grep. It is taking around 1 minute 22 seconds I used other options with grep, like, LC_ALL=C and -F, but the time is reduced to 1 minute 15 seconds, which is still not good for a 6GB file. Then I used ripgrep, it is taking 27 seconds on my machine, still not good. Then I used ripgrep with -F option, it is taking 14 seconds, still not good. I tried ag also (the silver searcher), but I found that it won't work for files bigger than 2 GB. I need your help which command line tool (or language) to achieve better results, or some way I can take advantage of the format of data to search by column. Like if I am searching by username, then instead of matching the whole line, I search only on the second column. I tried that using awk, but it is still slower.
has comment: http://stackoverflow.com/comment/86839793
tagged with: perl
has comment: http://stackoverflow.com/comment/86838639
has comment: http://stackoverflow.com/comment/86852401
tagged with: awk
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86832912
has comment: http://stackoverflow.com/comment/86833967
answer count: 1
has comment: http://stackoverflow.com/comment/86833331
downvote count: 1
has comment: http://stackoverflow.com/comment/86846420
has comment: http://stackoverflow.com/comment/86832888
has answer: http://stackoverflow.com/a/49915445
tagged with: linux
has comment: http://stackoverflow.com/comment/86854588
tagged with: bash
score: 3
has title: Search for a string in a 100 GB file
has comment: http://stackoverflow.com/comment/86832934
has comment: http://stackoverflow.com/comment/86832832
linked to: http://stackoverflow.com/q/6219141
linked to: http://stackoverflow.com/q/13913014

http://stackoverflow.com/a/49897410
score: 4
has body: Do you want to apply a transformation function to any of the nested keys matching a pattern in a dictionary? d = {"color": 1, 'child': {"color": 2}} def transform(d, p, t): for each in d: if isinstance(d[each], dict): transform(d[each], p, t) if each == p: d[each] = t(d[each]) transform(d, "color", lambda x: x+1) If you want to generalize "how do you determine if the pattern is matching", then you can pass the logic as a function like this: d = {"color": 1, 'child': {"background-color": 2}} def transform(d, p, t): for each in d: if type(d[each]) == dict: transform(d[each], p, t) if p(each): d[each] = t(d[each]) transform(d, lambda x: 'color' in x, lambda x: x+1) The argument p is called as a predicate function. You can call it with 'color' in x to handle partial strings for example.
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49897107
answers question: http://stackoverflow.com/q/49897107
type: Answer

http://stackoverflow.com/q/49876442
answer count: 1
accepted answer: http://stackoverflow.com/a/49876640
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/86768636
has comment: http://stackoverflow.com/comment/86769350
has answer: http://stackoverflow.com/a/49876640
has comment: http://stackoverflow.com/comment/86769256
has title: Removing ^M from JSON output
tagged with: python
has comment: http://stackoverflow.com/comment/86769181
has comment: http://stackoverflow.com/comment/86768498
type: AnsweredQuestion
score: 0
has body: I'm using requests to get output of REST API call, save output to 1.json, then from that json file extract description and JIRA key import csv import urllib2 import argparse import json from bson import json_util #password = str(sys.argv[1]) headers = { 'Content-Type': 'application/json', } params = ( ('jql', 'project="Technology" AND summary~"workspace creation*" AND issuetype="Task" AND status!="DONE"'), ) response = requests.get('https://jira.company.com/rest/api/2/search', headers=headers, params=params, auth=('user', 'Pass')) with open('1.json', 'w') as outfile: outfile.write(response.content) if sys.version[0] == '2': reload(sys) sys.setdefaultencoding("utf-8") sys.stdout = open('output.txt','wt') datapath = '1.json' data = json.load(open(datapath)) for issue in data['issues']: if len(issue['fields']['subtasks']) == 0 and 'description' in issue['fields']: custom_field = issue['fields']['description'] print custom_field print issue['key'] Output.txt: User:someuser^M ^M First Name:some^M ^M Last Name:user TECH-1427 I need to get csv file from this output.txt in following format: someuser,some,user,TECH-1427 I'm using this code re.findall(r'\bUser:(\S+)\s+First Name:(\S+)\s+Last Name:(\S+)\s+(TECH-\d+)', data) data is content of output.txt file Now, this only works if i manually remove ^M from output.txt, so how to get rid of ^M during parsing 1.JSON file so it's removed from output.txt ? Tried replacing but same results sys.stdout = open('out.txt','wt') with open ("output.txt", "r") as myfile: data=myfile.read() print data.replace('^M','')
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/49876618
has comment: http://stackoverflow.com/comment/86768816
tagged with: ternary-operator
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86768760
upvote count: 4
has title: Python :: Ternary Operator :: Not able to use multiple statements
has answer: http://stackoverflow.com/a/68336253
score: 2
downvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/86768713
favorite count: 0
has body: I have the scenario something like this. a = 3 b = 5 c = 7 # using ternary operator now, print a; c = 1 if a &lt; b else print b ; c = 2 Which raises this error when I use assignment operator on both the sides SyntaxError: can't assign to conditional expression If I use it on one side like this, it works fine. a = 1 ; c = 1 if a &lt; b else b So question is How to use multiple statements in Python Ternary Operator?
tagged with: conditional-statements
type: Question
tagged with: if-statement
has comment: http://stackoverflow.com/comment/86772539
has answer: http://stackoverflow.com/a/49880229

http://stackoverflow.com/a/49888913
score: 0
has comment: http://stackoverflow.com/comment/86836884
has body: Wrap your input statements in one of the built in conversion functions. ie. M=str(input("What is your first element/symbol")) Z=int(input("What is the subscript of that element?")) This will convert the input from the user to the format you want it. (converting to string isn't actually necessary as that is the default) Another thing, unrelated to your question, is you are going to want to change the way you are using that dictionary. Perhaps define it as M_dict and then reference it using the M entered by the user like this M_dict[M] That will give you the number corresponding to the element entered by the user which you can then multiply by the subscript.
has comment: http://stackoverflow.com/comment/86794690
type: Answer
answers question: http://stackoverflow.com/q/49888634
has comment: http://stackoverflow.com/comment/86836952

http://stackoverflow.com/q/49797475
favorite count: 0
type: Question
score: 3
tagged with: python
has body: I have a external service (ExternalDummyService) in which I register a callback. I want to create an observable from that callback and subscribe multiple asynchronous processes. Full code in pyfiddle: https://pyfiddle.io/fiddle/da1e1d53-2e34-4742-a0b9-07838f2c13df * Note that in the pyfiddle version, the "sleeps" are replaced with "for i in range(10000): foo += i" because sleep does not work properly. The main code is this: thread = ExternalDummyService() external_obs = thread.subject.publish() external_obs.subscribe(slow_process) external_obs.subscribe(fast_process) external_obs.connect() thread.start() class ExternalDummyService(Thread): def __init__(self): self.subject = Subject() def run(self): for i in range(5): dummy_msg = { ... } self.subject.on_next(dummy_msg) def fast_process(msg): print("FAST {0} {1}".format(msg["counter"], 1000*(time() - msg["timestamp"]))) sleep(0.1) def slow_process(msg): print("SLOW {0} {1}".format(msg["counter"], 1000*(time() - msg["timestamp"]))) sleep(1) The output I'm getting is this one, with both processes running synchronously and the ExternalDummyService not emitting new values until both processes has finished each execution: emitting 0 STARTED SLOW 0 1.0008811950683594 FAST 0 2.0122528076171875 emitting 1 SLOW 1 1.5070438385009766 FAST 1 1.5070438385009766 emitting 2 SLOW 2 0.5052089691162109 FAST 2 0.9891986846923828 emitting 3 SLOW 3 1.0006427764892578 FAST 3 1.0006427764892578 emitting 4 SLOW 4 1.0013580322265625 FAST 4 1.0013580322265625 FINISHED I would like to get something like this, with the service emitting messages without waiting for the processes to run and the processes running asynchronously: STARTED emitting 0 emitting 1 emitting 2 FAST 0 2.0122528076171875 FAST 1 1.5070438385009766 emitting 3 SLOW 0 1.0008811950683594 FAST 2 0.9891986846923828 emitting 4 FAST 3 1.0006427764892578 SLOW 1 1.5070438385009766 FAST 4 1.0013580322265625 SLOW 2 0.5052089691162109 SLOW 3 1.0006427764892578 SLOW 4 1.0013580322265625 FI…
linked to: http://stackoverflow.com/q/40447798
type: AnsweredQuestion
tagged with: rx-py
tagged with: reactivex
upvote count: 3
accepted answer: http://stackoverflow.com/a/49801802
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49801802
has title: RxPy: How to create hot observable from external callback and subscribe multiple asynchronous processes?

http://stackoverflow.com/comment/86661715
type: Comment
has text: You already *are* using another query to loop through the result (at the bottom). Just add the level to the CTE.
type: QuestionComment
comment on: http://stackoverflow.com/q/49821802
score: 0

http://stackoverflow.com/q/49798313
answer count: 3
has answer: http://stackoverflow.com/a/49803554
accepted answer: http://stackoverflow.com/a/49803554
tagged with: arrays
downvote count: 0
has comment: http://stackoverflow.com/comment/86611346
tagged with: word2vec
has answer: http://stackoverflow.com/a/49799146
possible better answer: http://stackoverflow.com/a/49799146
has body: I need to find the closest possible sentence. I have an array of sentences and a user sentence, and I need to find the closest to the user's sentence element of the array. I presented each sentence in the form of a vector using word2vec: def get_avg_vector(word_list, model_w2v, size=500): sum_vec = np.zeros(shape = (1, size)) count = 0 for w in word_list: if w in model_w2v and w != '': sum_vec += model_w2v[w] count +=1 if count == 0: return sum_vec else: return sum_vec / count + 1 As a result, the array element looks like this: array([[ 0.93162371, 0.95618944, 0.98519795, 0.98580566, 0.96563747, 0.97070891, 0.99079191, 1.01572807, 1.00631016, 1.07349398, 1.02079309, 1.0064849 , 0.99179418, 1.02865136, 1.02610303, 1.02909719, 0.99350413, 0.97481178, 0.97980362, 0.98068508, 1.05657591, 0.97224562, 0.99778703, 0.97888296, 1.01650529, 1.0421448 , 0.98731804, 0.98349052, 0.93752996, 0.98205837, 1.05691232, 0.99914532, 1.02040555, 0.99427229, 1.01193818, 0.94922226, 0.9818139 , 1.03955 , 1.01252615, 1.01402485, ... 0.98990598, 0.99576604, 1.0903802 , 1.02493086, 0.97395976, 0.95563786, 1.00538653, 1.0036294 , 0.97220088, 1.04822631, 1.02806122, 0.95402776, 1.0048053 , 0.97677222, 0.97830801]]) I represent the sentence of the user also as a vector, and I compute the closest element to it is like this: %%cython from scipy.spatial.distance import euclidean def compute_dist(v, list_sentences): dist_dict = {} for key, val in list_sentences.items(): dist_dict[key] = euclidean(v, val) return sorted(dist_dict.items(), key=lambda x: x[1])[0][0] list_sentences in the method above is a dictionary in which keys are a text representation of sentences, and values are vector. It takes a very long time, because I have more than 60 million sentences. How can I speed up, optimize this process? I'll be grateful for any advice.
favorite count: 0
has title: Search for the nearest array in a huge array of arrays
type: Question
has answer: http://stackoverflow.com/a/49800899
score: 3
tagged with: performance
tagged with: python
tagged with: numpy
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/q/49782487
type: Question
has comment: http://stackoverflow.com/comment/86580689
score: -2
tagged with: python
has title: python combine by key or value
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/86582836
has body: I have a table like below ID |Identifier1 | Identifier2 --------------------------------- 1 | a | c 2 | b | f 3 | a | g 4 | c | h 5 | b | j 6 | d | f 7 | e | k 8 | i | 9 | l | h The desired output is below Identifier | Gr_ID | Gr.Members --------------------------------------------------- a | 1 | (a,c,g,h,l) b | 2 | (b,d,f,j) c | 1 | (a,c,g,h,l) d | 2 | (b,d,f,j) e | 3 | (e,k) f | 2 | (b,d,f,j) g | 1 | (a,c,g,h,l) h | 1 | (a,c,g,h,l) j | 2 | (b,d,f,j) k | 3 | (e,k) l | 1 | (a,c,g,h,l) i | 4 | (i) How can I get the desired output? Looked at the dictionary methods and not finding any where we can group by key or value.
tagged with: pandas
has comment: http://stackoverflow.com/comment/86580784
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/49783643
accepted answer: http://stackoverflow.com/a/49783643
favorite count: 0

http://stackoverflow.com/comment/87452104
comment on: http://stackoverflow.com/q/49829467
type: Comment
has text: I see. Then I would try using one of [the latest Python Client Libraries versions](https://pypi.org/project/google-cloud-pubsub/#history), calling the callback function in the `subscribe()` method, and adjusting the amount of messages retrieved to a lower value that can be better handled by the VMs without increasing the delay and risking to hit the ack deadline (which may explain the reason for duplicated msgs, given that [messages are resent if not acked within the deadline](https://cloud.google.com/pubsub/docs/subscriber#create)). Let us know if the same behavior happens after the changes.
type: QuestionComment
score: 0

highest
tag name: highest
type: Tag
tags question: http://stackoverflow.com/q/49902603

http://stackoverflow.com/comment/86662488
score: 0
comment on: http://stackoverflow.com/q/49823221
type: QuestionComment
type: Comment
has text: Yes, please share what you have tried in a [minimalistic, complete, verifiable example](https://stackoverflow.com/help/mcve)?

http://stackoverflow.com/comment/98119668
has text: but it is not working for oga(telegram audio) file format.
comment on: http://stackoverflow.com/a/55719890
score: 2
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49837916
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49837159
has body: By specification of division in IEEE-754, if a/b = c/d, then a/b == c/d, provided that the operations in a/b == c/d are evaluated as specified in IEEE-754 using one floating-point format. (Python does not make this guarantee; it inherits the floating-point behavior of whatever platform it is implemented on, and IEEE-754 behavior is not universally guaranteed.) This is because IEEE-754 specifies that the result is the exact mathematical result rounded to the nearest representable value (according to the applicable rounding mode). Since the mathematical results are identical for a/b and c/d, the computed results are identical. However, a/b == c/d does not imply a/b = c/d. A counterexample is that 1 / (0x1p53-1) and 1 / (0x1p53-2) both produce 1.11022302462515678694266454965700950366517665087069677287701097156968899071216583251953125 • 10−16 (in hexadecimal floating-point, 0x1.0000000000001p-53).
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/86849297
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49916547
has text: I did this, but Python is just thinking and does not print anything
type: Comment

http://stackoverflow.com/comment/86614547
type: Comment
comment on: http://stackoverflow.com/q/49799906
score: 1
has text: Change the x axis labels or multiply the data by 1000?
type: QuestionComment

http://stackoverflow.com/q/49862521
has title: Python: Read in Multiple Excel Workbooks into one DataFrame
score: 2
type: AnsweredQuestion
tagged with: pandas
upvote count: 2
downvote count: 0
answer count: 1
has body: I have approximately 150 different workbooks (xlsx) in a folder that I would like to read into a python dataframe for analysis. Each workbook is set up identically with the same sheet names and column names. I would need to upload the first sheet of each workbook ("Keywords Rankings") to each DataFrame. For the first worksheet read in, I would want to start on row 11 to maintain the column headers; every worksheet after that I would want to append to my DataFrame starting on row 12. I am new to Python and have been reading some instructions online but am stuck. From my understanding, I could use the xlrd library to facilitate this. I've been playing around with the below code but haven't gotten far. 'Keywords Rankings' is the sheet name I want to append. import pandas as pd import numpy as np import glob as glob all_data = pd.DataFrame() all_data = pd.ExcelFile("C:\\Users\\John Smith\\Documents\\Analysis\\FPR Nov - Mar 2018\\Dec_1_General.xlsx") print(all_data.sheet_names) all_d = all_data.parse('Keywords Rankings') for f in glob.glob("Users\\John Smith\\Documents\\Analysis\\FPR Nov - Mar 2018\\*.xlsx", recursive=True): df = pd.read_excel(f) all_d = all_d.append(df,ignore_index=True)
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49862669
has answer: http://stackoverflow.com/a/49862669
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/86551037
score: 0
comment on: http://stackoverflow.com/q/49767872
type: Comment
type: QuestionComment
has text: Verify the header of `post` req. `'content-type': 'application/x-www-form-urlencoded'` . Is it correct ?

http://stackoverflow.com/comment/86663391
comment on: http://stackoverflow.com/q/49823526
type: Comment
type: QuestionComment
score: 0
has text: That was exactly what it was - thank you! I'll add what I've done as an answer, but am happy to accept yours if you want to write an answer.

http://stackoverflow.com/comment/86620132
type: Comment
type: QuestionComment
has text: Hmm. There *is* some overhead that goes up as you have more processes, just in closing the forked-off process's copy of your various FDs if they weren't created with the nofork flag, but I wouldn't expect that to be the level of sigificant you're reporting here.
comment on: http://stackoverflow.com/q/49802662
score: 0

http://stackoverflow.com/comment/86714003
type: QuestionComment
comment on: http://stackoverflow.com/q/49849683
score: 1
has text: if your dictionary is a then sum([a[k][3] for k in a]) will print 95, but you have to write a as {'bacon': ['packages', 5, 7, 35], 'eggs': ['cartons', 5, 2, 10], 'milk': ['gallons', 5, 10, 50]}
type: Comment

http://stackoverflow.com/a/63029780
type: Answer
answers question: http://stackoverflow.com/q/49873973
has body: async def main(): tornado.options.parse_command_line() ... app = Application(db) app.listen(options.port) shutdown_event = tornado.locks.Event() def shutdown( signum, frame ): print("shutdown database !!!!") db.close() shutdown_event.set() signal.signal(signal.SIGTERM, shutdown) signal.signal(signal.SIGINT, shutdown) await shutdown_event.wait() print("\n\nshutdown -h now") if __name__ == "__main__": tornado.ioloop.IOLoop.current().run_sync(main)
score: 0

aws-cloudformation
tag name: aws-cloudformation
type: Tag
tags question: http://stackoverflow.com/q/49784028

http://stackoverflow.com/q/49820329
has comment: http://stackoverflow.com/comment/86656496
has comment: http://stackoverflow.com/comment/86656064
has comment: http://stackoverflow.com/comment/86656147
downvote count: 1
has body: I'm working on a Raspberry-based project that needs SciPy, NumPy and scikit-learn. And we need to package our virtual environment in a .deb for distribution. For that, we use dh_virtualenv, which up until now has worked just fine. When I just install our requirements on the venv, like so: myvenv/bin/pip install numpy myvenv/bin/pip install scipy myvenv/bin/pip install sklearn The dependencies install just fine, although they take a painfully long time to do so. The problem comes when we try to make the package, following exactly these steps: mkdir myvenv-0.1 cd myvenv-0.1 dh_make --createorig nano ./debian/rules Then I find the "dh $@" part in the editor and I replace it with this %: dh $@ --with python-virtualenv --python /path/to/myvenv/bin/python And then I edit debian/control: nano ./debian/control and fill it up thusly: Source: myvenv Maintainer: My Name &lt;mymail@mymail.com&gt; Build-Depends: debhelper (&gt;= 9) Standards-Version: 3.9.5 Homepage: &lt;insert the upstream URL, if relevant&gt; Package: myvenv Version: 0.1-1 Architecture: armhf Pre-Depends: dpkg (&gt;= 1.16.1), python2.7 | python2.6 Section: python Priority: extra Description: My Description Then I freeze my requirements: /path/to/myvenv/bin/pip freeze &gt; requirements.txt nano into them: nano requirements.txt Then I look for the myvenv requirement line and remove it, otherwise the venv requires itself, which breaks the whole procedure later on (I know this too well.) At this point I generate a setup.py file for the myvenv package, which has to implement a fake unit test command, because dh_virtualenv tries to run the unit tests by default and the flag to disable them just doesn't work. Here's the file: from distutils.core import setup from distutils.cmd import Command class TestCommand(Command): user_options=[] description = '' def initialize_options(self): pass def finalize_options(self): pass def run(self): self.announce('test') setup( cmdclass={ 'test': TestCommand }, name='myvenv', version=…
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/86656559
type: Question
has comment: http://stackoverflow.com/comment/86666485
tagged with: gfortran
has comment: http://stackoverflow.com/comment/86658562
has comment: http://stackoverflow.com/comment/86658570
has comment: http://stackoverflow.com/comment/86658301
tagged with: python
has comment: http://stackoverflow.com/comment/86658019
tagged with: scipy
score: -1
has comment: http://stackoverflow.com/comment/86658001
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49875978
has title: Gfortran can't compile NumPy
has comment: http://stackoverflow.com/comment/86656724
type: AnsweredQuestion
tagged with: fortran
has answer: http://stackoverflow.com/a/49875978
upvote count: 0

http://stackoverflow.com/q/49821843
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49821929
tagged with: dataframe
tagged with: python
score: 2
has body: import pandas as pd C = {'name': ['Alice', 'Alice', 'Bob', 'Charlie'], 'phone': ['007', '1764', '1317210', '314159']} CONTACTS = pd.DataFrame(data = C) answer = {'guest_name': ['Alice', 'Bob', 'Charlie'], 'attending': [True, False, True]} guest_list = pd.DataFrame(data = answer) Illustrative context: I'm throwing a party, but there is a last-minute modification to the location. Thus, I want to call guests that said they will come. I have two pandas.DataFrame: my CONTACTS: with all my friends' name and phone. Note that some friends (e.g. Alice) are listed twice if they have multiple phone numbers. This DataFrame is a constant and I cannot (or don't want to) modify it. my guest_list: with all my friends' name and attending status (a boolean). Note that, unlike in CONTACTS, friends name are listed here only once. All friends name listed in CONTACTS exist in guest_list and vice-versa (in other words, CONTACTS.name is surjective onto guest_list.guest_name). Problem: I want to create the attending_guests_contact DataFrame containing the contact of my friends who attend the party only. Question: How to get a subset of CONTACTS based on answer.attending boolean? Note that: I don't want to modify CONTACTS, I would prefer not to create a copy of CONTACTS, as I have 'a lot' of contacts (~10^3—10^4) and multiple parties thrown so it would be time and memory consuming (i.e. I would like to perform the sub-selection in line). Edit: the two DataFrame don't share a same labeled column anymore.
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/49821975
tagged with: pandas
upvote count: 2
has title: pandas.DataFrame: Filter rows of df A based on data in df B?
has answer: http://stackoverflow.com/a/49821975
downvote count: 0
has answer: http://stackoverflow.com/a/49821929
favorite count: 0

http://stackoverflow.com/q/49764199
has comment: http://stackoverflow.com/comment/86544133
has comment: http://stackoverflow.com/comment/86544008
type: UnansweredQuestion
has body: To keep it completely simple: I opened a new project. In file lesson1.py I typed 1+2. The output is 3 Than I opened a new file lesson2.py and I typed 3+4. The output stays 3. Like it is not accepting the new file. What am I doing wrong? (I am not looking for a way to run the program like the other question which seems to be a duplicate of this, I know this is Shift-F10)
has title: Python: New (2nd) file in a project does output my 1st file in Pycharm
tagged with: python
score: 0
answer count: 0
tagged with: pycharm
has comment: http://stackoverflow.com/comment/86543998
linked to: http://stackoverflow.com/q/43807305
type: Question

http://stackoverflow.com/q/49777334
has answer: http://stackoverflow.com/a/49777715
has title: Pythonic way of using a variable as part of another variable?
tagged with: python
has comment: http://stackoverflow.com/comment/86570021
tagged with: date
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49777715
has comment: http://stackoverflow.com/comment/86570213
answer count: 1
has body: That's the clearest I could make my title. I have some code that reads in two CSV files. One CSV file has the data, and the other has information about this data... let's call it config. data_jan2018.csv data_feb2018.csv config.csv Now, config has columns for which dates I want to read in. I'm reading these in as follows: data_config = pd.read_csv(loc + data_config_name) # Read in dates from config file dates = data_config.drop_duplicates('Start_date') dates = dates'Start_date','End_date' print(dates) Start_date = dates['Start_date'].tolist() End_date = dates['End_date'].tolist() StartDate = ''.join(Start_date) EndDate = ''.join(End_date) print(StartDate) print(EndDate) date1 = datetime.strptime(StartDate, '%d%b%Y') date2 = datetime.strptime(EndDate, '%d%b%Y') # Loop across months for dt in rrule.rrule(rrule.MONTHLY, dtstart=date1, until=date2): print(dt) reporting_date = dt.strftime('%d%b%Y') reporting_date_fmt = dt.strftime(date_format) print('Formatted reporting_date is ' + reporting_date_fmt) source_data = pd.read_csv(loc + source_data_name) source_data.columns = source_data.columns.str.lower() As you can see, I want to read in a csv file called source_data_name. However, this file name contains my formatted reporting_date_fmt. I want the programmer to edit the file name at the beginning of the code so I have these line right at the top: date_format = '%b%Y' source_data_name = 'g4_RWA_sample_' + reporting_date_fmt + '.csv' But of course this flags a warning, telling me reporting_date_fmt hasn't been created yet. Is there a workaround to this?
type: Question

http://stackoverflow.com/a/49860404
has body: The problem is that you replace the context dict from the super() call with a brand new dictionary. def get_context_data(self, **kwargs): context = super(BookListView, self).get_context_data(**kwargs) ... context = { 'display_books':display_books, 'num_books':num_books, 'num_instances':num_instances, 'num_instances_available':num_instances_available, 'num_authors':num_authors } return context You should update the existing dictionary instead: def get_context_data(self, **kwargs): context = super(BookListView, self).get_context_data(**kwargs) ... context['display_books'] = display_books context['num_books'] = num_books context['num_instances'] = num_instances context['num_instances_available'] = num_instances_available context['num_authors'] = num_authors return context
type: Answer
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49860236
upvote count: 1

http://stackoverflow.com/comment/86826369
has text: but if you have the list as a= ' ['expert executive', 'internal committee period', 'report name', 'entry'] ' ? then it would be different story . do you have it like in this comment ?
type: AnswerComment
comment on: http://stackoverflow.com/a/49905246
score: 0
type: Comment

http://stackoverflow.com/comment/86646276
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49788047
has text: Any elements with the same key are always processed by the same reducer. That's how mapreduce works. Edit your question to include any error stacktrace and add the data that caused it. If you are interested in using Python, there are other libraries to process such data like MrJob or PySpark. Otherwise, see this post on how you can test your code locally before using Hadoop http://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/
type: Comment

http://stackoverflow.com/a/49898790
upvote count: 2
has comment: http://stackoverflow.com/comment/86812967
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49898747
score: 2
answers question: http://stackoverflow.com/q/49898747
type: AcceptedAnswer
has body: The first argument of __init__ should be self: def __init__(self, givenName, givenColor): self.name = givenName self.color = givenColor Otherwise, your code will fail as self will not be accessible within the method. You have 2 options to define attributes: Option 1 Define at initialization with __init__ as above. For example: r1 = robot('tom', 'red') Option 2 Do not define at initialization, in which case these arguments must be optional: class robot: def __init__(self, givenName='', givenColor=''): self.name=givenName self.color=givenColor def intro(self): print("my name izz "+self.name) r1 = robot() r1.givenName = 'tom' r1.givenColor = 'red'
has comment: http://stackoverflow.com/comment/86885743

http://stackoverflow.com/q/49889188
score: 8
favorite count: 0
type: Question
upvote count: 8
has comment: http://stackoverflow.com/comment/86794869
has body: I try to access the classmethod of a parent from within __init_subclass__ however that doesn't seem to work. Suppose the following example code: class Foo: def __init_subclass__(cls): print('init', cls, cls.__mro__) super(cls).foo() @classmethod def foo(cls): print('foo') class Bar(Foo): pass which produces the following exception: AttributeError: 'super' object has no attribute 'foo' The cls.__mro__ however shows that Foo is a part of it: (&lt;class '__main__.Bar'&gt;, &lt;class '__main__.Foo'&gt;, &lt;class 'object'&gt;). So I don't understand why super(cls).foo() doesn't dispatch to Foo.foo. Can someone explain this?
tagged with: python
has answer: http://stackoverflow.com/a/49890115
tagged with: inheritance
duplicate of: http://stackoverflow.com/q/17575074
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/86794578
has comment: http://stackoverflow.com/comment/86794535
linked to: http://stackoverflow.com/q/17575074
type: AnsweredQuestion
tagged with: class-method
accepted answer: http://stackoverflow.com/a/49890115
has comment: http://stackoverflow.com/comment/86794566
has title: Using `super()` within `__init_subclass__` doesn't find parent's classmethod
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/22403897

http://stackoverflow.com/q/49777533
linked to: http://stackoverflow.com/q/31730845
answer count: 1
has comment: http://stackoverflow.com/comment/86572387
has answer: http://stackoverflow.com/a/49786642
has title: I want to re-organize dictionary to panel data format but error appears
type: Question
has comment: http://stackoverflow.com/comment/86572338
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86570295
has body: My question is very similar to Reorganize Dictionary my dictionary comes in very similar type presented above. So I want to replicate this. But I have to error `''str' object cannot be interpreted as an integer. I present you my code. appended_data = pd.DataFrame() for item in data: for ii in list(item.keys()): df = pd.DataFrame.from_dict(item[ii], orient='index') df['date'] = int(ii) df['code'] = item[ii] appended_data = appended_data.append(df) dic = [appended_data.to_dict(orient='records')] # [[{'comp': '삼성자산운용', 'name': 'KODEX 레버리지', 'base': '코스피 200', 'lstdt': '2010/02/22', 'tax': '배당소득세(보유기간과세)', 'earn': '55.59', 'bosu': '0.64', 'ocha': '3.87', 'gap': '-0.48', 'nav': '18,494', 'volt': '높음', 'bun': '주식-시장대표', 'repli': '실물', 'pdf': '', 'info': '보기', 'date': 20180102, 'code': 'A278240'}, {'comp': '미래에셋자산운용', 'name': 'TIGER 레버리지', 'base': '코스피 200', 'lstdt': '2010/04/09', 'tax': '배당소득세(보유기간과세)', 'earn': '57.98', 'bosu': '0.09', 'ocha': '3.66', 'gap': '-0.27', 'nav': '295', 'volt': '보통', 'bun': '주식-시장대표', 'repli': '실물', 'pdf': '', 'info': '보기', 'date': 20180102, 'code': 'A267770'}] output = {} for entry in dic: entry = entry.copy() date = entry.pop('date') #Here is the error code = entry.pop('code') #Here is the error output.setdefault(code, {})[data] = entry Thank you so much
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/86570231
score: 0
tagged with: pandas

http://stackoverflow.com/comment/86782596
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49880673
has text: @PatrickHaugh okay mate i will try your advice. thanks a lot

http://stackoverflow.com/a/49837642
has body: Same problem here with OpenSuse Leap while trying to create a virtual environment. I get the exact same error as you, updating the system does not fix it, neither is updating anaconda. Maybe this is related to an update of Opensuse that causes an error with subprocess? [EDIT]: I solved this by removing and reinstalling anaconda. You have to make sure that no file is left behind during the uninstallation (the first time did not work for me because of that).
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49800656

http://stackoverflow.com/comment/86739739
has text: @JonClements thanks, just realised I had another issue too, see my answer.
type: QuestionComment
comment on: http://stackoverflow.com/q/49861786
type: Comment
score: 0

http://stackoverflow.com/comment/86741261
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.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49863035
score: 0

http://stackoverflow.com/comment/86600414
comment on: http://stackoverflow.com/q/49790974
has text: I did missed that. I have read the LM method though. I will see if I can figure it out. Thank you.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86682084
score: 3
comment on: http://stackoverflow.com/a/49832875
type: Comment
has text: This isn't exactly what I said. I said filtering 10 groups by the group name is faster than filtering the whole dataset and then grouping the whole dataset as both filtering and grouping (I am *assuming*) are a linear time operation. However if I try your example then `df[df.A >= 0].groupby('A')` is faster than something like `{name:group for name,group in df.groupby('A').groups.items() if name >= 0}` so I guess I don't have to worry about that speed so much.
type: AnswerComment

http://stackoverflow.com/a/49785917
has body: Maybe you want to use MathText instead of latex? plt.rcParams["mathtext.fontset"] = "stixsans" Complete example without latex: import numpy as np import matplotlib.pyplot as plt plt.rcParams["axes.labelsize"] = "large" plt.rcParams["mathtext.fontset"] = "stixsans" fig,ax=plt.subplots() all_lambda = np.linspace(-6,2,1000) ax.plot(all_lambda,np.exp(-np.exp(all_lambda))) ax.set_xlim([-6,2]) ax.set_ylim([-0.1,1.1]) ax.set_xlabel(r'$\log\lambda$') ax.set_ylabel(r'$\mathbb{P}(m=0\left| \lambda\right)$') fig.tight_layout() plt.show()
has comment: http://stackoverflow.com/comment/86587990
has comment: http://stackoverflow.com/comment/86596495
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49785653

http://stackoverflow.com/a/49763500
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49763476
upvote count: 5
has body: Option 1 zip Use zipped packing inside a dict comprehension. fields = [fields1, fields2, ...., fieldsN] {'column{}'.format(i) : list(v) for i, v in enumerate(zip(*fields), 1)} { 'column1' : ['A1', 'A2'], 'column2' : ['B1', 'B2'], 'column3' : ['C1', 'C2'] } Option 2 pd.DataFrame.to_dict This option uses the pandas API import pandas as pd pd.DataFrame(fields).rename( columns=lambda x: 'column{}'.format(x + 1) ).to_dict(orient='list') { 'column1' : ['A1', 'A2'], 'column2' : ['B1', 'B2'], 'column3' : ['C1', 'C2'] }
type: Answer
answers question: http://stackoverflow.com/q/49763476
score: 5

http://stackoverflow.com/q/49871917
has comment: http://stackoverflow.com/comment/86773050
tagged with: python
type: UnansweredQuestion
tagged with: service
has body: I have developed a python program to upload the file to S3, for that I have configured IAM access values using 'aws config' command (which creates ~/.aws folder and config and credentials with values within it). and when i run my program on the terminal the file uploaded to s3 successfully. Below is the code fragment: s3client=boto3.client('s3') s3client.upload_file(FILE_PATH, BUCKET_NAME,FILE_PATH) Now I'm trying to run this program from Linux service, for this i have created new service named s3upload.service in /lib/systemd/system/ folder. [Unit] Description=Demo S3 upload program After=multi-user.target [Service] Type=simple WorkingDirectory=/home/demouser/ ExecStart=/usr/bin/python /home/demouser/s3upload.py Restart=on-abort [Install] WantedBy=multi-user.target Surprisingly this doesn't work! Even though i have mentioned working directory for service is /home/demouser/ it is not recognizing ~/.aws folder contents? I'm getting follwing error: NoCredentialsError: Unable to locate credentials Heads Up: If I hard code the IAM access values in the program then it's working, but i don't want to follow that approach. Am i missing anything here when calling as service? how to fix this for service?
has comment: http://stackoverflow.com/comment/86770217
has answer: http://stackoverflow.com/a/49895848
downvote count: 0
tagged with: aws-sdk
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86801737
tagged with: boto3
answer count: 1
favorite count: 0
has title: How to give AWS Credentials and config file when program called from service
type: Question
has comment: http://stackoverflow.com/comment/86806292
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/86794103

http://stackoverflow.com/q/49893777
tagged with: http://stackoverflow.com/tag/json
answer count: 1
downvote count: 1
has title: parsing nested json and save in csv
favorite count: 0
tagged with: parsing
type: Question
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49894326
has body: I have a json file look like "persons" : { "-L1oNCxcRtS1" : { "createdByUser" : "P94r8Wlv3lOUZwsKB", "createdOn" : "2018-01-02T00:58:55.082Z", "modifiedByUser" : "P94r8Wlv3lOUZwsKBeb", "modifiedOn" : "2018-01-02T00:58:55.082Z", "photoBlobUser" : "OUZwsKBeblAy4vEyQ2", "userId" : "wsKBeblAy4vEyQ2" }, "-L1oNKHP3C" : { "createdByUser" : "UblFOHN3BqRKr2", "createdOn" : "2018-01-02T00:59:29.641Z", "emailAddress" : "adabas@abc.in", "isSocialDataShared" : true, "modifiedByUser" : "4owBjUblFOHN3BqRKr2", "modifiedOn" : "2018-04-11T16:00:08.318Z", "name" : "Arun", "nickname" : "Arun", "photoBlobUserID" : "4owBjHYyehdMwwUbl", "userId" : "4owBjHYyehdMwwUblFOHN3BqRKr2" } ............. where -L1oNCxcRtS1 and -L1oNKHP3C are persons, we need to parse the structure like it and save it in csv like table format where one additional column will be persons with the two values and rest of the columns will be keys. Please suggest.
has comment: http://stackoverflow.com/comment/86803083
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49787167
tagged with: blender
has title: Why normalized EXR renderings of surface Normals look different than PNG renderings?
has answer: http://stackoverflow.com/a/49822285
tagged with: python
possible better answer: http://stackoverflow.com/a/49808374
has body: I render surface Normals using Cycles and store the results in EXR format. The values in the EXR format are within the range of [-1, 1] meaning that I cannot directly store the values in a PNG file. Here's how I read the .exr files and store store the values in a numpy array: import OpenEXR, array, Imath exrFile = OpenEXR.InputFile('normal.exr') FLOAT = Imath.PixelType(Imath.PixelType.FLOAT) (RGB) = [array.array('f', exrFile.channel(Chan, FLOAT)).tolist() for Chan in ("R", "G", "B") ] normalNPArray = np.array(RGB) normalNPArray = normalNPArray.reshape((3, resolution, resolution)) I normalize the values as follow and store the surface Normal as a PNG image: normalNPArray += 1 normalNPArray /= 2 normalNPArray *= 255 normalNPArray = normalNPArray.astype(np.uint8) im = Image.fromarray(normalNPArray.transpose(1, 2, 0), mode='RGB') im.save('temp.png') Here's what I get after opening the stored image: If I simply ignore the values below zero (remove/comment the first two lines) I get the following: However, if I directly store the surface Normal as a PNG image instead of EXR I get the following: I wonder, how can I get a visualization that looks like the PNG rendering? How does Blender normalize the values?
has comment: http://stackoverflow.com/comment/86590733
has comment: http://stackoverflow.com/comment/86589727
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49808374
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49822285
tagged with: 3d
tagged with: rendering
has comment: http://stackoverflow.com/comment/86618676
has comment: http://stackoverflow.com/comment/86618893
has comment: http://stackoverflow.com/comment/86595847
type: Question
tagged with: graphics

http://stackoverflow.com/comment/86565373
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49771602
has text: @Minion Please provide your complete code and some data samples which produce the error. Edit the question to add the details.
score: 0

http://stackoverflow.com/a/49788653
downvote count: 0
answers question: http://stackoverflow.com/q/49788048
type: Answer
has comment: http://stackoverflow.com/comment/86592420
score: 2
has body: Assign blob.tags to a dataframe, then use df.to_csv(). Replace "blob.to_csv("abhi_blob.csv",sep=',')" with these two lines: blob_tags_df = pd.DataFrame(blob.tags) blob_tags_df.to_csv("abhi_blob.csv",sep=',')
upvote count: 2
has comment: http://stackoverflow.com/comment/86610380

http://stackoverflow.com/a/49786016
has comment: http://stackoverflow.com/comment/114278639
type: Answer
upvote count: 26
has comment: http://stackoverflow.com/comment/93893290
has comment: http://stackoverflow.com/comment/114269761
has comment: http://stackoverflow.com/comment/86588217
answers question: http://stackoverflow.com/q/49785865
has comment: http://stackoverflow.com/comment/114280295
has comment: http://stackoverflow.com/comment/86590416
has comment: http://stackoverflow.com/comment/86589358
has comment: http://stackoverflow.com/comment/114278850
has comment: http://stackoverflow.com/comment/99936538
has comment: http://stackoverflow.com/comment/86590224
has comment: http://stackoverflow.com/comment/114280445
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/114263432
has comment: http://stackoverflow.com/comment/86588129
has comment: http://stackoverflow.com/comment/99368754
has body: The message means exactly what it says: because you have called next() on the file, the use of tell() on that file has been disabled. It might not look like you've called next, but the for loop calls it implicitly. A for loop: for element in thing: do_stuff_with(element) is syntactical sugar for iterator = iter(thing) # the real implementation doesn't use a variable while True: try: element = next(iterator) # here's the next() call except StopIteration: break do_stuff_with(element) For a file, iter(file) returns the file, and the loop calls next on the file. As for why calling next disables tell(), this is for efficiency. It only happens for text files (specifically io.TextIOWrapper), which have to do a bunch of extra work to support tell; turning off tell support lets them skip that work. The original commit message for the change that made next disable tell is "Speed up next() by disabling snapshot updating then.", indicating it's for efficiency. For historical context, previous Python versions used a hidden buffer for next that tell and other file methods didn't account for, causing tell (and other file methods) to produce not-very-meaningful results during iteration over a file. The current IO implementation would be able to support tell() during iteration, but io.TextIOWrapper prevents such calls anyway. The historical incompatibility between next and other methods likely contributed to why it was considered reasonable to disable parts of file functionality during iteration. You didn't ask for workarounds, but for the benefit of people who end up on this page looking for a workaround, I'll mention that for line in iter(file.readline, ''): ... will let you iterate over the lines of a text file without disabling tell. (You can use for line in iter(file.readline, b'') for binary files, but there's not much point, because the tell disabling mechanism isn't there for binary files.)
accepted answer of: http://stackoverflow.com/q/49785865
has comment: http://stackoverflow.com/comment/93891627
has comment: http://stackoverflow.com/comment/114280330
has comment: http://stackoverflow.com/comment/130828583
score: 26

http://stackoverflow.com/a/49829913
has comment: http://stackoverflow.com/comment/86675527
has comment: http://stackoverflow.com/comment/103934538
has body: You can pass a custom key function to list.sort: x = [4,6,9,'ashley','drooks','chay','poo','may'] x.sort(key=lambda v: (isinstance(v, str), v)) # result: # [4, 6, 9, 'ashley', 'chay', 'drooks', 'may', 'poo'] This key function maps each element in the list to a tuple in which the first value is a boolean (True for strings and False for numbers) and the second value is the element itself, like this: &gt;&gt;&gt; [(isinstance(v, str), v) for v in x] [(False, 4), (False, 6), (False, 9), (True, 'ashley'), (True, 'chay'), (True, 'drooks'), (True, 'may'), (True, 'poo')] These tuples are then used to sort the list. Because False &lt; True, this makes it so that integers are sorted before strings. Elements with the same boolean value are then sorted by the 2nd value in the tuple.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86676533
has comment: http://stackoverflow.com/comment/86676169
answers question: http://stackoverflow.com/q/49829732
has comment: http://stackoverflow.com/comment/86675645
has comment: http://stackoverflow.com/comment/86688999
type: Answer
accepted answer of: http://stackoverflow.com/q/49829732
has comment: http://stackoverflow.com/comment/134111137
upvote count: 25
score: 25
has comment: http://stackoverflow.com/comment/86675575

http://stackoverflow.com/q/49906101
has title: Byte array to Int in Python 2.x using Standard Libraries
has body: I am comfortable in Python 3.x and Bytearray to Decimal conversion using int.from bytes(). Could come up with the below conversion snippet. Is there a way to achieve the same functionality using Python 2 for positive and negative integers. val = bytearray(b'\x8f\x0f\xfd\x02\xf4\x95s\x00\x00') a = int.from_bytes(val, byteorder='big', signed=True) # print(type(a), type(val), val, a) # &lt;class 'int'&gt; &lt;class 'bytearray'&gt; bytearray(b'\x8f\x0f\xfd\x02\xf4\x95s\x00\x00') -2083330000000000000000 Need to use Python 2.7 standard libraries to convert byte array to Int. Eg. bytearray(b'\x00')--&gt; Expected Result: 0 bytearray(b'\xef\xbc\xa9\xe5w\xd6\xd0\x00\x00') --&gt; Expected Result: -300000000000000000000 bytearray(b'\x10CV\x1a\x88)0\x00\x00') --&gt; Expected Result: 300000000000000000000
linked to: http://stackoverflow.com/q/30402743
has comment: http://stackoverflow.com/comment/86828040
favorite count: 0
has answer: http://stackoverflow.com/a/49908943
has comment: http://stackoverflow.com/comment/86841505
tagged with: python-3.x
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/86828155
accepted answer: http://stackoverflow.com/a/49908943
type: Question
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/86828245
has comment: http://stackoverflow.com/comment/86828024
upvote count: 1
has comment: http://stackoverflow.com/comment/86828132
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/86828080

http://stackoverflow.com/q/49832185
type: Question
has answer: http://stackoverflow.com/a/49832435
type: AnsweredQuestion
score: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/49832435
tagged with: argmax
has title: How to build argsecondmax in Numpy
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/49832368
upvote count: 3
has body: In Numpy, argmax is already defined, but I need argsecondmax, which is basically the second maxima. How can I do this, I'm a bit confused?
downvote count: 0
has answer: http://stackoverflow.com/a/49832368
tagged with: machine-learning
favorite count: 0

http://stackoverflow.com/comment/86644876
type: QuestionComment
has text: But if my jason file is having more than one record/object in it , the code is failing,as the putitem argument (Item)should be a class dict.
score: 0
comment on: http://stackoverflow.com/q/49815235
type: Comment

http://stackoverflow.com/q/49842652
tagged with: python
has answer: http://stackoverflow.com/a/49842789
downvote count: 6
tagged with: list
answer count: 2
upvote count: 0
type: UnansweredQuestion
tagged with: loops
has body: Given n = 5 My triangle should look like this : * *+* *+++* *+++++* ********* What i have tried : n = 5 for x in range(0, n): for y in range(0, n-x-1): print(end = "") for z in range(0,x+1): print("*", end = "") print() but the result is like this : * ** *** **** ***** Thanks for help and maybe some explanations
score: -6
favorite count: 0
type: Question
tagged with: python-3.x
has title: Print a simple triangle using list and loops in python
has answer: http://stackoverflow.com/a/49855986

http://stackoverflow.com/q/49783981
tagged with: python
has title: Using 3 channel image in numpy as texture image in vtk
has comment: http://stackoverflow.com/comment/86600983
has body: I have a RGB image in numpy format that I want to using for texture mapping using vtk. I usually load the texture image using PNGReader as should below -- png_reader = vtk.vtkPNGReader() png_reader.SetFileName(png_file) texture.SetInputConnection(png_reader.GetOutputPort()) I know vtk provides some sort of python integration but I wasn't sure how to do it. EDIT -- I looked at this, but that solution doesn't seem to work.
score: 0
linked to: http://stackoverflow.com/q/45395269
answer count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/86613040
tagged with: vtk
has answer: http://stackoverflow.com/a/54303637
has comment: http://stackoverflow.com/comment/86837904
type: UnansweredQuestion

http://stackoverflow.com/q/49905818
tagged with: dataframe
has title: I have pandas dataframe which i would like to be sliced after every 4 columns
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86827474
has answer: http://stackoverflow.com/a/49906149
has comment: http://stackoverflow.com/comment/86827897
has comment: http://stackoverflow.com/comment/86827914
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
answer count: 1
tagged with: python
tagged with: pandas
has comment: http://stackoverflow.com/comment/86828068
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/86827825
has body: I have pandas dataframe which i would like to be sliced after every 4 columns and then vertically stacked on top of each other which includes the date as index.Is this possible by using np.vstack()? Thanks in advance! ORIGINAL DATAFRAME Please refer the image for the dataframe. I want something like this WANT IT MODIFIED TO THIS

http://stackoverflow.com/a/49775211
type: Answer
has body: Very similar to Rakesh's answer but without reading the whole file just to find the line with "Measurement values:" import pandas as pd file_name = r"filename.csv" line_number = -1 with open(file_name, "r") as in_file: for i, line in enumerate(in_file, 1): if line.startswith("Measurement values:"): lineNumber = i break if line_number == -1: raise RuntimeError("Could not find end of header") df = pd.read_csv(file_name, skiprows = line_number) print(df)
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49773742

http://stackoverflow.com/comment/86687911
score: 0
comment on: http://stackoverflow.com/q/49826592
type: Comment
type: QuestionComment
has text: @sacul useful, followed it as you can see from the edit. However, either I'm not getting the results properly or the regression is not being run correctly.

http://stackoverflow.com/comment/105438201
type: AnswerComment
score: 1
has text: With some distance, I can see it was a rather unforgivable error on my part to allow __getitem__ to return None rather than raising a KeyError
type: Comment
comment on: http://stackoverflow.com/a/49889557

http://stackoverflow.com/a/49904989
answers question: http://stackoverflow.com/q/49904571
downvote count: 0
upvote count: 1
score: 1
has body: No there is no complete documentation for the CPython source code. The public API is documented (Python library reference and the C-API documentation). However there are also some documentations (although not complete and very superficial) in the development guide especially exploring the internals (including the links at the bottom). And you can always inspect the source code directly: CPython repository on GitHub.
type: Answer

http://stackoverflow.com/q/49806642
tagged with: bash
has comment: http://stackoverflow.com/comment/86656223
has comment: http://stackoverflow.com/comment/86648915
answer count: 1
tagged with: scripting
has title: Bash Process Execution Logic
upvote count: 1
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49806932
type: Question
has answer: http://stackoverflow.com/a/49806932
has comment: http://stackoverflow.com/comment/86628605
has body: I have a number of scripts to run, some of which have one or more scripts that must be completed first. I've read a number of examples showing how bash's control operators work, but haven't found any good examples to address the complexity of the logic i'm trying to implement. I have p_01.py and p_03.py that are both requirements for p_09.py, but also have individual processes that only require p_01. For example: ((python p_01.py &amp; python p_03.py) &amp;&amp; python p_09.py) &amp; (python p_01.py &amp;&amp; ( (python p_05.py; python p_10.py) &amp; (python p_08.py; python p_11.py) ) ) wait $(jobs -p) My question is, how can I accomplish all of the scripts running only after their requirements without repeating the running scripts (such as p_01.py, which you'll notice it's used twice above)? I'm looking for a generalized answer with some detail, since in actuality the dependencies are more numerous/nested than the example above. Thank you!
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86630310
type: AnsweredQuestion

http://stackoverflow.com/q/49812619
tagged with: image-segmentation
tagged with: deep-learning
upvote count: 2
score: 2
answer count: 1
downvote count: 0
has title: Keras image segmentation: loss function for a single pixel
tagged with: keras
has answer: http://stackoverflow.com/a/49826321
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
has body: My problem may be easy to solve for you but I did not found any answer out there and have no idea how to implement that as I am also fairly new to Keras and Tensorflow. The problem: I use a pretrained image segmentation net (PSPNet by Hengshuang Zhao et al 2017), for which someone converted the weights from Caffe to Keras with Tensorflow backend (PSPNet-Keras-tensorflow). I want to compute the gradient of a categorical crossentropy loss function with respect to the weights, not that complicated so far and solvable by me. But the problem is the loss function, because I only want the loss at a single pixel of the prediction. What I have so far for the loss of the whole image is: weights = model.trainable_weights gradients = model.optimizer.get_gradients(model.total_loss, weights) # model is compiled with categorical crossentropy input_tensor = [model.inputs[0], # input data model.sample_weights[0], # how much to weight each sample by model.targets[0], # labels keras.backend.learning_phase() # train or test mode] get_gradients = keras.backend.function(inputs=input_tensors, outputs=gradients) How do I have to adjust this to calculate only the loss for a single pixel? PS: Afterwards I want to iterate over a whole image (~2million pixels) and calculate for each pixel the gradient of the categorical crossentropy loss with respect to the weights. Thanks for any help and suggestions.
tagged with: python

http://stackoverflow.com/comment/86812734
has text: it brought back a " Traceback (most recent call last): File "c:\Users\dell\Desktop\Locale\packages\animals2.py", line 38, in <module> while not(new_catch in animals):TypeError: unhashable type: 'list'PS C:\Users\dell\Desktop\Locale\packages>" but i also need it to add the new inputs to my empty list
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49897909
type: Comment

http://stackoverflow.com/a/49800538
upvote count: 6
downvote count: 2
type: AcceptedAnswer
score: 4
answers question: http://stackoverflow.com/q/49799931
type: Answer
accepted answer of: http://stackoverflow.com/q/49799931
has body: Converting my comment to an answer here. You can use: import re str = re.sub(r'\s*&lt;[^&gt;]*&gt;\s*', ' ', str) Regex \s*&lt;[^&gt;]*&gt;\s* matches a string that starts with &lt; and ends with &gt; surrounded by optional whitespaces on either side.

http://stackoverflow.com/q/49915714
has comment: http://stackoverflow.com/comment/86847995
answer count: 1
tagged with: rpy2
tagged with: python
has body: I am trying to install rpy2 on a machine running Windows 10. I have already installed R 3.4.4 (64bit) and it works fine in RGui. I then tried to pip install rpy2, but was getting an error that it couldn't find R, so I added c:\Program Files\R\R-3.4.4\bin\ to my path environment variable. Now when I do pip install rpy2 I get a different error: Command '('c:\PROGRA~1\R\R-34~1.4\bin\x64\R', 'CMD', 'config', '--ldflags')' returned non-zero exit status 1 The full output is given below. Any idea what I am doing wrong? pip install rpy2 Collecting rpy2 Downloading https://files.pythonhosted.org/packages/88/f7/788e5e1587bc1ab48b5b0467f9c3a08ef5aadbd993ed835559a10e452121/rpy2-2.9.3.tar.gz (193kB) Complete output from command python setup.py egg_info: R version 3.4.4 (2018-03-15) -- "Someone to Lean On" Copyright (C) 2018 The R Foundation for Statistical Computing Platform: x86_64-w64-mingw32/x64 (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under the terms of the GNU General Public License versions 2 or 3. For more information about these matters see http://www.gnu.org/licenses/. 'sh' is not recognized as an internal or external command, operable program or batch file. R version 3.4.4 (2018-03-15) -- "Someone to Lean On" c:\PROGRA~1\R\R-34~1.4\bin\x64\R CMD config --ldflags Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\py\AppData\Local\Temp\pip-build-qz4rb_4o\rpy2\setup.py", line 374, in &lt;module&gt; ri_ext = getRinterface_ext() File "C:\Users\py\AppData\Local\Temp\pip-build-qz4rb_4o\rpy2\setup.py", line 269, in getRinterface_ext ldf = shlex.split(' '.join(rexec.cmd_config('--ldflags'))) File "C:\Users\py\AppData\Local\Temp\pip-build-qz4rb_4o\rpy2\setup.py", line 222, in cmd_config universal_newlines = True) File "c:\users\py\miniconda3\lib\subprocess.py", line 626, in check_output **kwargs).stdout File "c:\users\py\miniconda3\lib\subprocess.py", line 708, in run out…
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/86848127
has comment: http://stackoverflow.com/comment/86848290
downvote count: 0
linked to: http://stackoverflow.com/q/57882963
score: 4
accepted answer: http://stackoverflow.com/a/49917003
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/45093811
has answer: http://stackoverflow.com/a/49917003
has title: Installing rpy2 on windows

http://stackoverflow.com/q/49822414
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49846478
tagged with: unique
favorite count: 0
type: Question
tagged with: row
has body: Let's say I have the following dataFrame and I want to drop the rows containing 10, and 100, i.e. the elements that have appeared only once in col1. I can do the following: a = df.groupby('col1').size() b = list(a[a == 1].index) and then have a for loop and drop the rows one by one: d_ind = df[df['col1']==b[0]].index df.drop(d_ind, axis=0, inplace=True) Is there any faster, more efficient way?
has title: Drop rows of a pandas dataFrame with unique elements in a given column. (by unique I mean repeated once)
tagged with: dataframe
tagged with: python
score: 4
upvote count: 4
accepted answer: http://stackoverflow.com/a/49846478
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/a/49835655
score: 1
upvote count: 1
downvote count: 0
type: Answer
has body: They accomplish different things. The former returns a list of lambas that return numbers and the latter returns a lambda that returns a list of numbers. You can imagine different use cases for each.
answers question: http://stackoverflow.com/q/49835619

http://stackoverflow.com/comment/86724581
score: 0
comment on: http://stackoverflow.com/a/49855058
type: Comment
has text: Thanks! What is the difference between `CROSS JOIN` and `,` as in [this answer](https://stackoverflow.com/a/49854984/1422096)?
type: AnswerComment

google-translation-api
tags question: http://stackoverflow.com/q/49913350
type: Tag
tag name: google-translation-api

http://stackoverflow.com/q/49902879
has body: Came across this example online, its a dfs function which finds all the cycles within a graph. I'm trying to add the cycle part into the function so i don't have to use the shell to get the results. I'm new to generator objects so I'm not sure how to display cycles. version which uses the shell: def dfs(graph, start, end): fringe = [(start, [])] while fringe: state, path = fringe.pop() if path and state == end: yield path continue for next_state in graph[state]: if next_state in path: continue fringe.append((next_state, path+[next_state])) &gt;&gt;&gt; graph = { 1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2] } &gt;&gt;&gt; cycles = [[node]+path for node in graph for path in dfs(graph, node, node)] &gt;&gt;&gt; len(cycles) 7 &gt;&gt;&gt; cycles [[1, 5, 2, 1], [1, 3, 1], [1, 2, 1], [2, 1, 5, 2], [2, 1, 2], [3, 1, 3], [5, 2, 1, 5]] Here is my attempt: def dfs(g, start, end): fringe = [(start, [])] while fringe: state, path = fringe.pop() if path and state == end: yield path continue for next_state in g[state]: if next_state in path: continue fringe.append((next_state, path+[next_state])) cycles = (list([node]+path for node in g for path in dfs(g, node, node))) print("cycles",cycles) return path dfs(graph, 1, 1) tried several different start and end nodes all the same result. my graph is the same as above, graph = { 1: [2, 3, 5], 2: [1], 3: [1], 4: [2], 5: [2] } output = generator object dfs at 0x000001D9CB846EB8 Any ideas?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86821227
downvote count: 0
tagged with: brute-force
score: 1
has title: how can i print out the generator object without using the shell?
has comment: http://stackoverflow.com/comment/86821535
type: Question
tagged with: graph
has comment: http://stackoverflow.com/comment/86821653
tagged with: function-calls
answer count: 2
has answer: http://stackoverflow.com/a/49903114
possible better answer: http://stackoverflow.com/a/49903114
upvote count: 1
has comment: http://stackoverflow.com/comment/86821596
has comment: http://stackoverflow.com/comment/86821319
tagged with: python
tagged with: depth-first-search
has answer: http://stackoverflow.com/a/49903258
accepted answer: http://stackoverflow.com/a/49903258
favorite count: 0

firefox
type: Tag
tags question: http://stackoverflow.com/q/49885701
tags question: http://stackoverflow.com/q/49795554
tags question: http://stackoverflow.com/q/49904109
tag name: firefox
tags question: http://stackoverflow.com/q/49846327

http://stackoverflow.com/a/49909340
accepted answer of: http://stackoverflow.com/q/49909176
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49909176
upvote count: 4
has comment: http://stackoverflow.com/comment/86835788
has comment: http://stackoverflow.com/comment/86834747
has comment: http://stackoverflow.com/comment/86835565
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/86835773
has comment: http://stackoverflow.com/comment/86834796
has comment: http://stackoverflow.com/comment/86856877
has comment: http://stackoverflow.com/comment/86836230
has comment: http://stackoverflow.com/comment/86836242
has comment: http://stackoverflow.com/comment/86835516
has body: Since there is a small set of borough names for which to assign the integer codes, it's perfectly acceptable to do it as a series of explicit logical index assignments, such as with some example data below. Specifically, there is no need in this case to try to encapsulate the borough-to-code mapping into a dict or a helper function or any fancier apply or map operation on the DataFrame. Just a set of 5 boring, direct logical assignments. In [13]: df = pandas.DataFrame({ 'Borough': ["Manhattan", "Brooklyn", "Bronx", "07 Bronx", "109 Staten Island", "03 Brooklyn", "04 Queens"], 'Value':[1, 2, 3, 4, 5, 6, 7] }) In [14]: df Out[14]: Borough Value 0 Manhattan 1 1 Brooklyn 2 2 Bronx 3 3 07 Bronx 4 4 109 Staten Island 5 5 03 Brooklyn 6 6 04 Queens 7 In [15]: df['Borough_num'] = 6 # everything defaults to the 'other' case In [16]: df.loc[df.Borough.str.contains("Manhattan"), 'Borough_num'] = 1 In [17]: df.loc[df.Borough.str.contains("Brooklyn"), 'Borough_num'] = 2 In [18]: df.loc[df.Borough.str.contains("Queens"), 'Borough_num'] = 3 In [19]: df.loc[df.Borough.str.contains("Staten Island"), 'Borough_num'] = 4 In [20]: df.loc[df.Borough.str.contains("Bronx"), 'Borough_num'] = 5 In [21]: df Out[21]: Borough Value Borough_num 0 Manhattan 1 1 1 Brooklyn 2 2 2 Bronx 3 5 3 07 Bronx 4 5 4 109 Staten Island 5 4 5 03 Brooklyn 6 2 6 04 Queens 7 3 If you want to encapsulate the borough-to-code mapping for whatever reason, you can do it with a simple dict followed by a loop: In [30]: borough_code = {'Manhattan': 1, 'Brooklyn': 2, 'Queens': 3, 'Staten Island': 4, 'Bronx': 5} In [31]: for borough, code in borough_code.items(): ...: df.loc[df.Borough.str.contains(borough), 'Borough_num'] = code Unless the DataFrame is gigantic, the repeated vectorized calculation of str.contains will be indistinguishable from mapping a function across the column, but will be much easier to understand.

http://stackoverflow.com/q/49784872
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/86747561
has comment: http://stackoverflow.com/comment/86624351
favorite count: 0
has title: Entry-wise constraints in CVXPY
type: Question
has comment: http://stackoverflow.com/comment/86747696
tagged with: elementwise-operations
type: UnansweredQuestion
has body: I try to impose some elementwise constraints to the optimization variable using cvxpy. Here is the code: import cvxpy as cv import numpy as np import scipy.io as spio mat = spio.loadmat('data.mat', squeeze_me=True) zigma_bar_region1_normal = mat['zigma_bar_region1_normal'] # array J1_multi=mat['Q1'] # array multiplier1_multi=mat['multiplier1_multi'] # array J1_bar_multi=mat['J1_bar_multi'] # array J_multi_reg1_normal_part2=mat['J_multi_reg1_normal_part2'] # array # Construct the problem. J_reg1_normal = cv.Variable(12,12) objective = cv.Maximize( - 0.5*cv.trace(zigma_bar_region1_normal[0:12,0:12]*J_reg1_normal) + 0.5 * cv.log_det(J_reg1_normal) ) constraints = [0 &lt;= J_reg1_normal , J_reg1_normal[[0],[2,3,4,5,6,7,8,9,11]] == 0 , J_reg1_normal[[1],[3,5,6,7,8,9,10,11]] == 0 , J_reg1_normal[[2],[4,5,6,8,9,10,11]] == 0 , J_reg1_normal[[3],[5,6,7,8,9,10,11]] == 0 , J_reg1_normal[[4],[6,7,8,9,10,11]] == 0 , J_reg1_normal[[5],[6,7,8,9,10,11]] == 0 , J_reg1_normal[[6],[8,10]] == 0 , J_reg1_normal[[7],[9,10,11]] == 0 , J_reg1_normal[[8],[10,11]] == 0 , J_reg1_normal[[9],[11]] == 0 , J_reg1_normal[[10],[11]] == 0] # solution prob =cv.Problem(objective, constraints) result = prob.solve() print (J_reg1_normal.value) Based on the elementwise constraints (all the constraints except for the first one) that I imposed, I expect to see the related elements of the optimization variable equal to zero but the reslut is: J_reg1_normal.value= [[ 5.00766997e-02 -5.37660541e-08 -7.46538281e-07 -8.10192632e-07 -7.64060978e-07 1.25086461e-06 -1.03525218e-06 -7.51147527e-07 -9.97192725e-07 -1.24346873e-06 -5.76822200e-07 1.21530067e-07] [ -7.45516570e-07 7.37738183e-02 1.72064920e-07 3.36427991e-07 2.49936553e-07 7.95798210e-07 8.55689658e-08 1.84734980e-07 5.75522200e-08 4.81760532e-07 -5.45853914e-07 4.76049220e-07] [ -1.09635151e-06 8.07142981e-08 8.19960687e-02 2.11452883e-07 3.22655657e-07 1.19484242e-07 5.36718902e-07 2.61031577e-07 4.87627330e-07 1.03295724e-06 -1.44733384e-07 1.01243…
downvote count: 0
has comment: http://stackoverflow.com/comment/87928992
tagged with: python
tagged with: constraints
has comment: http://stackoverflow.com/comment/86624514
answer count: 0
has comment: http://stackoverflow.com/comment/86601540
tagged with: convex-optimization
has comment: http://stackoverflow.com/comment/86601396
tagged with: cvxpy
has comment: http://stackoverflow.com/comment/86780903

http://stackoverflow.com/q/49852825
type: UnansweredQuestion
tagged with: django-channels
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
has body: I need some help. I'm using Django-channels and I need for some purpose make several DB calls. Docs not clear for me: https://channels.readthedocs.io/en/latest/topics/databases.html So, what one of the following is the right way? 1. Create/call function for each database access with a decorator. 2. Make all calls to the database in one function, which wrapped by decorator?
has answer: http://stackoverflow.com/a/61820531
favorite count: 0
has title: database access from asynchronous code in Django-channels
score: 1
tagged with: database
has comment: http://stackoverflow.com/comment/86743115
tagged with: python
tagged with: asynchronous
type: Question

http://stackoverflow.com/q/49760431
has title: 'or' not working on while-loop
has comment: http://stackoverflow.com/comment/86536198
has answer: http://stackoverflow.com/a/49760832
tagged with: while-loop
upvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86535993
has comment: http://stackoverflow.com/comment/86535999
type: UnansweredQuestion
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/86536407
has body: print("You see an orc standing in your path. There is no way out but through it.") print("0. Escape\n1. Fight\n2. Defend\n3. Heal") Action = int(input("You grip your sword tightly and think about what to do next.")) while Action (!= 0) or (OrcHealth &lt;=0): if Action == 1: HeroAttack=random.randint(1,5) OrcHealth = OrcHealth - HeroAttack print("You see an opening, this is your chance! You swing your blade and do",HeroAttack,"to the orc.\n This brings the beast down to", OrcHealth) Action = int(input("You grip your sword tightly and think about what to do next.")) At line 6 I begin my while-loop. It half-works, but when OrcHealth reaches 0 or less the while-loop does not terminate as I intend. Does anyone know what I have done wrong?
tagged with: python

http://stackoverflow.com/comment/86550205
score: 1
type: Comment
type: QuestionComment
has text: You can prevent downvotes if add to your question what you try, your code. If some errors, no problem, but add it to question too.
comment on: http://stackoverflow.com/q/49767227

python-asyncio
tags question: http://stackoverflow.com/q/49779773
tags question: http://stackoverflow.com/q/49829320
tags question: http://stackoverflow.com/q/49759307
tags question: http://stackoverflow.com/q/49878329
tags question: http://stackoverflow.com/q/49837294
tags question: http://stackoverflow.com/q/49822552
tags question: http://stackoverflow.com/q/49787794
tags question: http://stackoverflow.com/q/49858021
tags question: http://stackoverflow.com/q/49858711
tags question: http://stackoverflow.com/q/49866918
tags question: http://stackoverflow.com/q/49901840
tags question: http://stackoverflow.com/q/49869769
tag name: python-asyncio
tags question: http://stackoverflow.com/q/49824768
type: Tag
tags question: http://stackoverflow.com/q/49784996
tags question: http://stackoverflow.com/q/49770609
tags question: http://stackoverflow.com/q/49906034

http://stackoverflow.com/q/49817153
has answer: http://stackoverflow.com/a/71296175
tagged with: python
answer count: 2
downvote count: 0
has body: For some reason, the Y-axis while plotting with altair seems to be inverted (would expect values to go from lower (bottom) to higher (top) of the plot). Also, I would like to be able to change the ticks frequency. With older versions I could use ticks=n_ticks but it seems now this argument can take only boolean. import altair as alt alt.renderers.enable('notebook') eff_metals = pd.read_excel(filename, sheet_name='summary_eff_metals') points = alt.Chart(eff_metals, height=250, width=400).mark_circle().encode( x=alt.X('Temperature:Q',axis=alt.Axis(title='Temperature (°C)'), scale=alt.Scale(zero=False, padding=50)), y=alt.Y('Efficiency:N',axis=alt.Axis(title='Efficiency (%)'), scale=alt.Scale(zero=False, padding=1)), color=alt.Color('Element:N'), ) text = points.mark_text(align='right', dx=0, dy=-5).encode( text='Element:N' ) chart = alt.layer(points, text, data=eff_metals, width=600, height=300) chart And the figure:
tagged with: axis
score: 6
has answer: http://stackoverflow.com/a/49841721
has title: Invert axis direction Altair
tagged with: altair
favorite count: 0
type: Question
type: UnansweredQuestion
upvote count: 6

http://stackoverflow.com/a/49831090
has body: You do not need to use pd.DataFrame.drop for this: mask = df1['barcode'].str.contains('....-..-....-11.', regex=True) df1 = df1[~mask] The ~ operator represents negation. Since mask is a Boolean array, it is negated and used as a row filter on df1.
has comment: http://stackoverflow.com/comment/86677757
score: 0
answers question: http://stackoverflow.com/q/49831072
type: Answer

http://stackoverflow.com/a/49886983
has body: Here's a vectorized approach making use of masking - def func_mask_vectorized(data, (x_0, y_0)): # Leverage broadcasting with open meshes to create the squared distances/ids m,n = data.shape Y,X = np.ogrid[:m,:n] ids = (X-x_0)**2 + (Y-y_0)**2 # Setup mask that will help us retrieve the unique "compressed" IDs # (similar to what return_inverse does). # This is done by setting 1s at ids places and then using that mask to # assign range covered array, in effect setting up the unique compress. IDs. mask = np.zeros(ids.max()+1, dtype=bool) mask[ids] = 1 id_arr = mask.astype(int) id_arr[mask] = np.arange(mask.sum()) r_out = id_arr[ids] # Finally extract out the unique ones among the IDs &amp; get their sqrt values float_values_out = np.sqrt(np.flatnonzero(mask)) return float_values_out, r_out Benchmarking Timing on the proposed setup with a data of shape (500,500), using the numbers range of 0-9 as also used in the sample from the question and timing all the complete solutions in this section below - In [371]: np.random.seed(0) ...: data = np.random.randint(0,10,(500,500)) ...: x_0 = 2 ...: y_0 = 3 # Original soln In [372]: %timeit func(data, (x_0,y_0)) 1 loop, best of 3: 6.77 s per loop # @Daniel's soln In [373]: %timeit func_return_inverse(data, (x_0,y_0)) 10 loops, best of 3: 23.9 ms per loop # Soln from this post In [374]: %timeit func_mask_vectorized(data, (x_0,y_0)) 100 loops, best of 3: 5.02 ms per loop Extending for cases where the numbers may extend to 100 or even 1000 doesn't change much on how these stack up - In [397]: np.random.seed(0) ...: data = np.random.randint(0,100,(500,500)) ...: x_0 = 50 ...: y_0 = 50 In [398]: %timeit func(data, (x_0,y_0)) ...: %timeit func_return_inverse(data, (x_0,y_0)) ...: %timeit func_mask_vectorized(data, (x_0,y_0)) 1 loop, best of 3: 5.62 s per loop 10 loops, best of 3: 20.7 ms per loop 100 loops, best of 3: 4.28 ms per loop In [399]: np.random.seed(0) ...: data = np.random.randint(0,1000,(500,500)) ...: x_0 = 500 ...: y_0 = 5…
has comment: http://stackoverflow.com/comment/86790313
answers question: http://stackoverflow.com/q/49886504
has comment: http://stackoverflow.com/comment/86790616
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49886504
type: AcceptedAnswer
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/86792014
downvote count: 0

http://stackoverflow.com/q/49852022
has answer: http://stackoverflow.com/a/49853998
has body: I have a unsorted list of number with even and odd. I need to segregate odd and even numbers in sorted order. For example: List = [5,6,4,7,11,14,12,1,3] Expected output : [4,6,12,14,1,3,5,7,11] My program to segregate the odd and even numbers. L = [5,6,4,7,11,14,12,1,3] def segregateEvenOdd(L): left,right = 0,len(L)-1 while left &lt; right: while (L[left]%2==0 and left &lt; right): left += 1 while (L[right]%2 == 1 and left &lt; right): right -= 1 if (left &lt; right): L[left],L[right] = L[right],L[left] left += 1 right = right-1 print segregateEvenOdd(L) output : [12, 6, 4, 14, 11, 7, 5, 1, 3] I am trying to sort the list using insertion sort, couldn't get right output. Any way to sort this easily
has answer: http://stackoverflow.com/a/49852313
answer count: 12
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/49852174
has answer: http://stackoverflow.com/a/49852443
linked to: http://stackoverflow.com/q/993984
has answer: http://stackoverflow.com/a/60573948
tagged with: python
tagged with: sorting
has answer: http://stackoverflow.com/a/61327980
has answer: http://stackoverflow.com/a/49852139
has answer: http://stackoverflow.com/a/72594993
has answer: http://stackoverflow.com/a/49852153
type: AnsweredQuestion
has title: Sorting/grouping odd and even numbers in odd and even segregated list
has answer: http://stackoverflow.com/a/66997342
downvote count: 0
has comment: http://stackoverflow.com/comment/86718605
has answer: http://stackoverflow.com/a/49852181
accepted answer: http://stackoverflow.com/a/49852181
has answer: http://stackoverflow.com/a/69099089
possible better answer: http://stackoverflow.com/a/69099089
favorite count: 0
type: Question

http://stackoverflow.com/a/49889085
has body: The methods parameter values should be set in the route wrapper. Also, it is generally cleaner to check if the request is a POST first: @app.route('/', methods=['GET', 'POST']) def index(): if flask.request.method == 'POST': return 'POST' return render_template('index.html')
downvote count: 0
has comment: http://stackoverflow.com/comment/86794295
type: Answer
accepted answer of: http://stackoverflow.com/q/49889078
has comment: http://stackoverflow.com/comment/86794309
answers question: http://stackoverflow.com/q/49889078
type: AcceptedAnswer
score: 6
upvote count: 6

http://stackoverflow.com/q/49820088
has comment: http://stackoverflow.com/comment/86660679
has answer: http://stackoverflow.com/a/67067829
has body: I'm writing some integration tests for a web API I build using Django Rest Framework and Django 1.11. My tests are passing when I use DRF's APIClient to send requests to my API endpoints, but when I use the CoreAPIClient the request throws an exception and returns an internal server error. However if I use Postman, or even the coreapi-cli commands it works without a problem. my test code: this works: from rest_framework.test import APITestCase, APIClient self.client = APIClient() account_params = { 'email': 'test1@example.com', 'username': 'testuser1', 'password': 'test1password' } account_response = self.client.post(reverse('account-list'), data=account_params) but using the core api client does not work: from rest_framework.test import APITestCase, CoreAPIClient self.client = CoreAPIClient() self.schema = self.client.get('http://localhost/api/schema') params = { 'email': 'test3@example.com', 'username': 'testuser3', 'password': 'test3password' } self.test_user = self.client.action(self.schema, ['accounts', 'create'], params=params) here is the exception I get: Error Traceback (most recent call last): File "/home/pitt/dev/cps/cps_mono/surveys/tests.py", line 429, in setUp self.test_user = self.client.action(self.schema, ['accounts', 'create'], params=params) File "/home/pitt/.virtualenvs/cps_mono/lib/python3.5/site-packages/coreapi/client.py", line 178, in action return transport.transition(link, self.decoders, params=params, link_ancestors=link_ancestors) File "/home/pitt/.virtualenvs/cps_mono/lib/python3.5/site-packages/coreapi/transports/http.py", line 386, in transition raise exceptions.ErrorMessage(result) coreapi.exceptions.ErrorMessage: <Error: 500 Internal Server Error> message: " Server Error (500) " I switched on the DEBUG_PROPAGATE_EXCEPTIONS flag and the exception throw is now in more detail: Error Traceback (most recent call last): File "/home/pitt/.virtualenvs/cps_mono/lib/python3.5/site-packages/django/db/backends/base/base.py", line 231, in _cursor …
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/126815707
has title: DRF + CoreAPIClient + psycopg2 throws exception, Interface error: connection already closed
has answer: http://stackoverflow.com/a/70524610
type: Question
has comment: http://stackoverflow.com/comment/86666090
answer count: 2
tagged with: django
tagged with: python
type: UnansweredQuestion
tagged with: django-rest-framework
tagged with: psycopg2
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/86662167
has comment: http://stackoverflow.com/comment/86658280
tagged with: core-api

http://stackoverflow.com/a/50119764
type: Answer
answers question: http://stackoverflow.com/q/49864214
score: 0
has body: An intuitive explanation for dropout efficiency might as follows. Imagine that you have a team of workers and the overall goal is to learn how to erect a building. When each of the workers is overly specialized, if one gets sick or makes a mistake, the whole building will be severely affected. The solution proposed by “dropout” technique is to pick randomly every week some of the workers and send them to business trip. The hope is that the team overall still learns how to build the building and thus would be more resilient to noise or workers being on vacation. Because of its simplicity and effectiveness, dropout is used today in various architectures, usually immediately after fully connected layers. Generalization in machine learning refers to how well the concepts learned by the model apply to examples which were not seen during training. The goal of most machine learning models is to generalize well from the training data, in order to make good predictions in the future for unseen data. Overfitting happens when the models learns too well the details and the noise from training data, but it doesn’t generalize well, so the performance is poor for testing data. It is a very common problem when the dataset is too small compared with the number of model parameters that need to be learned. This problem is particularly acute in deep neural networks where is not uncommon to have millions of parameters. Here is visual explanation i found : More info here.

http://stackoverflow.com/a/62044497
downvote count: 0
upvote count: 1
score: 1
has body: I was having same problem. We have to first upload the file on the server and then access it. It worked!!
type: Answer
answers question: http://stackoverflow.com/q/49792619

http://stackoverflow.com/q/49847376
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: Need your advise on avoiding 403 on private Isntagram APi usage. Ive reused one of the isntagram scraper codes on web. Ive done couple tries and even with headers and cookies all looks next. There is not issue with getting info stragiht from post url and extracting it. Though, post comment span across several pages and to switch to a next one i need to become authenticated. This is just a first step to test authentication. from botocore.vendored import requests import urllib.parse import hashlib import json def lambda_handler(event, context): CHROME_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' def getSession(rhx_gis, csrf_token, variables): """ Get session preconfigured with required headers & cookies. """ #"rhx_gis:csfr_token:user_agent:variables" print(variables) values = "%s:%s:%s:%s" % ( rhx_gis, csrf_token, CHROME_UA, variables) x_instagram_gis = hashlib.md5(values.encode()).hexdigest() session = requests.Session() session.headers = { 'user-agent': CHROME_UA, 'x-instagram-gis': x_instagram_gis } print(x_instagram_gis) session.cookies.set('ig_pr', '2') session.cookies.set('csrftoken', csrf_token) return session def runX(): session = requests.Session() session.headers = { 'user-agent': CHROME_UA } response = session.get("https://www.instagram.com/selenagomez") data = json.loads(response.text.split("window._sharedData = ")[1].split("; ")[0]) csrf = data['config']['csrf_token'] rhx_gis = data['rhx_gis'] variables = '{"id":"460563723","first":10,"after":"AQBf8puhlt8nU2JzmYdMMTuH0FbMgUM1fnIOZIH7n94DM4VLWkVILUAKVB-5dqvxQEI-Wd0ttlEDzimaaqwC98jccQaDQT4tSF56c_NlWi_shg"}' session = getSession(rhx_gis, csrf, variables) query_hash = '33ba35852cb50da46f5b5e889df7d159' encoded_vars = urllib.parse.quote(variables, safe='"') url = 'https://www.instagram.com/graphql/query/?query_hash=%s&variables=%s' % (query_hash, encoded_vars) print(url) opp = session.get(url) print(opp.status_code) runX(); UPD…
score: 2
tagged with: instagram-api
has title: Instagram private API 403 even with cookies and headers
answer count: 3
has answer: http://stackoverflow.com/a/49859114
downvote count: 0
has answer: http://stackoverflow.com/a/49984139
has answer: http://stackoverflow.com/a/49848871
tagged with: python-requests

http://stackoverflow.com/comment/86828027
type: Comment
type: QuestionComment
has text: Provide more details like expected output and your inputs
score: 0
comment on: http://stackoverflow.com/q/49906062

mixed
tag name: mixed
tags question: http://stackoverflow.com/q/49829732
type: Tag

http://stackoverflow.com/comment/86776510
has text: @nekomatic That was the first solution came to my mind. But when I import tensorflow, this error happened: ImportError: /lib64/libm.so.6: version `GLIBC_2.23' not found (required by /home/sky8/miniconda3/envs/cal/lib/python3.6/site-packages/tensorflow/python/_pywrap_tensorflow_internal.so) . I asked system manager, and he said :This looks like you have conflicting glibc version requirements across your libraries. This is generally caused by trying to combine the module software from the system software.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49870115

calibration
tag name: calibration
type: Tag
tags question: http://stackoverflow.com/q/49776930

http://stackoverflow.com/comment/86820760
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49901868
has text: you could use the mousePressEvent signal from a QTextEdit?
type: Comment

http://stackoverflow.com/a/49868505
has comment: http://stackoverflow.com/comment/86753737
upvote count: 6
has body: The name attribute is a string; trying to access it in the with statement makes it the managed resource (and str has no concept of context management). You need to manage the NamedTemporaryFile itself, and access the name as needed: with NamedTemporaryFile(suffix='.shp') as tmp_shp: df.to_file(tmp_shp.name) # Access .name here, assuming you need a str If to_file accepts file-like objects (I can't find docs for such a method), you'd avoid using .name at all (in either line). Update: Because you're on Windows, you can't actually open a file opened by NamedTemporaryFile with delete=True (the default) until the NamedTemporaryFile is closed (which means you can't use any data written to that file handle, since it's deleted, and introduces a race condition even if using it solely to generate a unique name; the file is deleted at that point, so you're really just creating a new file, but someone else might race you to creating that file later). Best I can suggest here is to using it without deletion support to get a unique name, wrapping it to force deletion yourself, e.g.: tmp_shp = None try: with NamedTemporaryFile(suffix='.shp', delete=False) as tmp_shp: df.to_file(tmp_shp.name) # Access .name here, assuming you need a str ... do any other stuff with the file ... finally: if tmp_shp is not None: os.remove(tmp_shp.name) Yeah, it's ugly. There aren't a lot of good options here; NamedTemporaryFile is fundamentally broken on Windows.
answers question: http://stackoverflow.com/q/49868470
type: AcceptedAnswer
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/86753893
accepted answer of: http://stackoverflow.com/q/49868470
has comment: http://stackoverflow.com/comment/86752853
has comment: http://stackoverflow.com/comment/86754162
has comment: http://stackoverflow.com/comment/86752987
type: Answer

http://stackoverflow.com/comment/86820088
type: Comment
comment on: http://stackoverflow.com/a/49899553
type: AnswerComment
has text: You are right, but still you have to use dot, right?
score: 0

http://stackoverflow.com/comment/86836009
has text: This is getting confusing, your title is grossly misleading: you **don't pass any parameters whatsoever to `logist = LogisticRegression()`**. You pass `random_state=True` to `train_test_split()`. So LogisticRegression's defaults to random_state=None, which the doc tells you it uses some random number from the random-number generator. `train_test_split()` and `LogisticRegression()` do not somehow silently share parameters with each other. Seriously please read the doc on both and understand what the code is actually doing, then revise your question.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49909153
type: QuestionComment

http://stackoverflow.com/q/49797674
linked to: http://stackoverflow.com/q/30161700
has comment: http://stackoverflow.com/comment/86620627
tagged with: amazon-s3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86610158
tagged with: python
has comment: http://stackoverflow.com/comment/86631533
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/98446387
has answer: http://stackoverflow.com/a/62883419
downvote count: 0
has comment: http://stackoverflow.com/comment/86683123
has title: AWS S3 Download and Upload using TemporaryFile
has comment: http://stackoverflow.com/comment/86610504
answer count: 1
tagged with: amazon-web-services
has body: I need to download all content (including versions) of an Amazon S3 Bucket and upload in other Amazon S3 Bucket. Don't tell me to use aws, I just can't use. I use tempfile.TemporaryFile for this, it apparently works, the print show that the file object has the right content inside, but the uploaded files are empty (zero bytes). with tempfile.TemporaryFile() as data: sourceUser.download_fileobj('source-bucket',key,data) # next 2 lines was just to check the content of the file data.seek(0) print (data.read()) destinationUser.upload_fileobj(data,'destination-bucket',key)
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/86671070
has text: You are missing the `enctype="multipart/form-data"` on your form, so no files will get sent to the view.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49826244

http://stackoverflow.com/q/49783142
answer count: 1
type: Question
tagged with: inkscape
has body: I know about: node.get("wight") or: node.attrib("wight") But for elements that don't have their attibute, like g element. How can I get the width?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/50082553
score: 0
has title: Inkscape extension, how to get a g element width and height?

http://stackoverflow.com/q/49801353
has answer: http://stackoverflow.com/a/49826999
score: 0
tagged with: tkinter
tagged with: optionmenu
answer count: 1
has title: add option to python tkinter optionmenu and execute a function when selected
has body: Here is a much simplified version of what I was trying to do. import Tkinter as tk root = tk.Tk() n = 1 def show1(): print var.get() def add1(): global n l = 'Option %d' % n n += 1 op['menu'].add_command(label=l,command=tk._setit(var,l)) var.set(l) print 'added %s' % l var = tk.StringVar() op = tk.OptionMenu(root,var,[], command=show1) op.pack() tk.Button(root,text='add 1', command=add1).pack() tk.Button(root,text='show', command=show1).pack() root.mainloop() The 'add 1' button successfully adds options to the option menu. Clicking on an option does not call the show1 routine, you have to click on the 'show' button. -------Original Question----- I'm trying to read in a number of selected files and save information about each of them. As I read them in the file base name is stored in the option list. That seems to be working. I would like to show the saved information when I click on a selection in the option menu. That is not working. The code below is adding name to the option list, but you have to click the 'Get it' button to show the data. #!/usr/bin/python2.7 import Tkinter as tk import os,sys import tkFileDialog as tkfd class E(tk.Frame): def __init__(self): tk.Frame.__init__(self) self.grid() self.files = {} self.statusMsg = tk.StringVar() self.nLines = tk.StringVar() self.maxLine = tk.StringVar() self.fileName = tk.StringVar() tk.Button(self,text='Get a file',command=self.openfile, bd=5).grid(row=1, column=0) self.fileOption = tk.OptionMenu(self,self.fileName, [], command=self.getIt) self.fileOption.configure(width=10, bd=5, relief='ridge') self.fileOption.grid(row=2, column=0) tk.Label(self,text='Line Count').grid(row=3, column=0) tk.Label(self,textvariable=self.nLines).grid(row=3, column = 1) tk.Label(self,text='Max Line').grid(row=4, column=0) tk.Label(self,textvariable=self.maxLine).grid(row=4, column = 1) tk.Button(self,text='show file',command=self.getIt, bd=5).grid(row=5) tk.Label(self,text='Status').grid(row=6, column=0) tk.Label(self,textvariable=sel…
type: Question
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/49876066
has body: I finally figured it out. I have divided process into multiple parts. I then make AJAX call to access it. My urls.py file: from django.conf.urls import url from .views import tag, check_tagid, scan_tag urlpatterns = [ url(r'^tag/', tag, name="tag"), url(r'^check_tagid/', check_tagid, name="check_tagid"), url(r'^scan_tag/', scan_tag, name="scan_tag"), ] My views.py file: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import Student import serial def check_tagid(request): """Check if scanned tag id is already associated or not""" tagid = request.GET.get('tagid', None) if Student.objects.filter(tag_id__iexact=tagid).exists(): data = { 'is_taken': Student.objects.filter(tag_id__iexact=tagid).exists(), 'student': Student.objects.get(tag_id=tagid).name } else: data = { 'is_taken': Student.objects.filter(tag_id__iexact=tagid).exists(), } return JsonResponse(data) def scan_tag(request): """Function to check if tag is scanned or not""" if request.is_ajax(): ## Init RFID reader data = serial.Serial( port='/dev/ttyUSB1', baudrate = 9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS ) context = {'tagid': data.read(12).decode("utf-8")} return JsonResponse(context) else: return HttpResponse("This route only handles AJAX requests") def tag(request): return render(request, 'students/tag.html', {}) my tag.html file: Scanning for tag All of this is now working as expected. So, /tag/ is the main entry point. Now in tag.html I use jQuery get method on /scan_tag/. It will return RFID tag number. Then I call AJAX on /check_tagid/ and it will true/false depending on whether the student is in the database or not.
answers question: http://stackoverflow.com/q/49840767
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/86778685
has comment: http://stackoverflow.com/comment/86772102
score: 1
type: AcceptedAnswer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49840767

http://stackoverflow.com/comment/86569906
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49777274
has text: Please format your data so it is readable.

http://stackoverflow.com/comment/86618796
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49801208
has text: I was just counting the matrices which have a 1 in the upper left hand corner -- 1 out of 11 have this property. It was a random test -- I just wanted to do *something* with each matrix produced.
type: Comment

http://stackoverflow.com/comment/86788481
comment on: http://stackoverflow.com/a/49885898
score: 0
type: Comment
type: AnswerComment
has text: That's an algebraic derivation, not Python code. Use the second line only.

http://stackoverflow.com/a/49903761
has body: import csv import glob dest_fname = "C:\\Users\\gomathis\\Downloads\\To csv\\FinalTR.csv" src_fnames = glob.glob("C:\\Users\\gomathis\\Downloads\\To csv\\*.csv") with open(dest_fname, 'w', newline='') as f_out: writer = csv.writer(fout) copy_headers = True for src_fname in src_fnames: # don't want to overwrite destination file if src_fname.endswith('FinalTR.csv'): continue with open(src_fname, 'r', newline='') as f_in: reader = csv.reader(f_in) # header row is copied from first csv and skipped on the rest if copy_headers: copy_headers = False else: next(reader) # skip header for row in reader: writer.writerow(row) Notes: Placed your open() in with-statements for automatic closing of files. Removed the binary flag from file modes and added newline='' which is needed for files passed to csv.reader and csv.writer in Python 3. Changed from csv.writer to csv.reader for the files you were reading from. Added a copy_headers flag to enable copying headers from the first file and skipping copying of headers from any files after that. Check source filename and skip it when it matches the destination filename.
answers question: http://stackoverflow.com/q/49899165
type: Answer
has comment: http://stackoverflow.com/comment/86824134
has comment: http://stackoverflow.com/comment/86823746
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/86823800
has comment: http://stackoverflow.com/comment/86823887
accepted answer of: http://stackoverflow.com/q/49899165

http://stackoverflow.com/q/49814774
tagged with: python
has comment: http://stackoverflow.com/comment/92222427
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: execve
tagged with: subprocess
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has title: execveat(2) / fexecve(3) like behavior with Python’s subprocess
has answer: http://stackoverflow.com/a/52645610
accepted answer: http://stackoverflow.com/a/52645610
has body: How can I get Python’s subprocess module to accept an fd instead of a path (== execveat() with AT_EMPTY_PATH)? Example: subprocess.Popen (["argv0", "argv1"], shell=False, executable=os.open ("/proc/self/exe", os.O_RDONLY | os.O_CLOEXEC)) With Python 3.6.5 this fails on account of TypeError. The goal is, of course, avoiding the TOCTTOU between validating the binary and the call to execve(2). I’m aware that os.execve() can be used with fds too but I’d prefer not to reimplement the subprocess module on top of that.
has comment: http://stackoverflow.com/comment/91831575
has comment: http://stackoverflow.com/comment/92088657

http://stackoverflow.com/a/49910660
answers question: http://stackoverflow.com/q/49910606
has body: Suppose you have an array arr = [1,2,3,4,5,6], and m=3. If you can break it up into divisible chunks, then: back_m_iter = zip(*([iter(reversed(arr))]*m)) Gives you an array grouped by m elements from the back. If you want the list, simply: back_m_list = list(back_m_iter) output: [(6,5,4),(3,2,1)] If you want to fill the empty spots with None's for nondivisible arrays(say arr is extended by 1): from itertools import zip_longest back_m_iter = zip_longest(*([iter(reversed(arr))]*m), fillvalue=None) output: [(7,6,5),(4,3,2),(1,None,None)] You can replace None with 0's if you wanted the rest to be 0's. EDIT: Just saw your comment, here's a revision (misunderstood your question): back_m_list = [x[::-1] for x in back_m_iter] output: [(4,5,6),(1,2,3)] You can also do: back_m_iter = reversed(list(zip(*([iter(arr)]*m)))) output: [(4,5,6),(1,2,3)]
upvote count: 2
downvote count: 0
score: 2
type: Answer

http://stackoverflow.com/a/49890879
score: 0
has comment: http://stackoverflow.com/comment/86797465
answers question: http://stackoverflow.com/q/49890750
has comment: http://stackoverflow.com/comment/86797543
has body: import pandas as pd atlantic = pd.read_csv('atlantic.csv', sep=',') data = atlantic.to_xarray() xr.open_dataset(data)
has comment: http://stackoverflow.com/comment/86797423
has comment: http://stackoverflow.com/comment/86797763
has comment: http://stackoverflow.com/comment/86797500
type: Answer

http://stackoverflow.com/q/49771560
score: 0
has comment: http://stackoverflow.com/comment/86558061
has comment: http://stackoverflow.com/comment/86558577
has comment: http://stackoverflow.com/comment/86558350
type: Question
has comment: http://stackoverflow.com/comment/86558287
answer count: 0
has comment: http://stackoverflow.com/comment/86559476
has comment: http://stackoverflow.com/comment/86558231
type: UnansweredQuestion
has title: How to use functions of library in python?
tagged with: python
tagged with: information-gain
has body: I want to use function which calculates conditional mutual information in python. I found a library 'mdentropy' implementing it. But when I tried to see the list of functions of mdentropy library by using command dir(mdentropy) it showed: ['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__'] I opened the folder of mdenetropy but I am not able to see any python file having such functions there. I downloaded the library from here: https://pypi.python.org/pypi/mdentropy My question basically is: How can I use the function to calculate Conditional Mutual Information from this library? Is there any other resource from where I can calculate this function?

http://stackoverflow.com/q/49859127
has answer: http://stackoverflow.com/a/49859621
score: 3
has answer: http://stackoverflow.com/a/49859269
has answer: http://stackoverflow.com/a/49859255
possible better answer: http://stackoverflow.com/a/49859255
accepted answer: http://stackoverflow.com/a/49859269
tagged with: pivot-table
tagged with: dataframe
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/49859323
type: AnsweredQuestion
tagged with: pandas
upvote count: 3
downvote count: 0
has body: I have score data, and I want to group by customised score bining. Id Date Score 1 2018-01-01 56 2 2018-01-01 72 3 2018-01-01 91 4 2018-01-01 67 5 2018-01-01 65 6 2018-01-02 75 7 2018-01-02 72 8 2018-01-02 91 9 2018-01-02 82 10 2018-01-02 81 Here's what I expected Date &lt;60 60-79 80-100 2018-01-01 1 3 1 2018-01-02 0 2 3 What I did is result = pd.crosstab(df.Date, df.Score) result['&lt;60'] = result['1']+ ... + result['59'] result['60-79'] = result['60']+ ... + result['79'] result['80-100'] = result['80']+ ... + result['100'] and then I should drop a lot of columns Any better way to do this?
has title: How to bucketing a score list and grouping by date in pandas dataframe effectively
favorite count: 0
type: Question

http://stackoverflow.com/q/49867770
possible better answer: http://stackoverflow.com/a/49868058
tagged with: python
has title: How to make a new column for a date index
accepted answer: http://stackoverflow.com/a/49868440
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49868440
has answer: http://stackoverflow.com/a/49868058
type: Question
score: 0
has body: I want to make a new column for a date index . Here's my dataset score &lt;80 80-100 data 2018-01-01 3 5 2018-01-02 6 3 Here's the characteristic In [150] df.columns Out[150] CategoricalIndex(['&lt;80', '80-100'], categories=['&lt;80', '80-100'], ordered=True, name='final_score', dtype='category') and In [151] df.index Out[151] Index([2018-01-01, 2018-01-02], dtype='object', name='date') I want to convert index to a column like, what I've try is df['date'] = df.index But, it doesn't work
tagged with: pandas

http://stackoverflow.com/a/49846427
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49840576
has body: The simplest thing is to use a pyspark.sql.Window and select: import pyspark.sql.functions as f from pyspark.sql import Window w = Window.partitionBy('user') df = df.select('user', f.count('somecol').over(w).alias('count')) df.show() #+-----+-------+ #|user| count | #+----+-------+ #| 6| 2| #| 9| 2| #| 6| 2| #| 12| 1| #| 9| 2| #+----+-------+ We define the Window w to partition by (group by) the user column. Then we calculate the count over this window.
downvote count: 0

django-forms
tags question: http://stackoverflow.com/q/49859441
tags question: http://stackoverflow.com/q/49842383
tags question: http://stackoverflow.com/q/49903386
tags question: http://stackoverflow.com/q/49867966
tags question: http://stackoverflow.com/q/49778708
tags question: http://stackoverflow.com/q/49905484
tags question: http://stackoverflow.com/q/49913996
tags question: http://stackoverflow.com/q/49809879
tags question: http://stackoverflow.com/q/49848267
tag name: django-forms
type: Tag
tags question: http://stackoverflow.com/q/49782992
tags question: http://stackoverflow.com/q/49820946
tags question: http://stackoverflow.com/q/49776144
tags question: http://stackoverflow.com/q/49778993
tags question: http://stackoverflow.com/q/49772087

pca
tag name: pca
tags question: http://stackoverflow.com/q/49885007
type: Tag

http://stackoverflow.com/comment/86695235
type: Comment
has text: Have you tried to use the csv `sniffer` ?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49832053

http://stackoverflow.com/comment/86824752
comment on: http://stackoverflow.com/q/49777020
type: Comment
type: QuestionComment
has text: Would you mind [opening an issue](https://github.com/tensorflow/tensorflow/issues/new)? I believe this is something we'd like to support.
score: 0

http://stackoverflow.com/q/49842873
accepted answer: http://stackoverflow.com/a/49849527
downvote count: 1
score: -1
has body: I am trying to connect to my mongodb in mlab.com using flask but when I run my flask script I am getting Authentication failed error, please help. my code: from flask import Flask, jsonify, request from flask_pymongo import PyMongo app = Flask(__name__) app.config['MONGO_DBNAME'] = 'mydb' app.config['MONGO_URI'] = 'mongodb://user:pwd@ds157799.mlab.com:57799/mydb' mongo = PyMongo(app) @app.route('/framework', methods=['GET']) def get_all_frameworks(): framework = mongo.db.framework output = [] for q in framework.find(): output.append({'name' : q['name'], 'language' : q['language']}) return jsonify({'result' : output}) Error: File "mongo.py", line 12, in &lt;module&gt; mongo = PyMongo(app) File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\flask_pymongo\__init__.py", line 97, in __init__ self.init_app(app, config_prefix) File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\flask_pymongo\__init__.py", line 283, in init_app mechanism=auth_mechanism) File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\database.py", line 1167, in authenticate connect=True) File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\mongo_client.py", line 588, in _cache_credentials sock_info.authenticate(credentials) File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\pool.py", line 620, in authenticate auth.authenticate(credentials, self) File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\auth.py", line 486, in authenticate auth_func(credentials, sock_info) File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\auth.py", line 237, in _authenticate_scram_sha1 res = sock_info.command(source, cmd) File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\pool.py", line 517, in command collation=collation) File "C:\Users\ELCOT\AppData\Local\Programs\Python\…
favorite count: 0
has answer: http://stackoverflow.com/a/49844985
type: Question
has answer: http://stackoverflow.com/a/49849527
tagged with: mongodb
has answer: http://stackoverflow.com/a/54242955
upvote count: 0
tagged with: mlab
tagged with: python
tagged with: flask
linked to: http://stackoverflow.com/q/49843914
type: AnsweredQuestion
answer count: 3
has title: authendication failed when connecting to mongodb in mlab
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/49844985

http://stackoverflow.com/comment/86632432
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49808801
has text: What, precisely, is your question?
score: 0

http://stackoverflow.com/q/49844360
has answer: http://stackoverflow.com/a/51335490
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/86703930
has comment: http://stackoverflow.com/comment/86704247
has comment: http://stackoverflow.com/comment/86703502
has title: Keras(FIT_GENERATOR)- Error, when checking target: expected activation_1 to have 3 dimensions, but got array with shape (32, 416, 608, 3)
linked to: http://stackoverflow.com/q/46493419
tagged with: python
has body: I've been working on a segmentation problem for many days and after finally finding out how to properly read the dataset, I ran into this problem: ValueError: Error when checking target: expected activation_1(Softmax) to have 3 dimensions, but got array with shape (32, 416, 608, 3) I used the functional API, since I took the FCNN architecture from [here](https://github.com/divamgupta/image-segmentation-keras/blob/master/Models/FCN32.py). It is slightly modified and adapted in accordance with my task(IMAGE_ORDERING = "channels_last"(TensorFlow backend)). Can anyone please help me? Massive thanks in advance. The architecture below is for FCNN, which I try to implement for the purpose of the segmentation. Here is the architecture(after calling model.summary()): 1. 2. The specific error is: "Importing the dataset" function: "Fit_Generator method calling": img_input = Input(shape=(input_height,input_width,3)) #Block 1 x = Convolution2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1', data_format=IMAGE_ORDERING)(img_input) x = BatchNormalization()(x) x = Convolution2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2', data_format=IMAGE_ORDERING)(x) x = BatchNormalization()(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool', data_format=IMAGE_ORDERING)(x) f1 = x # Block 2 x = Convolution2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1', data_format=IMAGE_ORDERING)(x) x = BatchNormalization()(x) x = Convolution2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2', data_format=IMAGE_ORDERING)(x) x = BatchNormalization()(x) x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool', data_format=IMAGE_ORDERING )(x) f2 = x # Block 3 x = Convolution2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1', data_format=IMAGE_ORDERING)(x) x = BatchNormalization()(x) x = Convolution2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2', data_format=IMAGE_ORDERING)(x) …
has answer: http://stackoverflow.com/a/49884446
has comment: http://stackoverflow.com/comment/86714962
type: Question
accepted answer: http://stackoverflow.com/a/49877645
has comment: http://stackoverflow.com/comment/86706622
has comment: http://stackoverflow.com/comment/86706608
has comment: http://stackoverflow.com/comment/86703473
tagged with: keras-layer
answer count: 3
has comment: http://stackoverflow.com/comment/86703512
downvote count: 0
has comment: http://stackoverflow.com/comment/86704319
tagged with: keras
possible better answer: http://stackoverflow.com/a/49884446
favorite count: 0
has comment: http://stackoverflow.com/comment/86703775
has answer: http://stackoverflow.com/a/49877645

http://stackoverflow.com/a/49824328
has body: You had Renb as a symbol, but then assigned a value to it. This means you lost that symbol, you don't have a handle on it anymore. Use a different Python variable to hold any numerical value related to that symbol, like Renb_sol below. Also, substitution of numerical values can be done later, after the solution is obtained. This allows you to use the same equation solving for different variables in it. Eq_uvlo = Eq(Rent/Renb, (Vuvlo/1.274) -1) Renb_sol = solve(Eq_uvlo, Renb)[0].subs({Rent: 47e3, Vuvlo: 8}) print(Renb_sol) Vuvlo_sol = solve(Eq_uvlo, Vuvlo)[0].subs({Rent: 47e3, Renb: 9100}) print(Vuvlo_sol) prints 8902.46803449301 7.85400000000000
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49814487
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49814487

http://stackoverflow.com/comment/86802661
type: QuestionComment
has text: @Kasramvd Please close it back again, the answer is there, in https://stackoverflow.com/a/5844618/3832970. It works in both Python 2 and 3.
score: 0
comment on: http://stackoverflow.com/q/49892621
type: Comment

http://stackoverflow.com/comment/86832706
comment on: http://stackoverflow.com/q/49908354
type: Comment
has text: `if value<0: continue`
score: 4
type: QuestionComment

http://stackoverflow.com/a/49767957
accepted answer of: http://stackoverflow.com/q/49767631
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49767631
type: Answer
has body: If I've understand correctly, you have a data of second or minute wise and you want to compute the average for day. First of all you have to combine the creationdateTime time column day wise which can be done with Grouper functionality and then you can use the mean function so that it will get you the mean in 3rd column for every entry on that day. daywisedf = df.groupby(pd.Grouper(key='creationdateTime',freq='1d')).mean() This will get average of each day in 3rd column itself. Note: Your creationdateTime should be in datetime format in order to use Grouper. For more info visit Pandas docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Grouper.html
score: 0

http://stackoverflow.com/a/49831405
upvote count: 1
has body: The remove_member method is wrong for several reasons. The line del unique_id will not remove the value from all_users, which is just a list of Team Members. And you shouldn't have to ask the user for all of this information - just the ID (or the name) would be enough. What I suggest is: @staticmethod def remove_member(): print() print("We're sorry to see you go , please fill out the following information to continue") print() unique_id = input("what is your User ID?\n") unique_id = int(unique_id) for i, user in enumerate(all_users): if user.user_id == unique_id: all_users.remove(i) break
has comment: http://stackoverflow.com/comment/86683589
has comment: http://stackoverflow.com/comment/86687190
answers question: http://stackoverflow.com/q/49831310
type: Answer
score: 1
downvote count: 0

amazon-athena
type: Tag
tag name: amazon-athena
tags question: http://stackoverflow.com/q/49855087

graphviz
tags question: http://stackoverflow.com/q/49875342
tag name: graphviz
type: Tag
tags question: http://stackoverflow.com/q/49853303

http://stackoverflow.com/a/49900540
answers question: http://stackoverflow.com/q/49898899
type: Answer
downvote count: 0
has body: def combine_list(*args): return map(list, args) final = list(combine_list(a,b,c)) It will be like: [['a', 'b', 'c'], [1, 2, 3], ['red', 'green', 'blue']]
score: 1
upvote count: 1

http://stackoverflow.com/a/49791775
has body: You need to create a boolean array and you can select what you want: X = X[ind_delete!=1] Selects the positions for where the value is not 1.
score: 0
answers question: http://stackoverflow.com/q/49791681
type: Answer

http://stackoverflow.com/comment/86590390
score: 1
has text: Could be argued to be more general, _"Is there any way to mention the axis?"_
type: QuestionComment
comment on: http://stackoverflow.com/q/49787422
type: Comment

http://stackoverflow.com/comment/87677957
comment on: http://stackoverflow.com/a/50330634
has text: This is likely not the actual answer.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/a/49781348
has body: Rather than guessing what format the data is in, you should find out. If you're generating it yourself, and don't know how to parse back in what you're creating, change your code to generate something that can be easily parsed with the same library used to generate it, like JsonLines or CSV. If you're ingesting it from some API, read the documentation for that API and parse it the way it's documented. If someone handed you the file and told you to parse it, ask that someone what format it's in. Occasionally, you do have to deal with some crufty old file in some format that was never documented and nobody remembers what it was. In that case, you do have to reverse engineer it. But what you want to do then is guess at likely possibilities, and try to parse it with as much validation and error handling as possible, to verify that you guessed right. In this case, the format looks a lot like either JSON lines or ndjson. Both are slightly different ways of encoding multiple objects with one JSON text per line, with specific restrictions on those texts and the way they're encoded and the whitespace between them. So, while a quick&amp;dirty parser like this will probably work: with open('tweets.txt') as f: for line in f: tweet = json.loads(line) dosomething(tweet) You probably want to use a library like jsonlines: with jsonlines.open('tweets.txt') as f: for tweet in f: dosomething(tweet) The fact that the quick&amp;dirty parser works on JSON lines is, of course, part of the point of that format—but if you don't actually know whether you have JSON lines or not, you're better off making sure.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49780991
upvote count: 1
type: Answer

http://stackoverflow.com/comment/86819904
has text: @chrisz untrue, I have similar list comprehensions elsewhere in my code
comment on: http://stackoverflow.com/q/49902214
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49788637
score: 0
type: Answer
has body: So, assume you can use sort. Sort two lists first, then do with two pointers, move one pointer with smaller value forward each time. For union func, add all values each time and move forward both pointers when their values are equal. For intersection func, only add values when the values are equal. Time O(nlogn+n)->O(nlogn)
answers question: http://stackoverflow.com/q/49788464

http://stackoverflow.com/q/49792148
answer count: 3
upvote count: 1
has title: For loop and open statements
downvote count: 1
tagged with: loops
has comment: http://stackoverflow.com/comment/86598846
tagged with: iteration
favorite count: 0
has answer: http://stackoverflow.com/a/49792254
type: Question
has answer: http://stackoverflow.com/a/49792307
has answer: http://stackoverflow.com/a/49792299
tagged with: file-io
has body: I understand why the first for loop works; that loop is essentially looping through a list, as per the readlines() method. The second for loop doesn't make sense to me. The loop is opening the file, but since the default for an open statement is read, shouldn't the output be the whole file in one big string upon each iteration, instead of a single line? Here's the code: #The two for loops do the same thing: for line in open('test.txt').readlines(): print(line.rstrip()) for line in open('test.txt'): # Use iterators: best for text input print(line.rstrip())
tagged with: python
accepted answer: http://stackoverflow.com/a/49792254
possible better answer: http://stackoverflow.com/a/49792299
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/86631535
type: Comment
type: QuestionComment
has text: The code of your pastebin working for me.
score: 0
comment on: http://stackoverflow.com/q/49808108

http://stackoverflow.com/comment/86755647
score: 0
has text: Which path is not valid? When I run the command /anaconda3/bin/python3.6 /Users/user/application/test.py in the terminal, I get the output I want. It only does not work when I run the php script.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49869649

http://stackoverflow.com/comment/86773115
comment on: http://stackoverflow.com/q/49878711
has text: i did it say auth_goup table not exists... also i delete all migrations still have the error
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86696279
comment on: http://stackoverflow.com/q/49839270
type: Comment
type: QuestionComment
score: 0
has text: you may want to read [this article](https://cloud.google.com/ml-engine/docs/scikit/quickstart)

http://stackoverflow.com/comment/86578246
type: Comment
has text: @krishnab: The Jacobian will be calculated automatically – if the integrator can make use of it. The things you mention just exist for fine tuning. You usually do not need to bother about this.
type: AnswerComment
comment on: http://stackoverflow.com/a/49770275
score: 1

http://stackoverflow.com/q/49774179
type: Question
tagged with: numpy
type: UnansweredQuestion
tagged with: arrays
tagged with: bounding-box
tagged with: python
tagged with: label
score: 3
has title: Python: get boundingbox coordinates for each cluster in segmentation map (2D numpy array)
upvote count: 3
has answer: http://stackoverflow.com/a/49774684
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/86567139
has body: Python: I got a segmentation map (2D numpy array) with class values (integer 0 to N) for each pixel of the original img and i want to find the bounding box coordinates for each connected cluster in the segmentation map. EDIT: there might be more than one cluster per class in the map! I guess i can use something like skimage.measure.label(seg_map, connectivity=1)
favorite count: 0

http://stackoverflow.com/q/49804665
has body: I'm currently writing a simple blog application using Flask-Admin for administrative tasks. I'd like to enable CSRF protection and have followed the instructions on the Advanced Functionality page in the docs. However, this doesn't seem to prevent my dummy CSRF attacks from succeeding and it is unclear how Flask-Admin follows the CSRF protection implementation outlined in the WTForms documentation. Regarding my dummy CSRF attacks, my method follows the example for POST requests suggested in the OWASP CSRF article: &lt;body onload="document.forms[0].submit()"&gt; &lt;form action="http://localhost:5000/admin/blogpost/new?url=%2Fadmin%2Fblogpost%2F" method="POST"&gt; &lt;input type="hidden" name="title" value="Evil title"/&gt; &lt;input type="hidden" name="content" value="Evil content"/&gt; &lt;input type="submit" value="Save"/&gt; &lt;/form&gt; where the action address is the new post creation page that draws from the create.html template of Flask-Admin. When I load the malicious form from a separate origin (localhost:3000) and submit it on document load, I find that the request goes through despite the form being configured with the Flask-Admin SecureForm setup linked above. I've tried consulting the Flask-Admin source code, but couldn't find the WTForms csrf_token in the relevant templates, though the SecureForm includes the CSRF settings as expected. Does Flask-Admin diverge from the documented WTForms implementation of CSRF protection? If so, how? More practically speaking, is there any additional configuration beyond the use of Flask-Admin's SecureForm in my ModelView-based classes necessary to enable CSRF protection? Note also that the technique described in this answer also worked for me in my attempts to use exposed admin URLs cross-site (again from localhost:3000) to perform actions requiring authentication. This leads me to ask the follow-up: is it possible to implement CSRF on non-form Flask-Admin pages, i.e. for GET requests, to protect exposed admin URLs …
favorite count: 0
type: Question
answer count: 0
tagged with: flask-wtforms
type: UnansweredQuestion
tagged with: flask-admin
downvote count: 0
tagged with: csrf
tagged with: python
tagged with: flask
score: 3
upvote count: 3
has title: How does Flask-Admin SecureForm and CSRF protection work

http://stackoverflow.com/comment/86549939
has text: Hi my problem is only sequential and duplicating rows, remove the first one from the other @Aditya
comment on: http://stackoverflow.com/q/49767227
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/86550594
type: Comment
type: QuestionComment
has text: Currently uploading. @juan.arvillaga , we were required to put it into a csv file. I'll look into object serialization as well. Thank you!
comment on: http://stackoverflow.com/q/49767477
score: 0

ipv6
tag name: ipv6
tags question: http://stackoverflow.com/q/49817064
tags question: http://stackoverflow.com/q/49792539
type: Tag

http://stackoverflow.com/comment/136086071
has text: `TypeError: dtype timedelta64[ns] cannot be converted to datetime64[ns]`
type: Comment
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/49849072

http://stackoverflow.com/a/49875936
type: Answer
has body: As long as you really want to pass it all of the first 6 (0-5, inclusive) arguments, you can probably use tuple unpacking: p = Column(*fg[:6,]) show(p) Here a slightly more complete example using numpy arrays: import numpy as np def f(x0, x1): print(x0, x1) x = np.array([[0, 1], [2, 3], [4, 5]]) f(*x[:2,]) # [0 1] [2 3]
answers question: http://stackoverflow.com/q/49875898
score: 0

http://stackoverflow.com/q/49773957
has comment: http://stackoverflow.com/comment/86562836
score: 0
has comment: http://stackoverflow.com/comment/86563280
linked to: http://stackoverflow.com/q/2612802
has body: class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates.sort() res = [] # save the result path = [] # save each unique combination self.dfs(0, target, path, res, candidates) return res def dfs(self, start_index, target, path, res, candidates): if target == 0: res.append(path) return if target &lt; 0: path.pop() return for i in range(start_index, len(candidates)): if i &gt; start_index and candidates[i] == candidates[i-1]: continue path += [candidates[i]] self.dfs(i+1, target-candidates[i], path, res, candidates) if path: path.pop() The above code for LeetCode problem Combination Sum II, given the input [10,1,2,7,6,1,5] and 8, the output should be [[1,1,6],[1,2,5],[1,7],[2,6]]. However, the output of this piece of code run to be [[],[],[],[]], I'm very confusing and wondering why :(
has comment: http://stackoverflow.com/comment/86563529
answer count: 0
has title: Confusing about passing list in recursion function of python
has comment: http://stackoverflow.com/comment/86562857
type: Question
has comment: http://stackoverflow.com/comment/86563148
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/q/49830757
type: Question
has answer: http://stackoverflow.com/a/49831021
upvote count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/49833016
accepted answer: http://stackoverflow.com/a/49830912
tagged with: python
tagged with: dictionary
favorite count: 0
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has body: I am trying to write a nested dictionary into python. I have a dictionary like below: {'09-04-2018' : {1: 11, 2: 5, 3: 1, 4: 1, 5: 0} , '10-04-2018' : {1: 5, 2: 1, 3: 1, 4: 1, 5: 0}} and i wanted to write it something like: count,09-04-2018,10-04-2018 1,11,5 2,5,1 3,1,1 4,1,1 5,0,0
has answer: http://stackoverflow.com/a/49830912
has title: Writing a nested dictionary into csv python
possible better answer: http://stackoverflow.com/a/49831021

http://stackoverflow.com/comment/86569979
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49776137
has text: @Nipper your error message changed. That's good! It means you're making progress. It looks like you solved your original "not callable" problem. The issue now is that `minimize` will always pass `data` in as a `numpy` array, not as a pandas dataframe. You'll need to add a line to the start of `a` that will perform the array to dataframe conversion when it's needed.

django-2.0
tags question: http://stackoverflow.com/q/49827112
tags question: http://stackoverflow.com/q/49879828
tag name: django-2.0
tags question: http://stackoverflow.com/q/49904994
type: Tag

http://stackoverflow.com/a/49865220
accepted answer of: http://stackoverflow.com/q/49861305
type: Answer
has body: Add this field to Node: class FacultyNode(DjangoObjectType): departments = DjangoFilterConnectionField( DepartmentNode, # lambda: DepartmentNode (if Node is defined later) filterset_class=DepartmentFilter, )
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49861305

http://stackoverflow.com/comment/101011634
comment on: http://stackoverflow.com/a/49883466
type: Comment
score: 0
type: AnswerComment
has text: From my test code, it seems @lru_cache is faster compared to using my own dict for a cache, using cache.get(args, my_function(args) and storing cache[args] = my_res at the end. Why is that?

http://stackoverflow.com/q/49901193
has comment: http://stackoverflow.com/comment/86822018
has answer: http://stackoverflow.com/a/49909301
score: 0
tagged with: django-views
has comment: http://stackoverflow.com/comment/86818826
tagged with: django-models
tagged with: python
type: Question
answer count: 2
type: UnansweredQuestion
has body: urls.py path('preferences/<action>/<category>/', views.preferences), HTML form {% csrf_token %} {% for field in location_form %} {{ field.label_tag }} {{ field }} {% for error in field.errors %} {{ error }} {% endfor %} {% endfor %} Save Delete views.py elif action == 'delete': if category == 'location': # match form data to CLLocation's location field location_url = request.POST['location'] location_list = CLLocation._meta.get_field('location').choices for location in location_list: if location[0] == location_url: CLLocation.objects.get(location=location[1], user__username=request.user).delete() I am receiving a "matching query does not exist error." I know there is an object in the database with a matching "user" and "location" field, but I can't properly access and delete it! models.py class CLLocation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) location_choices = ( ('https://auburn.craigslist.org/', 'AL - auburn'), ... location = MultiSelectField(choices=location_choices)
has answer: http://stackoverflow.com/a/49901614
has comment: http://stackoverflow.com/comment/86818940
has title: Django matching error with choices field
tagged with: django

http://stackoverflow.com/comment/86571531
comment on: http://stackoverflow.com/a/49777573
type: AnswerComment
score: 1
has text: @Vineet With `zip`, memory should not be an issue in this case.
type: Comment

http://stackoverflow.com/comment/86732458
has text: I already tried that and it gives the same error.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49843361
score: 0

http://stackoverflow.com/comment/86669443
score: 2
has text: Will `print(df1)` not work? or you may need `from IPython.display import display` ? Also, are you getting any error?
type: Comment
comment on: http://stackoverflow.com/q/49826909
type: QuestionComment

http://stackoverflow.com/q/49869046
tagged with: python-3.x
type: UnansweredQuestion
tagged with: oracle-database
has body: I am writing a program where I am able to add a bread to an Oracle 11g database. The code I've got so far allows me to add the ID manually but it SHOULD auto increment when added so not needing the ID. BreadID = int(input("Enter the bread ID: ")) Name = input("Please enter the name for the new bread: ") LoafPrice = int(input("Enter the price in pence: ")) Calories = int(input("Enter the calories: ")) cur.execute("INSERT INTO BREAD VALUES (:BID,:BName,:BCal,:BPrice)",{'BID':BreadID, 'BName':Name, 'BPrice':LoafPrice, 'BCal':Calories,}) con.commit() This is the code I have for manually adding it. I've searched online for the answer how to add auto increment but all have failed to provide me with errors and more problems. I have seen online that just leaving the ID column out will allow auto increment but I get this 'ORA-00947: not enough values' even though I've specified the column names. Any help is appreciated as I have been stuck on this for a while now.:)
tagged with: python
has comment: http://stackoverflow.com/comment/86753552
has answer: http://stackoverflow.com/a/49869132
score: 0
tagged with: sql
has title: SQL Auto-increment ID python
answer count: 1
has comment: http://stackoverflow.com/comment/86753587
tagged with: oracle11g
type: Question

http://stackoverflow.com/q/49892030
has comment: http://stackoverflow.com/comment/86799847
has comment: http://stackoverflow.com/comment/86800189
tagged with: python
has body: How do I get this game to end when the input is no without going back to the top and looping through or getting an error code? Note I put "End" in so that it would not iterate again import random it's a simple guessing game that I want to start over if yes but end if no def main(): y_games = 2 for y in range(y_games): play_guessingGame_() def play_guessingGame_(): guessesTaken = 0 print('Hello Friend,\n') print('What is your name?\n') name = input() print(name + ' ,It is good to meet you!\n') print("Let's play a game!\n ") print('I am thinking of a number between 1 and 10. . . what is my number?\n') try: answer = random.randint(1,10) while guessesTaken &lt; 5: print("Start guessing!\n") guess = input() guess = int(guess) guessesTaken = guessesTaken + 1 if guess &gt; answer: print('Too high! Try again!\n') elif guess &lt; answer: print('Too low! Try again!\n') elif guess == answer: break while guess == answer: guessesTaken = str(guessesTaken) if guessesTaken == str(1): print('AND ON THE FIRST TRY!!! IMPRESSIVE!!!!') print('There is no beating you\n') break if guessesTaken &gt; str(1): print('Good job! You guessed my number in ' + guessesTaken + ' guesses') print('There is no beating you\n') break if guess != answer: print("I'm sorry, you have run out of guess.\n") print('Better luck next time!\n') except ValueError: print('Please enter whole numbers only') print('\nDo you want to try again? ') response = input() if response == 'yes': print("Great! Let's do this!") if response == 'no': print('\nWell, all good things must come to end!') Exit main()
type: Question
tagged with: python-3.x
upvote count: 0
downvote count: 2
has answer: http://stackoverflow.com/a/49892388
has title: How do I get this game to end when the input is no without going back to the top?
has comment: http://stackoverflow.com/comment/86799665
type: UnansweredQuestion
score: -2
answer count: 1
favorite count: 0

http://stackoverflow.com/q/49790580
upvote count: 10
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53510105
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/35606172
has body: I am using Apache Beam in Python with Google Cloud Dataflow (2.3.0). When specifying the worker_machine_type parameter as e.g. n1-highmem-2 or custom-1-6656, Dataflow runs the job but always uses the standard machine type n1-standard-1 for every worker. Does anyone have an idea if I am doing something wrong? Other topics (here and here) show that this should be possible, so this might be a version issue. My code for specifying PipelineOptions (note that all other options do work fine, so it should recognize the worker_machine_type parameter): def get_cloud_pipeline_options(project): options = { 'runner': 'DataflowRunner', 'job_name': ('converter-ml6-{}'.format( datetime.now().strftime('%Y%m%d%H%M%S'))), 'staging_location': os.path.join(BUCKET, 'staging'), 'temp_location': os.path.join(BUCKET, 'tmp'), 'project': project, 'region': 'europe-west1', 'zone': 'europe-west1-d', 'autoscaling_algorithm': 'THROUGHPUT_BASED', 'save_main_session': True, 'setup_file': './setup.py', 'worker_machine_type': 'custom-1-6656', 'max_num_workers': 3, } return beam.pipeline.PipelineOptions(flags=[], **options) def main(argv=None): args = parse_arguments(sys.argv if argv is None else argv) pipeline_options = get_cloud_pipeline_options(args.project_id pipeline = beam.Pipeline(options=pipeline_options)
has answer: http://stackoverflow.com/a/49811037
accepted answer: http://stackoverflow.com/a/49889746
has title: worker_machine_type tag not working in Google Cloud Dataflow with python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49889746
linked to: http://stackoverflow.com/q/45211277
possible better answer: http://stackoverflow.com/a/49811037
score: 10
tagged with: apache-beam
tagged with: python
tagged with: google-cloud-dataflow

http://stackoverflow.com/comment/86792812
comment on: http://stackoverflow.com/q/49887395
score: 0
type: Comment
type: QuestionComment
has text: Forgot to revoke I realized its not duplicate once I dig more into this.

http://stackoverflow.com/q/49818592
type: UnansweredQuestion
tagged with: pip
tagged with: python
has body: Is it possible to execute some (Python) code whenever I call pip install my_module? Specifically, I have a wheel containing all the modules as well as the __init__.py file and would like to type pip install my_module after which the package gets installed and then some other code is executed.
has comment: http://stackoverflow.com/comment/86653121
has title: Executing code while using pip install
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86652213
has answer: http://stackoverflow.com/a/49818664
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86651888

http://stackoverflow.com/comment/86583248
score: 0
type: Comment
type: AnswerComment
has text: Oh you can further simplify the code. I SEE!!! Thanks Roushan45!!!
comment on: http://stackoverflow.com/a/49782727

http://stackoverflow.com/comment/86748907
type: Comment
score: 0
has text: If 5000 reows take 10 minutes there is either something very wrong with your database configuration or (more likely) the problem is not really with JDBC writer. How do you create `df_name`?
comment on: http://stackoverflow.com/q/49866323
type: QuestionComment

http://stackoverflow.com/q/49912069
score: -1
has comment: http://stackoverflow.com/comment/86840033
has answer: http://stackoverflow.com/a/49912145
type: Question
has comment: http://stackoverflow.com/comment/86839994
has comment: http://stackoverflow.com/comment/86839960
downvote count: 2
has title: Split text in pandas table
upvote count: 1
has comment: http://stackoverflow.com/comment/86840031
has comment: http://stackoverflow.com/comment/86840026
has body: I have a pandas table like this: ID | Tag 1 | up down 2 | right-left 3 | summerfivehigh 4 | up a right b left I have a pandas series with the following words (note that 'fivehigh' is intentionally missing): up, down, right, left, summer I want to split out the rows for IDs based on the words in the series, like so: ID | Tag 1 | up 1 | down 2 | right 2 | left 3 | summer 3 | fivehigh 4 | up 4 | a 4 | right 4 | b 4 | left Essentially I want to "split" tags if a piece of text they contain appears in the series.
answer count: 1
accepted answer: http://stackoverflow.com/a/49912145
favorite count: 0
has comment: http://stackoverflow.com/comment/86839931
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86840116
tagged with: pandas
has comment: http://stackoverflow.com/comment/86839912
has comment: http://stackoverflow.com/comment/86839858
tagged with: python

http://stackoverflow.com/a/49781584
type: Answer
answers question: http://stackoverflow.com/q/49781559
score: 2
downvote count: 0
has body: json_data = {"window_string": "X=-10 H=30 Y=20 W=40"} print(json_data["window_string"].split()) #Use str.split() Output: ['X=-10', 'H=30', 'Y=20', 'W=40']
upvote count: 2

http://stackoverflow.com/comment/86667794
score: 0
comment on: http://stackoverflow.com/q/49814367
type: Comment
type: QuestionComment
has text: Even though you say it's hacky... could you indulge me and tell me how one would go about using this "inspect trick"? ;)

http://stackoverflow.com/q/49825857
has body: I decided to try using classes to recreate a game so that I do not have to use global variables but when I try to run the game I'm getting an error. Traceback (most recent call last): File "D:\Users\James\Desktop\botmod OOP\index.py", line 203, in &lt;module&gt; Game.New_Game(Root) File "D:\Users\James\Desktop\botmod OOP\index.py", line 18, in New_Game Play_Button = self.Start_Canvas.create_window(300, 325, window = Play_Button) File "C:\Users\James\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py"&gt;, line 2501, in create_window return self._create('window', args, kw) File "C:\Users\James\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py"&gt;, line 2474, in _create *(args + self._options(cnf, kw)))) _tkinter.TclError: bad window path name ".!button" I have looked through this to the best of my ability and cannot workout alone what the error is. Below is my code I can provide all the code if needed just comment. It should create a Tkinter button then apply it to the canvas but it gives me the error above. def New_Game(self, Root): self.Start_Canvas = Canvas(Root, width = 600, height = 500, bd=0, highlightthickness=0, bg = '#ffffff') self.Start_Canvas.pack() Title = self.Start_Canvas.create_text(300, 163, text = "BOTMOD", font = ('Cinema Gothic BTN Shadow', 75, 'normal')) Gen_PButton = Button(text = "PLAY", width = 10, font=('Arial', 15), command = self.Play_Game) Play_Button = self.Start_Canvas.create_window(300, 325, window = Gen_PButton) Gen_EButton = Button(text = "EXIT", width = 10, font=('Arial', 15), command = lambda: self.Game_End("EXIT")) Exit_Button = self.Start_Canvas.create_window(300, 375, window = Gen_EButton) Before I used oop, this worked using Global variables and Functions so I cannot find what is causing the issue as the button is defined. The Example Code is Below from tkinter import * from random import choice, shuffle class Game: def __init__(self): self.Playing_Game = True self.Game_Paused = False self.Restart_Game =…
has comment: http://stackoverflow.com/comment/86667547
has comment: http://stackoverflow.com/comment/86667610
score: 9
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49862936
has comment: http://stackoverflow.com/comment/86684486
tagged with: tkinter
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/86675820
favorite count: 0
has comment: http://stackoverflow.com/comment/86667575
type: Question
upvote count: 9
has answer: http://stackoverflow.com/a/49862936
has title: I get the error _tkinter.TclError: bad window path name ".!button" and i'm not sure why
has comment: http://stackoverflow.com/comment/86667651
tagged with: oop
has comment: http://stackoverflow.com/comment/86669153
has comment: http://stackoverflow.com/comment/86667569
tagged with: python
has comment: http://stackoverflow.com/comment/86667545
has comment: http://stackoverflow.com/comment/86687957
has comment: http://stackoverflow.com/comment/86667631

http://stackoverflow.com/q/49862839
favorite count: 0
type: Question
has title: youtube-dl is not merging audio and video when embedded in Python Script
has body: I am attempting to download the highest quality audio and video of a particular YouTube video from within a Python script. My code is pretty straight forward: import youtube_dl ydl_opts = { 'format': 'bestvideo[width&gt;=1920]/bestvideo+bestaudio/best', 'outtmpl': 'test.mp4', } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc']) The format line was taken from this question. The problem I'm encountering is that the downloaded result has no audio component. The video component works as expected. The console output doesn't seem to indicate that audio is downloaded either. C:\Dev&gt;py youtube_test.py [youtube] BaW_jenozKc: Downloading webpage [youtube] BaW_jenozKc: Downloading video info webpage [youtube] BaW_jenozKc: Extracting video information [download] Destination: test.mp4 [download] 100% of 2.11MiB in 00:00 Why am I not getting the audio component over the test video and how can I solve that? I am running on Windows 10. I have ffmpeg installed and in my path. C:\Dev&gt;ffmpeg -version ffmpeg version N-90721-g783df2eb59 Copyright (c) 2000-2018 the FFmpeg developers built with gcc 7.3.0 (GCC) configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-bzlib --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth libavutil…
upvote count: 5
tagged with: python
score: 4
tagged with: youtube-dl
linked to: http://stackoverflow.com/q/31631535
accepted answer: http://stackoverflow.com/a/49865949
possible better answer: http://stackoverflow.com/a/71835757
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49865949
has answer: http://stackoverflow.com/a/71835757
downvote count: 1

http://stackoverflow.com/a/49812435
upvote count: 0
has body: You have done the __str__ method wrong. This code might solve your issue. from django.db import models class Album(models.Model): artist = models.CharField(max_length=100) album_title = models.CharField(max_length=250) genre = models.CharField(max_length=50) album_logo = models.CharField(max_length=1000) def __str__(self): return self.album_title + ' - ' + self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) def __str__(self): return self.song_title
answers question: http://stackoverflow.com/q/49809314
downvote count: 1
type: Answer
score: -1

http://stackoverflow.com/comment/86784621
score: 0
comment on: http://stackoverflow.com/q/49884154
has text: I just need to get localhost:8080 when I split user:pass and local:host via the @
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86655271
comment on: http://stackoverflow.com/q/49820153
score: 1
type: Comment
type: QuestionComment
has text: Possible duplicate of [How to set the current working directory?](https://stackoverflow.com/questions/1810743/how-to-set-the-current-working-directory)

http://stackoverflow.com/comment/86620071
comment on: http://stackoverflow.com/q/49802662
type: QuestionComment
type: Comment
has text: ...it'd also be interesting to determine whether this is fork or execv overhead -- if the former, perhaps your use case calls for a prefork pool or similar, in which case you might consider using [Celery](http://www.celeryproject.org/) for a 3rd-party-maintained, pre-optimized job pool implementation.
score: 0

http://stackoverflow.com/comment/86609527
comment on: http://stackoverflow.com/a/49797466
score: 0
type: Comment
has text: see my comment, it will fail because it's not a valid json (I don't think I deserve -1).... not because my code is not working, in any case I'm trying to create something to make it work with this not valid json....
type: AnswerComment

http://stackoverflow.com/q/49798358
has comment: http://stackoverflow.com/comment/86611506
accepted answer: http://stackoverflow.com/a/58892663
tagged with: python
has answer: http://stackoverflow.com/a/58892663
has title: Get position of float in an increasing sequence
has body: Suppose given a ndarray t = [t_0, t_1, ..., t_p] of p+1 real numbers different and sorted. I have another ndarray (bigger) T = [T_0, T_1, ..., T_N] of N+1 real numbers that all belong to [t_0, t_p]. What I want is the array [i_0, i_1, ..., i_N] of the (uniquely defined) indices i_j such that T_j belongs to [t_i_j, t_i_{j+1}[. I can make things such that T would be sorted as well, if it helps. I would imagine that such a basic operation could be part of the numpy library, but I cannot seem to find it.
type: AnsweredQuestion
tagged with: numpy
score: 1
has comment: http://stackoverflow.com/comment/86611624
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/49893521
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49884826
has body: This behaviour occurs when the database is in WAL mode, and when your program does something to prevent the database from doing automatic checkpoints. Either use a different journal mode, or fix the wal_autocheckpoint setting, or fix your program so that it does not leak active transactions/cursors.
type: Answer
has comment: http://stackoverflow.com/comment/86828712

http://stackoverflow.com/a/49909283
has comment: http://stackoverflow.com/comment/86840615
has comment: http://stackoverflow.com/comment/86839113
type: Answer
has comment: http://stackoverflow.com/comment/86860767
has body: You seem to have two different problems here but they may be related. Since you gave a traceback for the Permission Denied error on C:\Todolist2.xlsx, let's look at that one. On Windows, many programs, when they open a file, put a lock on it. This is especially true for "applications" programs, like Excel and Notepad. If one program has a file locked, any another program that tries to open that file to overwrite it will get a permissions error. And that's exactly what you're seeing: The first time through, your code overwrites Todolist2.xslx, then uses startfile to tell Excel (or some application that's registered for Excel files) to open it, which works. Then it tries to overwrite the same file, which Excel presumably still has locked and open, which fails. Depending on what you're actually trying to do here, there are a few possible workarounds: Copy Todolist2.xlsx to a temporary file, then start that temporary. Create new files Todolist2.xlsx, Todolist2-1.xlsx, etc., and keep opening them. Use either COM automation or a GUI scripting framework like autogui to make Excel open a copy of the file rather than opening the file itself. Use either of the above to make Excel close the file before overwriting the file and launching it. Launch a new Excel instance to open the file using subprocess.Popen, so you can kill it and launch a new one. Rewrite your whole code to build the spreadsheet using Excel COM automation, rather than by building a file to pass to it.
score: 0
answers question: http://stackoverflow.com/q/49908361

http://stackoverflow.com/comment/86540739
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49762540
has text: @zwer that's actually the answer
score: 0

http://stackoverflow.com/q/49785742
tagged with: string
favorite count: 0
score: 2
type: AnsweredQuestion
has body: I have a df as below: Index Site Name 0 Site_1 Tom 1 Site_2 Tom 2 Site_4 Jack 3 Site_8 Rose 5 Site_11 Marrie 6 Site_12 Marrie 7 Site_21 Jacob 8 Site_34 Jacob I would like to strip the 'Site_' and only leave the number in the "Site" column, as shown below: Index Site Name 0 1 Tom 1 2 Tom 2 4 Jack 3 8 Rose 5 11 Marrie 6 12 Marrie 7 21 Jacob 8 34 Jacob What is the best way to do this operation?
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49785934
tagged with: python
has answer: http://stackoverflow.com/a/49785934
has answer: http://stackoverflow.com/a/49785784
has answer: http://stackoverflow.com/a/49785806
type: Question
has title: How to strip the string and replace the existing elements in DataFrame
upvote count: 2
answer count: 5
has answer: http://stackoverflow.com/a/49786012
has answer: http://stackoverflow.com/a/49785787
downvote count: 0
possible better answer: http://stackoverflow.com/a/49785784

http://stackoverflow.com/comment/86563572
type: Comment
comment on: http://stackoverflow.com/a/49774300
type: AnswerComment
has text: No. *Have you copied and pasted my code exactly?* I don't think you have.
score: 0

http://stackoverflow.com/a/49767532
has comment: http://stackoverflow.com/comment/86551048
has comment: http://stackoverflow.com/comment/86590482
score: 2
answers question: http://stackoverflow.com/q/49767101
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: In Python '&amp;' has higher precedence than '==' so We are getting the wrong result Try this: if (a==b) &amp; (a==20): print "a is equal to b" else: print "a is not equal to b"
accepted answer of: http://stackoverflow.com/q/49767101
type: Answer

http://stackoverflow.com/a/49876499
answers question: http://stackoverflow.com/q/49875544
has body: Instead of drawing the contours themselves you need to find the bounding box around the largest contour. Find the largest contour and draw the bounding box using cv2.boundingRect() : x,y,w,h = cv2.boundingRect(cnt) cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) where cnt is the largest contour in the image and the 4 corners of the rectangle are x, y, x+w, y+h Check out the bounding rectangle section given in this LINK to help you out.
type: Answer
score: 0

http://stackoverflow.com/q/49853247
has comment: http://stackoverflow.com/comment/86721415
score: 0
type: UnansweredQuestion
answer count: 1
has body: I was trying to replicate the following scrapy tutorial - http://blog.florian-hopf.de/2014/07/scrapy-and-elasticsearch.html. I get the following error trace while running the spider- [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2018-04-16 14:00:41 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023 2018-04-16 14:00:41 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying &lt;GET http://www.meetup.com/robots.txt&gt; (failed 1 times): [&lt;twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.&gt;] 2018-04-16 14:00:41 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying &lt;GET http://www.meetup.com/robots.txt&gt; (failed 2 times): [&lt;twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.&gt;] 2018-04-16 14:00:41 [scrapy.downloadermiddlewares.retry] DEBUG: Gave up retrying &lt;GET http://www.meetup.com/robots.txt&gt; (failed 3 times): [&lt;twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.&gt;] 2018-04-16 14:00:41 [scrapy.downloadermiddlewares.robotstxt] ERROR: Error downloading &lt;GET http://www.meetup.com/robots.txt&gt;: [&lt;twisted.python.failure.Failure twisted.internet.error.ConnectionDone: Connection was closed cleanly.&gt;] Traceback (most recent call last): File "D:\anaconda\lib\site-packages\twisted\internet\defer.py", line 1384, in _inlineCallbacks result = result.throwExceptionIntoGenerator(g) File "D:\anaconda\lib\site-packages\twisted\python\failure.py", line 393, in throwExceptionIntoGenerator return g.throw(self.type, self.value, self.tb) File "D:\anaconda\lib\site-packages\scrapy\core\downloader\middleware.py", line 43, in process_request defer.returnValue((yield download_func(request=request,spider=spider))) Can someone kindly help me fix/understand the issue.
tagged with: url
tagged with: web-scraping
tagged with: scrapy
has answer: http://stackoverflow.com/a/49854207
type: Question
tagged with: python
has title: Scrapy - unable to hit the URL for webscraping

http://stackoverflow.com/comment/86700266
type: AnswerComment
has text: @ThomasGrainger That is a good point. As always with performance, things depend on the settings, and YMMV.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49842339

http://stackoverflow.com/a/50706154
answers question: http://stackoverflow.com/q/49887968
upvote count: 2
score: 2
downvote count: 0
type: Answer
has body: Downgrade your Pillow version to 5.0.0 pip install --force-reinstall Pillow==5.0.0

http://stackoverflow.com/q/49773059
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/35624662
has answer: http://stackoverflow.com/a/64781690
has answer: http://stackoverflow.com/a/49773925
type: AnsweredQuestion
score: 3
answer count: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/49773925
favorite count: 0
tagged with: parsing
type: Question
possible better answer: http://stackoverflow.com/a/49773725
has answer: http://stackoverflow.com/a/49773725
has title: How to extract tables names in a SQL script?
has body: Assuming there is a sql script: select * from ( select col1 from test.test_a join test.test_a1 on a.col1 = a1.col1) a left join test.test_b b on a.col1 = b.col2 left join test.test_c c on b.col2 = c.col3 left jon (select col4 from test.test_d) d on c.col3 = d.col4 I am reading this question and tring to extract all TABLE NAMES after 'from' or 'join' in the script above using python. The difficuty is I am processing the script line by line, but the table name and the key word may be NOT in the same line. So how to extract such table names from the script? Any suggestion is appreciated.

http://stackoverflow.com/q/49860136
tagged with: numpy
score: 0
has answer: http://stackoverflow.com/a/49860446
tagged with: random
has body: Consider the following random function which returns nearly the same number it received (it returns a sample from the Gaussian distribution with mean x and standard deviation of 0.001 * x): def similar(x, rel_std=0.001): sigma = rel_std * x mu = x return sigma * np.random.randn() + mu So for example: &gt; print(similar(1.0)) 0.99946018 This function seems to be applicable to arrays of arbitrary shape: &gt; ones = np.ones(5) &gt; print(similar(ones)) [0.99946018 0.99946018 0.99946018 0.99946018 0.99946018] &gt; example = np.array([[[6,7,8,9,10],[-1,-2,-3,-4,-5]],[[1,2,3,4,5], [-2,-1,0,1,2]]]) &gt; print(similar(example)) [[[ 6.00610123 7.0071181 8.00813497 9.00915185 10.01016872] [-1.00101687 -2.00203374 -3.00305062 -4.00406749 -5.00508436]] [[ 1.00101687 2.00203374 3.00305062 4.00406749 5.00508436] [-2.00203374 -1.00101687 0. 1.00101687 2.00203374]]] However, as you might have noticed, it does not use for every cell a new random seed. What I am looking for is a function which uses randomness for every cell of an arbitrarily shaped NumPy array. Since the shape may be of any kind, I think nested for-loops are not usable. An additional requirement is that the approach should work reasonably fast even for arrays of shape (1024, 1024). Is there a way of writing a fast (e. g. by vectorizing) function performing the mentioned task? EDIT: I don't mind to change the definition of similar, or to use a function of different interface – as long as the suggestion fits the purpose of producing a »similar« matrix.
answer count: 1
accepted answer: http://stackoverflow.com/a/49860446
type: Question
type: AnsweredQuestion
has title: Python: Replace every value in a NumPy array with a similar one
tagged with: python

http://stackoverflow.com/q/49883236
answer count: 4
has comment: http://stackoverflow.com/comment/86783826
has answer: http://stackoverflow.com/a/77993689
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49887868
has comment: http://stackoverflow.com/comment/86783124
downvote count: 0
has comment: http://stackoverflow.com/comment/86782717
tagged with: pandas
has comment: http://stackoverflow.com/comment/86783953
has answer: http://stackoverflow.com/a/62754084
possible better answer: http://stackoverflow.com/a/62754084
has comment: http://stackoverflow.com/comment/86783972
has body: I have 2 fixed width files like below (only change is Date value starting at position 14). sample_hash1.txt GOKULKRISHNA 04/17/2018 ABCDEFGHIJKL 04/17/2018 111111111111 04/17/2018 sample_hash2.txt GOKULKRISHNA 04/16/2018 ABCDEFGHIJKL 04/16/2018 111111111111 04/16/2018 Using pandas read_fwf I am reading this file and creating a Dataframe by excluding the Date value and loading only the first 13 characters. My dataframe looks like this import pandas as pd df1 = pd.read_fwf("sample_hash1.txt", colspecs=[(0,13)]) df2 = pd.read_fwf("sample_hash2.txt", colspecs=[(0,13)]) df1 GOKULKRISHNA 0 ABCDEFGHIJKL 1 111111111111 ... df2 GOKULKRISHNA 0 ABCDEFGHIJKL 1 111111111111 ... Now I am trying to generate a hash value on each Dataframe, but the hash is different for df1 and df2. I'm not sure what's wrong with this. Can someone throw some light on this please? I have to identify if there is any change in data between the files (excluding the Date columns). print(hash(df1.values.tostring())) -3571422965125408226 print(hash(df2.values.tostring())) 5039867957859242153 I am loading these files into a table (each full file is around 2 GB size). Every time we are receiving full files from source. Sometimes there is no change in the data (excluding the last column, Date). My idea is to reject such files. If I can generate a hash on the file and store it somewhere (in a table) next time I can compare the new file hash value with the stored hash. I thought this is the right approach but I got stuck with hash generation. I checked this post Most efficient property to hash for numpy array but that is not what I am looking for.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86786180
has answer: http://stackoverflow.com/a/49887868
has answer: http://stackoverflow.com/a/76365130
tagged with: hash
has comment: http://stackoverflow.com/comment/86783627
has title: How to generate a Hash or checksum value on Python Dataframe (created from a fixed width file)?
has comment: http://stackoverflow.com/comment/86786014
upvote count: 18
score: 18
linked to: http://stackoverflow.com/q/16589791
tagged with: python
has comment: http://stackoverflow.com/comment/86782567

http://stackoverflow.com/a/49912492
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49911771
upvote count: 1
has comment: http://stackoverflow.com/comment/86881011
type: Answer
has body: Somewhere in your code you need to create an instance of Culpture. You need to use that instance to call show_frame. When you do that, the instance will be automatically passed as the self parameter, and the argument you pass will be frame_name. culpture = Culpture(root) ... culpsure.show_frame(fsignin) You didn't show where you create the instance of Culpture so it's hard to be any more specific than that.

jquery
tags question: http://stackoverflow.com/q/49814863
tags question: http://stackoverflow.com/q/49799549
type: Tag
tag name: jquery
tags question: http://stackoverflow.com/q/49867703
tags question: http://stackoverflow.com/q/49794347
tags question: http://stackoverflow.com/q/49885711
tags question: http://stackoverflow.com/q/49888314
tags question: http://stackoverflow.com/q/49851316
tags question: http://stackoverflow.com/q/49852552
tags question: http://stackoverflow.com/q/49804663
tags question: http://stackoverflow.com/q/49867966
tags question: http://stackoverflow.com/q/49893574
tags question: http://stackoverflow.com/q/49773300

http://stackoverflow.com/comment/86582511
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49781435
has text: I also modified as like as follows path= os.readlink(filename) with open(path) as f: data= f.read() still not able to read with built-in read method

http://stackoverflow.com/comment/86733918
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49859467
has text: Because you are returning the string `"None"` and not `None`. Change the code in the else to `average=None` and it should work.
type: Comment

http://stackoverflow.com/comment/86768754
has text: @JacquesGaudin Hi Jacques, thanks for pointing me to that thread; unfortunately, I'm not a very advanced programmer, and I don't understand what the OP meant by "removing of the python 3.6.4 x32, removing of the virtual environment and recreating it with new python 3.6.4 x64" Would you mind explaining how to remove the virtual env and recreating it with python 3.6.4 x64?
comment on: http://stackoverflow.com/q/49859885
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49901842
has comment: http://stackoverflow.com/comment/88271172
type: Answer
has body: It turns out that indeed, through some backend magic, pathos prevents multiple instances of the same type of pool to be initialized. To prevent leakage, one can do at the end of each iteration thispool.terminate() thispool.restart()
score: 5
upvote count: 5
downvote count: 0
answers question: http://stackoverflow.com/q/49888485

http://stackoverflow.com/q/49889620
has answer: http://stackoverflow.com/a/49889717
has body: I am working on a basic shapes program in Python and can't seem to work out my code. I need to keep it simple using while loops and the variables given, nested loops are usable. Here is my code for a square: def drawSquare(size, drawingChar): print('Square: ') row = 1 while row &lt;= size: # Output a single row drawRow(size, drawingChar) # Output a newline to end the row print() # The next row number row = row + 1 print() It is supposed to print like: x x x x based on a size and character entered by the user. drawRow is another function similar to drawSquare: def drawRow(size, drawingChar): col = 1 while col &lt;= size: print(drawingChar, end=' ') col = col + 1
has comment: http://stackoverflow.com/comment/86795591
tagged with: diagonal
downvote count: 0
answer count: 3
upvote count: 1
tagged with: python
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/86795784
has answer: http://stackoverflow.com/a/49890628
has comment: http://stackoverflow.com/comment/86795455
type: Question
has answer: http://stackoverflow.com/a/49889754
has comment: http://stackoverflow.com/comment/86795903
has comment: http://stackoverflow.com/comment/86795458
has title: Diagonal shape in Python using while loops
score: 1
has comment: http://stackoverflow.com/comment/86795717

http://stackoverflow.com/q/49905403
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49905435
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/49905435
type: Question
has title: Python ValueError: time data '2001-11-03 ' %Y:%m %d %H:%M:%S' when dates in csv file are month/day/year
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
tagged with: python
accepted answer: http://stackoverflow.com/a/49905455
has body: I'm having an issue where the date format is not matching up. Meaning in my .csv file the dates are as follows %m/%d/%Y (ex. 11/3/2001) but in the error it saying %Y/%m/%d or %Y/%d/%m. I've tried all the possible permutations as far as year, month and day and I continue to recieve the same error of ValueError: time data '2001-11-03 ' %Y:%m %d %H:%M:%S'. Below is my code. Thanks. df = pd.read_excel('.xlsx', header=None) df.to_csv('.csv', header=None, index=False) df= pd.read_csv('.csv', index_col[5,8,9,12], date_parser=lambda x: datetime.datetime.strptime(x, '%Y/%m/$d %H:%M:%S').strptime('%m/%d/%Y)) Note: What I'm trying to do is convert an .xlsx file to .csv and then remove the trailing 0:00 from multiple columns within the .csv file. Hope this helps.
tagged with: datetime-format
has answer: http://stackoverflow.com/a/49905455

http://stackoverflow.com/q/49865586
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: CloseSpider: Failing to Close spider
answer count: 0
score: 1
downvote count: 0
upvote count: 1
tagged with: scrapy
has body: I want to stop the spider if the page throws captcha. Hence, I wrote the following code to the my custom Downloader Middleware as shown below. def process_response(self, request, response, spider): title = response.xpath('//title/text()').extract_first() if title == 'Robot Check': print('CAPTCHA THROWWWEEED') raise CloseSpider('Closing Spider...') else: return response My spider: I removed some parts class GoToPageSpider(scrapy.Spider): name = 'gotopage' allowed_domains = ["www.amazon.com"] start_urls = ['https://www.amazon.com'] def __init__(self): .... def parse(self, response): yield Request(response.url, callback=self.start_crawling) def start_crawling(self, response): for isbn in self.queue_results: link = self.link + isbn yield Request(link, callback=self.parse_book, meta={'ISBN':isbn}) def parse_book(self, response): isbn = response.meta['ISBN'] title = response.xpath('//*[@id="productTitle"]/text()').extract_first() if title: title = title.split("(")[0] rank = '' rank = response.xpath('//*[@id="SalesRank"]/text()').extract() if rank: yield {'ISBN': isbn, 'RANK': rank, 'TITLE': title} def close(self, spider, reason): .... PROBLEM: Although I see there 'Closing Spider...' message, it does not stop the spider. I also wrote raise CloseSpider('Closing Spider...') code in the spider. This time, it does not even show the message. Here is the traceback that I receive. I see that I also got During handling of the above exception, another exception occurred: error. ERROR: Error downloading &lt;GET https://www.amazon.com/dp/0486460169&gt; Traceback (most recent call last): File "c:\users\hp\pycharmprojects\amazon_v1\venv\lib\site-packages\twisted\internet\defer.py", line 1386, in _inlineCallbacks result = g.send(result) File "c:\users\hp\pycharmprojects\amazon_v1\venv\lib\site-packages\scrapy\core\downloader\middleware.py", line 43, in process_request defer.returnValue((yield download_func(request=request,spider=spider))) File "c:\users\hp\pycharmprojects\amazon_v1\ven…
favorite count: 0
type: Question

http://stackoverflow.com/comment/86677967
comment on: http://stackoverflow.com/q/49831320
type: QuestionComment
has text: You might attract more help by focusing on the "minimal" part of a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve).
type: Comment
score: 2

http://stackoverflow.com/comment/86601441
comment on: http://stackoverflow.com/a/49793438
type: Comment
has text: Thanks @Rajesh Yogeshwar for your inputs
score: 0
type: AnswerComment

http://stackoverflow.com/comment/86744011
score: 0
has text: Didn't notice till it was giving me errors, need to finish with `y=y[0]` to make it an actual matrix, or remove the 1 in the shape parameter. Is there a reason you added it?
type: AnswerComment
comment on: http://stackoverflow.com/a/49862579
type: Comment

http://stackoverflow.com/a/62713320
downvote count: 0
answers question: http://stackoverflow.com/q/49863789
upvote count: 7
type: Answer
has body: You can do it using css: %%html lbl = widgets.Label(value= 'Test' ) # lbl = widgets.HTMLMath(value= 'Test' ) # Alternate way using HTMLMath lbl.add_class('lbl_bg') hBox = widgets.HBox([lbl],layout=Layout(justify_content= 'flex-end')) hBox.add_class("box_style") Output :
has comment: http://stackoverflow.com/comment/114409315
score: 7

http://stackoverflow.com/q/49845774
has answer: http://stackoverflow.com/a/49845800
type: AnsweredQuestion
upvote count: 0
has body: Im importing from the pycountries module and trying to just print out a list of all the listed countries but I can figure it out. My test code is: from pycountry import countries for num in range(0,len(countries)): print(countries[num]) Which spits out a list of all the country objects (I'll list one for example). Country(alpha_2='AO', alpha_3='AGO', name='Angola', numeric='024', official_name='Republic of Angola') I've tried looking at listed dir methods and tried things like: print(countries[num][name]) What am I doing wrong? How to I pull specific things like the name or the alpha_2 from the object. Thanks for any help and sorry for the probably stupid question.
answer count: 1
downvote count: 1
favorite count: 0
has title: How can I pull specific attributes from a Python3 module?
type: Question
tagged with: python
tagged with: module
accepted answer: http://stackoverflow.com/a/49845800
score: -1

http://stackoverflow.com/comment/86838384
comment on: http://stackoverflow.com/q/49911206
type: Comment
type: QuestionComment
score: 0
has text: ... `min` and `max` are your friend? Is that want you wanted?

http://stackoverflow.com/comment/86741068
type: Comment
type: AnswerComment
has text: @Roushan: The tags say 3.x.
comment on: http://stackoverflow.com/a/49862949
score: 0

http://stackoverflow.com/comment/86630151
type: QuestionComment
comment on: http://stackoverflow.com/q/49807541
type: Comment
has text: Do you want each item to be unique, or the combination of all of them together?
score: 0

http://stackoverflow.com/q/49792127
upvote count: 1
favorite count: 0
has title: How to fix "Error: Please select a valid Python interpreter" in Pycharm?
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/60558139
downvote count: 5
tagged with: python
has body: Error: Error: Please select a valid Python interpreter Screenshot: How to fix this?
has answer: http://stackoverflow.com/a/64949327
answer count: 3
tagged with: pycharm
has answer: http://stackoverflow.com/a/49792225
score: -4

http://stackoverflow.com/a/49821712
has body: Confirm that within the folder, the models have another init and the one that correctly enters the file that contains the class Try it , : class ProductTemplate(models.Model): _inherit = 'product.template' remise = fields.Float('remise du fournisseur', size=10, required=True) marge = fields.Float('marge', size=10, required=True) total_reste = fields.Float('Reste', size=10, required=True) P.d: The _columns attribute is from old api v7
has comment: http://stackoverflow.com/comment/86763534
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49779590
has comment: http://stackoverflow.com/comment/86767918

http://stackoverflow.com/comment/86797543
has text: @weathergirl at which line? edit your answer and include the full error message please.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49890879
type: Comment

http://stackoverflow.com/comment/86893316
type: AnswerComment
has text: ooh god, i forgot to close. now i get output.
score: 0
comment on: http://stackoverflow.com/a/49924498
type: Comment

http://stackoverflow.com/a/56158605
answers question: http://stackoverflow.com/q/49768770
score: 1
downvote count: 0
upvote count: 1
has body: Or simply the required library just isn't in the repo. I'm Python newbie and all advices about upgrading pip finally shown as misleading. I had just to look into https://pypi.org/ , finding the library (airflow in my case) stopped at some old version, after which it was renamed. Yes, also that silly solution is also possible :-).
type: Answer

http://stackoverflow.com/a/49886452
accepted answer of: http://stackoverflow.com/q/49886311
type: Answer
answers question: http://stackoverflow.com/q/49886311
has comment: http://stackoverflow.com/comment/86789488
has body: Yes, because the file context is also an iterator: with open(filename, 'r') as f: for l1, l2 in zip(f, f): # ... do something with l1 and l2 This is the shortest and most pythonic way afaik.
has comment: http://stackoverflow.com/comment/86789573
type: AcceptedAnswer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/86789405
has comment: http://stackoverflow.com/comment/86789341
has comment: http://stackoverflow.com/comment/86789206
has comment: http://stackoverflow.com/comment/86789269
has comment: http://stackoverflow.com/comment/86789389
downvote count: 0

http://stackoverflow.com/comment/86670616
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49827567
has text: The type is never a string but a class.
score: 5

http://stackoverflow.com/q/49905530
has answer: http://stackoverflow.com/a/49954060
has comment: http://stackoverflow.com/comment/86826987
has comment: http://stackoverflow.com/comment/86827321
tagged with: python
has comment: http://stackoverflow.com/comment/86831362
has title: Selenium doesn't load the complete page
score: 0
has comment: http://stackoverflow.com/comment/86830144
tagged with: screen-scraping
type: AnsweredQuestion
answer count: 1
tagged with: selenium
type: Question
accepted answer: http://stackoverflow.com/a/49954060
has body: I'm trying to scrape this site: https://www.lobstersnowboards.com/shop/eiki-pro-model--459 And one of the fields I want to get is the available models: But this part is not getting loaded by selenium: I had tried with both, firefox and chrome, getting the same result.

http://stackoverflow.com/q/49887084
has answer: http://stackoverflow.com/a/49887195
linked to: http://stackoverflow.com/q/5893163
possible better answer: http://stackoverflow.com/a/49887184
has answer: http://stackoverflow.com/a/49887264
upvote count: 1
has answer: http://stackoverflow.com/a/49887184
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49887154
has body: My program generates a random string with a random amount of letters from 10 to 20. def program(): import random import sys x=['q','w','e','r'] y=random.randint(10,20) for t in range (0,y): w=random.randint(0,3) e=x[w] sys.stdout.write(e) The program will print a random string like 'wwwweewwqqrrrrwwqqeeqqww'. How would I store this string as a variable?
has answer: http://stackoverflow.com/a/49887154
has comment: http://stackoverflow.com/comment/86790290
downvote count: 0
has comment: http://stackoverflow.com/comment/86790401
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/49887344
type: AnsweredQuestion
has title: How to assign the result of a for loop to a variable in Python
has comment: http://stackoverflow.com/comment/86790379
has answer: http://stackoverflow.com/a/49887231
score: 1

http://stackoverflow.com/comment/86849089
comment on: http://stackoverflow.com/a/49916240
score: 1
has text: I agree. It seems to me since queryset is being filtered sequentially. I mean, since first one returned empty, the next ones received empty. Can you try changing the order of fields and then check the output?
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/86768414
type: QuestionComment
comment on: http://stackoverflow.com/q/49875889
type: Comment
has text: Both scrips are working fine when you execute them individually?
score: 1

http://stackoverflow.com/comment/86824513
comment on: http://stackoverflow.com/a/49866515
type: Comment
type: AnswerComment
score: 1
has text: The x input is the data that the sequences are generated from. Think of it as a sliding window, capturing multiple values of X for each Y that will be predicted. So you input X values without a window, and the output is a window of X values representing the X values leading up to Y value that's being predicted.

http://stackoverflow.com/a/49904235
has body: Check this out all(item in B.items() for item in A.items()) Hope it will help you!!
downvote count: 0
upvote count: 5
score: 5
answers question: http://stackoverflow.com/q/49904181
type: Answer

http://stackoverflow.com/q/49868611
answer count: 1
has answer: http://stackoverflow.com/a/49869339
has body: I have df1 and df2. for each element in df1 I want to check if it exist in df2 and print df3 df1=['c_1', 'd_1', 'f_1', 'h_1', 'i_1', 'n_1', 'v_1', 'm_1'] df2=[['lia', 'f_1', 'n_1', 'v_1'], ['eli', 'f_1', 'n_1', 'v_1', 'm_1']] I want an output like this: df3=[('f_1', {'lia': 1}), ('n_1', {'lia': 1}), ('v_1', {'lia': 1}), ('c_1', {'lia': 0}), ('d_1', {'lia': 0}), ('h_1', {'lia': 0}), ('i_1', {'lia': 0}), ('m_1', {'lia': 0}), ('f_1', {'eli': 1}), ...] I tried some iterations but it didn't work. here is my code. def st_pl(line, df1): ln=line st=df1 l = ln[0] if l: dict_l = {l: 1} if not l: dict_l = {l: 0} li_st = [] size = len(ln) for i in range(1, size): tup = (ln[i], dict_l) li_st.append(tup) return li_st
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86752780
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86752847
tagged with: python
tagged with: dictionary
has title: Make complex dictionary from two arrays of keys
downvote count: 4
has comment: http://stackoverflow.com/comment/86753091
upvote count: 0
score: -4

http://stackoverflow.com/a/49821432
has body: I think I was a little quick to post the question, but I hope this might help others come up with other ideas on how to troubleshoot a similar issue. In my src/models.py file where I keep my models, you must make sure that your models are defined correctly. Since Flask-SQLAlchemy is a wrapper around the SQLAlchemy you must use the data types under the db object. Essentially, I had my models defined as such: class Task(db.Model): __tablename__ = 'tasks' id = Column(Integer, primary_key=True) task_id = Column(String) name = Column(String) created_at = Column(DateTime, default=datetime.datetime.now) As you can see, I was inheriting from db.Model instead of the return value of declarative_base(). I also needed to add the db. in front of all the data types, including Column, Integer, String, Float, DateTime, relationship, and ForeignKey. So, I was able to fix my issue by changing my model to something like: class Task(db.Model): __tablename__ = 'tasks' id = db.Column(db.Integer, primary_key=True) task_id = db.Column(db.String) name = db.Column(db.String) created_at = db.Column(db.DateTime, default=datetime.datetime.now) See: Documentation on declaring Flask-SQLAlchemy models
score: 1
has comment: http://stackoverflow.com/comment/86658903
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49820972

http://stackoverflow.com/comment/86784411
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/49884154
type: Comment
has text: It seems unlikely that you're unable to modify the snippet that you currently have to access the second part. If you don't understand that line well enough to do that, I'd recommend a structured tutorial e.g. https://docs.python.org/3/tutorial/.

http://stackoverflow.com/comment/86715833
type: QuestionComment
type: Comment
score: 0
has text: @Wen I already have one column in the try.csv file and I would like to add another one with the data from 'list1'. The number of elements in both the columns are same.
comment on: http://stackoverflow.com/q/49844685

http://stackoverflow.com/comment/86889405
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49924498
type: AnswerComment
has text: @Hitesh Sorry, I partly misread your question. The two checks are necessary because one checks that the number of datasets (paths) is the same. The other loops over all paths to check that their names are identical.

http://stackoverflow.com/comment/86729072
score: 0
type: Comment
has text: Even when I do 'return render_template('index.html', form1=form1, num=num, classify=Classify)' and change everything in index.html to reflect this eg: '{{ form2.csrf_token }}' I still get jinja2.exceptions.UndefinedError: 'form2' is undefined
type: AnswerComment
comment on: http://stackoverflow.com/a/49856803

mleap
type: Tag
tags question: http://stackoverflow.com/q/49860969
tag name: mleap

http://stackoverflow.com/q/49832506
type: Question
accepted answer: http://stackoverflow.com/a/49832663
answer count: 1
has comment: http://stackoverflow.com/comment/86680270
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49832663
has body: I'm adding pagination on my website. This is my function: views.py def ProductList(request, category_slug=None, page_number=1): content = {} category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) current_page = Paginator(products, 2) content['category'] = category content['categories'] = categories content['products'] = current_page.page(page_number) return render(request, 'product/list.html', content) urls.py urlpatterns = [ url(r'^$', views.ProductList, name='ProductList'), url(r'^page/(\d+)/$', views.ProductList, name='ProductList'), url(r'^(?P&lt;category_slug&gt;[-\w]+)/$', views.ProductList, name='ProductListByCategory'), url(r'^(?P&lt;id&gt;\d+)/(?P&lt;slug&gt;[-\w]+)/$', views.ProductDetail, name='ProductDetail'), ] But every time I'm trying to get next page I see this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/page/2/ Raised by: shop.views.ProductList I can't really understand what I'm doing wrong. Thank you.
tagged with: pagination
has comment: http://stackoverflow.com/comment/86680355
has title: Django function doesn't return HTML page

runtime-error
tags question: http://stackoverflow.com/q/49916252
tags question: http://stackoverflow.com/q/49829627
type: Tag
tag name: runtime-error

http://stackoverflow.com/q/49860061
tagged with: python
type: UnansweredQuestion
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49860315
downvote count: 0
has title: Converting xlsx to csv Dates in wrong column
answer count: 1
favorite count: 0
type: Question
has body: I'm trying to convert an xlsx file to csv. My pieced together code works, the only issue I'm running into is that when the date conversion happens they are placed in column 1 when the dates are in column 5. I'm at a loss as to what am I doing wrong? Any advice/examples? def xlsx2csv (): wb = xlrd.open_workbook('.xlsx', '.csv' ) sh = wb.sheet_by_index(0) file = open('.csv', 'wb') csv_out = unicodecsv.writer(, encoding = 'utf-8') for row_number in range(sh.nrows): date = sh.row_values(row_number)[5] if isinstance(date, float) or isinstance(date, int): year, month, day, hour, minute, sec = xlrd.xldate_as_tuple(date,0) py_date = "%2d/%2d/%04"% (month, day, year) wr.writerow[py_date] + sh.row_vlaues(row_number)[0:]) else: wr.writerow([py_date] + sh_row_values(row_number)[0:]) file.close() xlsx2csv()
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/86742222
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49863183
score: 0
has text: You can use `timeit` to check.

http://stackoverflow.com/a/49909548
upvote count: 2
has body: In your __init__.py you only have cel. You don't have an object called celery in your __init__ file, so it can't be imported to some other file. You can try from app import cel.˛ EDIT: in __init__ you from .ctasks import subtaskcaller, make_celery but in ctasks you import cel from app (which doesn't exist yet at that point, only Flask, request, and SocketIO exist at that point in time). So you need to put your @cel decorated functions in yet another script, which you can import all the way at the bottom of __init__
type: AcceptedAnswer
score: 2
answers question: http://stackoverflow.com/q/49909363
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49909363

http://stackoverflow.com/comment/86817320
type: AnswerComment
has text: That's true, it might be more robust.
type: Comment
comment on: http://stackoverflow.com/a/49900913
score: 0

http://stackoverflow.com/a/49905254
type: Answer
has comment: http://stackoverflow.com/comment/94270144
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/94003597
answers question: http://stackoverflow.com/q/49854842
has body: Assuming you have already installed plotly using $ pip install plotly the following should be sufficient to get you started. This is currently working in my Jupyter Notebook to plot offline. import plotly.offline as py import plotly.graph_objs as go py.init_notebook_mode(connected=True) # Initialise offline ploytly environment Follow along with one of their simple scatter plots to check everything is working. using py.iplot will display the plot as an output within your notebook, while py.plot will display the plot in a new tab.

http://stackoverflow.com/comment/86748246
type: QuestionComment
has text: And please format your code properly. Python indentation is important!
score: 0
comment on: http://stackoverflow.com/q/49866370
type: Comment

http://stackoverflow.com/q/49869373
has comment: http://stackoverflow.com/comment/86754941
possible better answer: http://stackoverflow.com/a/49869473
accepted answer: http://stackoverflow.com/a/49869406
tagged with: tuples
has comment: http://stackoverflow.com/comment/86754063
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86754934
has answer: http://stackoverflow.com/a/49869406
has comment: http://stackoverflow.com/comment/86754108
tagged with: python
linked to: http://stackoverflow.com/q/252703
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
has body: I'm trying to return all the dates that match with the traffic intensity in the function below but am getting all the elements of only the first tuple as a list instead of all tuples that match. def traffic_intensity(count): """Returns string indicating intensity level given by number of vehicles""" level_name = "" if(count &lt; 5000): level_name = "Very Low" elif(count &gt;= 5000 and count &lt; 10000): level_name = "Low" elif(count &gt;= 10000 and count &lt; 18000): level_name = "Moderate" elif(count &gt;= 18000): level_name = "High" return(level_name) def dates_with_intensity(vehicle_records, intensity): """Returns number of days with the given traffic intensity level""" new_list = [] for number in vehicle_records: date_count = number[0] number_count = number[1] traffic = traffic_intensity(number_count) if traffic == intensity: new_list += date_count return new_list For the test data vehicle_records = [('2010-01-01',1), ('2010-01-02',2), ('2010-01-03',3)] days = dates_with_intensity(vehicle_records, 'Very Low') print(days) I am supposed to be getting ['2010-01-01', '2010-01-02', '2010-01-03'] but instead am getting ['2', '0', '1', '0', '-', '0', '1', '-', '0', '1'] Can someone please help me with this?
answer count: 2
has title: returning date with traffic intensity from tuples in a list
has answer: http://stackoverflow.com/a/49869473
has comment: http://stackoverflow.com/comment/86754915
downvote count: 0
score: 4

http://stackoverflow.com/q/49821374
has answer: http://stackoverflow.com/a/49841648
accepted answer: http://stackoverflow.com/a/49841648
has title: Invoking a Ruby program using Python and filename parameter
tagged with: python
has body: I am creating a tool that creates a UI in python using flask. One of the tools functions is to allow a user to upload a CSV file to be processed by a API script. The API is written in Ruby. How can I pass the data from the python program to the ruby script and possibly return some information about how the data was processed back to the python program to display to the user? Some hypotheses I had but could use clarification on if they are possible include: passing the filename as a parameter and invoke the ruby program Creating a local file(s) to be asynchronously read (and possibly written to by both programs)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86658646
answer count: 1
type: Question
score: 0

http://stackoverflow.com/q/49891116
has comment: http://stackoverflow.com/comment/86797834
has title: Python: How do I parallelize a job that compares two lists?
type: Question
has comment: http://stackoverflow.com/comment/86797872
type: UnansweredQuestion
has body: I have two lists and need to compare and calculate element by element. As these lists get larger, performance is suffering. Someone recommended breaking one of the lists into N sections and running the comparison in parallel. How do I run these in parallel? key={} #compare each list, element by element for i in range(len(list1)): for j in range(len(list2)): matched = False try: matched = match_function(list[i]['typeforma'], list[i]['typeformb'],list[j]['typeforma'], list[j]['typeformb'], ) except: print("Error",i,j) if matched: # store two matches in the dictionary key[list2[j]['id']]=list1[i]['identifier'] break; j+=1 i+=1
tagged with: python
tagged with: parallel-processing
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49891246
has comment: http://stackoverflow.com/comment/86798130
answer count: 1

http://stackoverflow.com/a/50466186
has body: You need this from tensorflow.python.keras import Sequential you should use keras api implemented in tensorflow instead of using keras api directly.
has comment: http://stackoverflow.com/comment/101094138
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/101193601
has comment: http://stackoverflow.com/comment/97041128
score: 2
answers question: http://stackoverflow.com/q/49801891

http://stackoverflow.com/q/49763568
favorite count: 0
type: Question
tagged with: interpolation
tagged with: numpy
downvote count: 0
upvote count: 1
tagged with: python
has title: Using scipy.interpolate.RegularGridInterpolator get an error "There are 100 point arrays, but values has 2 dimensions"
has body: I know that there is a post explaining how to do it, but I think I followed the steps outlined in the post and still got a dimensional error. This is what I tried: import numpy as np from scipy.interpolate import RegularGridInterpolator x = np.linspace(0,1,100) y = x ** 2 f = RegularGridInterpolator(x,y) What I did is exactly the same as what the linked post does. However, I'm still getting the same error: There are 100 point arrays, but values has 2 dimensions Is that because I'm dealing with 1 dimensional data? Greatly appreciated if I can get a pointer on this.
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/30056577
accepted answer: http://stackoverflow.com/a/49763979
score: 1
has answer: http://stackoverflow.com/a/49763979
answer count: 1
tagged with: scipy

math
tags question: http://stackoverflow.com/q/49790974
tags question: http://stackoverflow.com/q/49864149
tags question: http://stackoverflow.com/q/49830644
tags question: http://stackoverflow.com/q/49785753
type: Tag
tags question: http://stackoverflow.com/q/49882469
tags question: http://stackoverflow.com/q/49852207
tags question: http://stackoverflow.com/q/49765279
tags question: http://stackoverflow.com/q/49825417
tags question: http://stackoverflow.com/q/49784499
tags question: http://stackoverflow.com/q/49818392
tags question: http://stackoverflow.com/q/49864714
tags question: http://stackoverflow.com/q/49779981
tags question: http://stackoverflow.com/q/49908354
tag name: math
tags question: http://stackoverflow.com/q/49816671
tags question: http://stackoverflow.com/q/49885332
tags question: http://stackoverflow.com/q/49900087
tags question: http://stackoverflow.com/q/49865057
tags question: http://stackoverflow.com/q/49811904

http://stackoverflow.com/comment/86618360
type: AnswerComment
has text: hi, thanks for the help. I have tried the advice you gave me, and it works! and i tried use these code `url(r'^category/(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'),` `url(r'^product/(?P<product_slug>[-\w]+)/$', views.product_detail, name='product_detail'),`
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49801422

http://stackoverflow.com/comment/86708268
score: 0
has text: I have recorded a little clip showing you that it works with the latest version of terminator (1.0): https://www.youtube.com/watch?v=5d494o9K4WA Must be a client side setting then I guess.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49846439

css
tags question: http://stackoverflow.com/q/49843159
tags question: http://stackoverflow.com/q/49802395
tags question: http://stackoverflow.com/q/49824504
tags question: http://stackoverflow.com/q/49873194
tags question: http://stackoverflow.com/q/49884143
tags question: http://stackoverflow.com/q/49909996
tags question: http://stackoverflow.com/q/49819328
tags question: http://stackoverflow.com/q/49806805
tag name: css
tags question: http://stackoverflow.com/q/49783892
type: Tag
tags question: http://stackoverflow.com/q/49794878

http://stackoverflow.com/comment/86785263
comment on: http://stackoverflow.com/a/49882699
type: Comment
score: 0
type: AnswerComment
has text: I've tested the code and it works fine. Make sure your client_id, client_secret and user_agent are correct. Quick start guide here: https://praw.readthedocs.io/en/latest/getting_started/quick_start.html

http://stackoverflow.com/comment/86842544
comment on: http://stackoverflow.com/q/49912851
score: 0
type: Comment
type: QuestionComment
has text: from the histogram2d documentation : x : array_like, shape (N,) An array containing the x coordinates of the points to be histogrammed. y : array_like, shape (N,) , but it seems your x and y shapes are (10,10)

http://stackoverflow.com/comment/86755383
type: QuestionComment
comment on: http://stackoverflow.com/q/49865057
score: 0
type: Comment
has text: @pault I dunno, it's conceivable that x contains time/date objects and arithmetic operations have been defined on such objects. The trapezoid rule is just some simple arithmetic so it's plausible that it could return another time/date object. Of course the units should be units(y) times time but if y has no units associated with it, the units of the result will just be time. Of course more info is needed. I guess what I'm saying is that it might "accidentally" be correct ... it might.

http://stackoverflow.com/comment/86772365
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49866323
has text: _everything goes smoothly (taking only few seconds)_ - because everything before you call an action is lazy. Nothing happens there.
score: 0

http://stackoverflow.com/q/49877370
type: UnansweredQuestion
has body: For the below code how I can make parallel lines with a specified distance. given first line points A(0,7) B(5,2) Second line(3,2) import matplotlib.pyplot as plt import math import numpy as np x=[0, 7] y=[5, 2] plt.plot(x,y) o = np.subtract(2, 7) q = np.subtract(5, 0) slope = o/q #(m,p) are the new coordinates to plot the parallel line m = 3 p = 2 axes = plt.gca() x_val = np.array(axes.get_xlim()) y_val = np.array(slope*(x_val - m) + p) plt.plot(x_val,y_val, color="black", linestyle="--") plt.show()
tagged with: python
has title: Drawing parallel lines using Python?
has comment: http://stackoverflow.com/comment/86770662
has comment: http://stackoverflow.com/comment/86771006
has answer: http://stackoverflow.com/a/49878619
has comment: http://stackoverflow.com/comment/86770490
score: 2
has comment: http://stackoverflow.com/comment/86771109
upvote count: 3
tagged with: matplotlib
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86770772

http://stackoverflow.com/comment/86754110
type: AnswerComment
comment on: http://stackoverflow.com/a/49868296
score: 0
type: Comment
has text: cool, and something like this: result 123.456.789-123

http://stackoverflow.com/a/49914814
upvote count: 1
answers question: http://stackoverflow.com/q/49914567
accepted answer of: http://stackoverflow.com/q/49914567
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/86846394
has body: Most Simplest and easiest way is to iterate through each row of the dataframe using iterrows(), Check this updated code: @app.route('/inner', methods=['GET', 'POST']) def inner(): name = request.form['name'] password = request.form['password'] if name == "" or password == "": return render_template('index.html'); else: # Reading the file everytime will degrade the function performance df = pd.read_csv("login.csv", sep=',', encoding="utf-8") for index,row in df.iterrows(): if row['name'] == name and row['password'] == password: print('sucess') return render_template('inner.html'); else: return render_template('index.html');
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49807004
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86628897
has title: Sorting a csv given a key set python
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86628887
tagged with: python
answer count: 2
has answer: http://stackoverflow.com/a/49807076
tagged with: pandas
score: 2
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/86628868
has body: I have a csv file that needs to be ordered with a specific order of names. e.g the order key is [David, Paul, Harry, John] column1 of the csv is however : Harry David John Paul And I need to order the csv so column1 is David Paul John Harry How can I do this in pandas.
downvote count: 0
has answer: http://stackoverflow.com/a/49807185

http://stackoverflow.com/comment/86640581
comment on: http://stackoverflow.com/a/49806266
type: AnswerComment
score: 1
has text: Well this is indeed the answer. I have also updated my repository with this answer thanks!
type: Comment

http://stackoverflow.com/comment/86701784
type: QuestionComment
comment on: http://stackoverflow.com/q/49843479
has text: Does the zip contain `setup.py` at the top-level? I suspect there is a top-level subdirectory that prevents the zip to be pip-installable.
score: 0
type: Comment

http://stackoverflow.com/comment/86646313
type: Comment
has text: This is the code I am using and its giving me an error:
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49814422

http://stackoverflow.com/a/49823164
type: Answer
has comment: http://stackoverflow.com/comment/116286719
has comment: http://stackoverflow.com/comment/112918865
downvote count: 0
answers question: http://stackoverflow.com/q/49822874
score: 16
upvote count: 16
has body: Here is a way to use pandas.io.json.json_normalize(): from pandas.io.json import json_normalize df = df.join(json_normalize(df["e"].tolist()).add_prefix("e.")).drop(["e"], axis=1) print(df) # e.k1 e.k2 #0 v1 v2 #1 v3 v4 #2 v5 v6 However, if you're column is actually a str and not a dict, then you'd first have to map it using json.loads(): import json df = df.join(json_normalize(df['e'].map(json.loads).tolist()).add_prefix('e.'))\ .drop(['e'], axis=1)

http://stackoverflow.com/q/49904801
tagged with: python-requests
downvote count: 1
has comment: http://stackoverflow.com/comment/86825858
has comment: http://stackoverflow.com/comment/86828124
has comment: http://stackoverflow.com/comment/86827472
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/86826653
has comment: http://stackoverflow.com/comment/86825736
score: 1
has comment: http://stackoverflow.com/comment/86828297
answer count: 1
accepted answer: http://stackoverflow.com/a/49909791
has answer: http://stackoverflow.com/a/49909791
favorite count: 0
has body: I am trying to download few videos from list of links. Every line in text file is one link. When I try to download all videos in loop, only first one is working. Videos are from 60 - 100 MB. Loop continues afterwards, but files are empty. Thank you for help. def download(): name = 'video' a = 1 with open('download.txt') as f: lines = f.readlines() for line in lines: url = line response = requests.get(url, stream=True) name = name + str(a) filename = name + '.mp4' with open(filename, 'wb') as f: f.write(response.content) a = a + 1
has comment: http://stackoverflow.com/comment/86825877
type: Question
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/86825503
has comment: http://stackoverflow.com/comment/86835154
has comment: http://stackoverflow.com/comment/86836205
has title: Download multiple files in Python loop, only first works
tagged with: python

http://stackoverflow.com/comment/86692590
comment on: http://stackoverflow.com/q/49838416
score: 0
has text: `data.keys()` will contain a list of keys. You can loop over `range(len(data.keys()))` to get current and next keys
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86581900
comment on: http://stackoverflow.com/a/49783240
score: 14
has text: what if I have a lot of otherstuff columns? Should I loop through all other columns and create a dictionary ?
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49822424
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has title: How to apply a time windows of 1 second and moving forwards of 250 ms to a pandas dataframe
score: 0
has comment: http://stackoverflow.com/comment/86660975
answer count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/86660687
has comment: http://stackoverflow.com/comment/86660837
has body: I would like to build an array of dataframe portions where each portion is obtained by rolling a pandas dataframe with a time windows of one 1 seconds but sliding forwards every 250 millisecond. DF: time, ax, ay, az, id 2018-01-24 13:43:58.700, 0.021973, 0.012283, -0.995468, 1 2018-01-24 13:43:58.711, 0.021072, 0.013779, -0.994308, 1 2018-01-24 13:43:58.721, 0.020157, 0.015717, -0.995575, 1 2018-01-24 13:43:58.733, 0.017883, 0.012756, -0.993927, 1 ... 2018-01-24 13:43:59.700, 0.021194, 0.012161, -0.994705, 1 2018-01-24 13:43:59.712, 0.019638, 0.013718, -0.994019, 0 2018-01-24 13:43:59.721, 0.019440, 0.010803, -0.994476, 0 ... 2018-01-24 13:44:00.700, 0.018112, 0.010849, -0.993073, 0 2018-01-24 13:44:00.712, 0.011154, 0.010849, -0.994644, 0 2018-01-24 13:44:00.721, 0.020340, 0.010040, -0.995804, 0 ... As output, I am expecting an array of dataframe portions as follows: DF1 that starts 2018-01-24 13:43:58.700 DF1 that ends 2018-01-24 13:43:59.700 DF2 that starts 2018-01-24 13:43:58.950 DF2 that ends 2018-01-24 13:43:59.950 etc.. My attempt is to apply the following line of codes: df["ephoc_as_datatime"] = pd.to_datetime(df["ephoc_as_datatime"]) # Convert column type to be datetime indexed_df = df.set_index(["ephoc_as_datatime"]) # Create a datetime index print(indexed_df.rolling(100)) # Then apply functions to rolling windows How Can I say move forwards of 250ms? How I can take each portion and put it in an array? Any help would be very appreciated. Many Thanks in advance Carlo
type: Question

http://stackoverflow.com/comment/86691093
comment on: http://stackoverflow.com/a/49837937
type: AnswerComment
score: 0
has text: What do you mean? What function am I trying to call? Right now I'm just trying to print a string to get it working.
type: Comment

http://stackoverflow.com/comment/86654583
type: QuestionComment
comment on: http://stackoverflow.com/q/49800726
score: 0
has text: Using the code in `cplex._internal._procedural` is not supported and is subject to change at any time. In my comment above, I'm asking you to show the code using the public API that you think is slow.
type: Comment

http://stackoverflow.com/comment/86801000
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49892258
has text: hey chrisz can you help me how to overwrite in that file

http://stackoverflow.com/comment/86674734
score: 0
type: QuestionComment
type: Comment
has text: Ty. That solves my Problem. Tyvm
comment on: http://stackoverflow.com/q/49829212

http://stackoverflow.com/a/50650506
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49776224
type: Answer
has body: So, what I was planning to do was not ideal . . Apache Tika requires to scan physical files to fetch metadata. I made a bridge and started from sessions pulling files to the server Tika code was hosted.
answers question: http://stackoverflow.com/q/49776224
score: 0

http://stackoverflow.com/a/49866486
answers question: http://stackoverflow.com/q/49866458
has body: You can use re.findall with \W: inputs = [':boy', '_144-', '_1445', '_1445', 'alpha', 'monkey', '#sdakm', '.file', '.magic'] final_inputs = list(filter(lambda x:re.findall('[\W_]', x), inputs)) Output: [':boy', '_144-', '_1445', '_1445', '#sdakm', '.file', '.magic']
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/86748894
type: Answer

http://stackoverflow.com/a/49866738
upvote count: 1
downvote count: 1
has body: If you are trying to find the total sum for each path, create a dictionary storing the values for each action: frontier = [{'path': ['PULL'], 'state': (2, 5, 4, 3, 0, 1)}, {'path': ['SWAP', 'PULL'], 'state': (2, 4, 5, 0, 3, 1)}, {'path': ['SWAP'], 'state': (2, 5, 4, 0, 1, 3)}, {'path': ['PUSH', 'PUSH'], 'state': (2, 0, 5, 4, 3, 1)}] actions = {'PUSH': 5, 'PULL': 6, 'SWAP': 8, 'FLIP': 2} final_dict = [{**b, **{'path':sum(actions.get(i) for i in b['path'])}} for b in frontier] Output: [{'state': (2, 5, 4, 3, 0, 1), 'path': 6}, {'state': (2, 4, 5, 0, 3, 1), 'path': 14}, {'state': (2, 5, 4, 0, 1, 3), 'path': 8}, {'state': (2, 0, 5, 4, 3, 1), 'path': 10}] For the condensed result: print([i['path'] for i in final_dict]) Output: [6, 14, 8, 10]
type: Answer
answers question: http://stackoverflow.com/q/49866677
score: 0

http://stackoverflow.com/a/49846462
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49846434
has body: It seems need merge with left join: yp = B'x1', 'x2'.merge(A, how='left') print (yp) x1 x2 y 0 0 2 0.002255 1 1 7 0.006804 2 1 9 -0.000391
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49846434
type: Answer
has comment: http://stackoverflow.com/comment/86707968
has comment: http://stackoverflow.com/comment/86707959
upvote count: 2

http://stackoverflow.com/q/49906918
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49906971
has answer: http://stackoverflow.com/a/49906971
answer count: 1
tagged with: scikit-learn
tagged with: python
score: 2
type: AnsweredQuestion
has body: I'm using movie_reviews data and using countvectorizer in it. I want to change it in dictionary for showing the unique words in index as you see the code below: from sklearn.feature_extraction.text import CountVectorizer import nltk cv = CountVectorizer(tokenizer=nltk.word_tokenize , stop_words='english') movie_train_cv = cv.fit_transform(movie_train.data) movie_train_cv.vocabulary_ AttributeError: vocabulary not found. At last line ,I get the error. Please let me know what is the correct syntax. I want like that. sents = ['A rose is a rose is a rose is a rose.', 'Oh, what a fine day it is.', "It ain't over till it's over, I tell you!!"] #sents turned into sparse vector of word frequency counts sents_counts = foovec.fit_transform(sents) #foovec now contains vocab dictionary which maps unique words to indexes foovec.vocabulary_ here is the output of this code: {'a': 4, 'rose': 14, 'is': 9, '.': 3, 'oh': 12, ',': 2, 'what': 17, 'fine': 7, 'day': 6, 'it': 10, 'ai': 5, "n't": 11, 'over': 13, 'till': 16, "'s": 1, 'i': 8, 'tell': 15, 'you': 18, '!': 0}
has title: AttributeError: vocabulary not found
upvote count: 3

http://stackoverflow.com/comment/86777655
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49880880
type: AnswerComment
has text: No idea what made the difference, but it is now working, thank you :)

http://stackoverflow.com/a/49858625
type: Answer
has body: If you want in one iteration then you can try this approach: vowels = ['a','e','i','o','u'] consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] letter_number_pairs = {'a': 1,'b': 8,'c': 3,'f': 3,'h': 8,'i': 2,'l': 4,'p': 2,'q': 1,'s': 5,'u': 9,'w': 0,'y': 5,'z': 2} vowel_sum=[] conso_sum =[] for i in letter_number_pairs: if i in vowels: vowel_sum.append(letter_number_pairs[i]) elif i in consonants: conso_sum.append(letter_number_pairs[i]) else: pass #in case of special characters print(sum(vowel_sum)) print(sum(conso_sum)) output: 12 41
score: 1
has comment: http://stackoverflow.com/comment/86732304
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49857765

http://stackoverflow.com/q/49793212
favorite count: 0
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/86602115
has body: This is my first Tkinter program I am writing from scratch. I've done tutorials on Tkinter, but am really still a newbie to it. Thanks for your patience. I'm creating a 'Binary Helper' for my students in Tkinter, but I'm partially stuck with the part where I am trying to concatenate string values to display in a label. When I click one of the 'bit' buttons, it should automatically update the 'on/off' image, display '0' or '1' in a label, display the bit value in another label. It does all those things correctly, but when it should also display the 'combined' binary value at the top in a different label, it works ok when 'switching' them 'on' one at a time, but when I 'switch' it off AND any other value is 'on' it displays the binary value at the top as all being 'off' i.e. '00000000' instead of the actual binary value... FIY: I know I haven't coded the 'denary' value yet...I shall do so after this problem is solved. Any ideas, advice or help is greatly appreciated. Here's my code so far... #Binary Helper with OOP - edujo (11/04/2018) #Version 6 from tkinter import * from PIL import Image, ImageTk tk = Tk() tk.title("Binary Helper") tk.configure(bg = "blue") #Ensure that window can't be resized tk.resizable(0,0) #Place the window on top of all other windows tk.wm_attributes("-topmost", 1) #Images On/Off on = "On.png" off = "Off.png" class Buttons(): """Binary Helper""" def __init__(self, btnRow=1, btnColumn=1, bitVal="0", bitRow=1, bitColumn=1, binVal="0", binRow=1, binColumn=1, imgFile=off, imgRow=8, imgColumn=1): self.btnRow = btnRow self.btnColumn = btnColumn self.bitVal = bitVal self.bitRow = bitRow self.bitColumn = bitColumn self.binVal = binVal self.binRow = binRow self.binColumn = binColumn self.imgFile = imgFile self.imgRow = imgRow self.imgColumn = imgColumn def switching(self, event): #Switching binVal 0/1 if self.binVal == "1": self.binLbl.configure(text = "0") self.binVal = "0" self.imgFile = Image.open(off) self.imgFile = ImageTk.PhotoImage(self.imgFile)…
has answer: http://stackoverflow.com/a/49793917
type: Question
tagged with: binary
has comment: http://stackoverflow.com/comment/86602370
tagged with: tkinter
has title: Can't fully update label with concatenated strings in Python Tkinter
type: UnansweredQuestion
answer count: 1
upvote count: 1
tagged with: string
downvote count: 1

http://stackoverflow.com/comment/86659689
score: 1
type: QuestionComment
has text: It doesn't look like QPython actually has docstrings.
type: Comment
comment on: http://stackoverflow.com/q/49822079

http://stackoverflow.com/q/49842547
accepted answer: http://stackoverflow.com/a/49842769
has body: For example, I have this 2d array: [ [ 0.0, 0.24320757858085434, 0.14893361727523413, 0.29786723455046826, 0.18838778030301612, 0.12160378929042717 ], [ 0.23717478210768014, 0.0, 0.16770789675478251, 0.20539938644228997, 0.25981195646349819, 0.1299059782317491 ], [ 0.21681956134183847, 0.250361664212574, 0.0, 0.23178986094050727, 0.16390018248131957, 0.13712873102376066 ], [ 0.2933749527592357, 0.20744741852633861, 0.15681550844086434, 0.0, 0.18554661183269694, 0.15681550844086434 ], [ 0.20305810393286577, 0.28716752453162431, 0.12135042758887897, 0.20305810393286577, 0.0, 0.18536584001376513 ], [ 0.17877693623386351, 0.19584032147389943, 0.13848001934394774, 0.23407395508684939, 0.25282876786143976, 0.0 ] ] which gives sets of probabilities. How can I find the best probability of each row? And also is there any way to find for example the 2nd, 3rd best probability without changing the elements' positions?
has comment: http://stackoverflow.com/comment/86699981
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49842613
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/17906949
has comment: http://stackoverflow.com/comment/86700394
linked to: http://stackoverflow.com/q/6422700
favorite count: 0
tagged with: numpy
has answer: http://stackoverflow.com/a/49843594
possible better answer: http://stackoverflow.com/a/49842613
has comment: http://stackoverflow.com/comment/86764329
type: Question
has answer: http://stackoverflow.com/a/49842769
tagged with: arrays
linked to: http://stackoverflow.com/q/34835951
tagged with: python
upvote count: 6
score: 6
tagged with: python-2.7
has title: How to find the max of each row in 2d arrays?
tagged with: list

http://stackoverflow.com/a/49859875
has comment: http://stackoverflow.com/comment/86737349
score: 12
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49859625
downvote count: 0
has comment: http://stackoverflow.com/comment/86737129
has body: You simply need to assign the difference between y and model.predict(x) to a new column (or take absolute value if you just want the magnitude if the difference): #df["Distance"] = abs(y - model.predict(x)) # if you only want magnitude df["Distance"] = y - model.predict(x) print(df) # Exam Results Hours Studied Distance #0 93 8.232795 -0.478739 #1 94 7.879095 1.198511 #2 92 6.972698 0.934043 #3 88 6.854017 -2.838712 #4 91 6.043066 1.714063 #5 87 5.510013 -1.265269 #6 89 5.509297 0.736102 This is because your model predicts a y (dependent variable) for each independent variable (x). The x coordinates are the same, so the difference in y is the value you want.
answers question: http://stackoverflow.com/q/49859625
has comment: http://stackoverflow.com/comment/86737703
has comment: http://stackoverflow.com/comment/100581685
upvote count: 12
type: Answer
has comment: http://stackoverflow.com/comment/86736971

http://stackoverflow.com/q/49820562
has comment: http://stackoverflow.com/comment/86717114
has comment: http://stackoverflow.com/comment/86676056
has comment: http://stackoverflow.com/comment/86686718
score: 1
tagged with: gtk3
has body: Is it possible to get a widget just by a value of its property? for example I have a Gtk.Box, which changes during program, but all the time all version of this box have position 2 in parent container. And I must send it as a parameter to function. Certainly, I could make a loop for all elements in container, checking if position ==2 and run function for an item when it is, but I hope there is more elegant way...
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/86676038
answer count: 0
has title: How to get widget by property value in Gtk+ 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86658955
has comment: http://stackoverflow.com/comment/86718270
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/86683304
has comment: http://stackoverflow.com/comment/86683507
tagged with: python
has comment: http://stackoverflow.com/comment/86673088

http://stackoverflow.com/comment/86738933
comment on: http://stackoverflow.com/q/49861233
type: Comment
score: 0
has text: I see that in your template you are looping through `perguntas` and using its `loop.index` you try to access `answers` values, Can you try to print into the console( `print(perguntas);print(answers)`) the content of both variable and post them into your question here?
type: QuestionComment

http://stackoverflow.com/comment/86584821
has text: If you use something like `test = [1,2,3]` for your loops, it works because a list is not an *iterator*, but it is an *iterable*. In that case, each `for` loop implicitly calls `iter` to get a distinct iterator for the list. Your `test` class *is* an iterator, since it defines `__next__`, so each loop uses the same iterator.
score: 0
comment on: http://stackoverflow.com/q/49784629
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86816664
type: AnswerComment
has text: Okay so I solved it using the `copy.deepcopy()` method which creates a copy of an object that can be altered without affecting the original object. But I am still curious about how getter/setter doesn't make sense in Python, if you care how to explain how else I should do it.
score: 0
comment on: http://stackoverflow.com/a/49878275
type: Comment

http://stackoverflow.com/a/49763737
answers question: http://stackoverflow.com/q/49763394
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49763394
has body: Yes, it is impossible -- by design. A JSON serializer is, by nature, supposed to emit only valid JSON. From RFC 8259, emphasis mine: 7. Strings The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks, except for the characters that MUST be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F). Any character may be escaped. If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point. The hexadecimal letters A through F can be uppercase or lowercase. So, for example, a string containing only a single reverse solidus character may be represented as "\u005C". Alternatively, there are two-character sequence escape representations of some popular characters. So, for example, a string containing only a single reverse solidus character may be represented more compactly as "\\". Note the phrase "MUST be escaped" -- "MUST" is a formally-defined term-of-art; something which does not comply with a MUST requirement from the JSON specification is not allowed to call itself JSON. In summary: A string containing only a literal backslash in your data may be encoded in JSON as "\u005c", or "\\". It may not be encoded as "\" (including that character as an unescaped literal).
downvote count: 0
type: Answer
score: 6
upvote count: 6

http://stackoverflow.com/comment/86610940
score: 0
type: AnswerComment
has text: I fixed my code.But I deleted that dtype and worked fine
type: Comment
comment on: http://stackoverflow.com/a/49797251

http://stackoverflow.com/comment/86737109
type: AnswerComment
comment on: http://stackoverflow.com/a/49860067
has text: Thanks. this should do the work.
type: Comment
score: 0